MATLAB: Mapping arrays of different dimensions

arrayindexing

Hi there, I have the following 2x2x2 dimensional array A(:,:,1) = [1 2; 3 4] and A(:,:,2) = [5 6; 7 8] and the following 3 vectors of size 1×5 that store indices related to A: i = [1 1 1 2 2], j = [2 2 2 2 2] and k = [1 1 2 2 1].
I would like to obtain a vector B of size 1×5 that stores the entries of A as follows:
B(1,1) = A(i(1), j(1), k(1)), so B(1,1) = A(1,2,1) = 2
B(1,2) = A(i(2), j(2), k(2)), so B(1,2) = A(1,2,1) = 2
B(1,3) = A(i(3), j(3), k(3)), so B(1,3) = A(1,2,2) = 6
And so on… such that in the end B = [2 2 6 8 4],
without using loops.
I hope you can help me with this. Many thanks!

Best Answer

A(:,:,1) = [1 2; 3 4]
A(:,:,2) = [5 6; 7 8]
i = [1 1 1 2 2];
j = [2 2 2 2 2];
k = [1 1 2 2 1];
index = sub2ind(size(A), i, j, k);
B = A(index)