MATLAB: Access all k-th elements of a n-dimensional array, where the k indexes are defined in a (n-1)-dimensional array.

array indexingarraysMATLABmultidimensional arrays

I have a 3-dimensional N-by-M-by-L array of values A, e.g.
A(:,:,1) = [1 2 3;
4 5 6;
7 8 9];
A(:,:,2) = [10 11 12;
13 14 15
16 17 18];
I also have a N-by-M matrix containing indexes idx, e.g.
idx = [1 2 1;
2 1 1;
2 2 2];
where the indexes are in the range [1 to L].
I would like to create the N-by-M matrix B such that B(i,j) = A(i,j,idx(i,j)), e.g.
B = [1 11 3;
13 5 6;
16 17 18].
I can see that it could be done easily with nested for loops, but i was wondering if there is a vectorized (and possibly faster) way to achieve this.

Best Answer

>> S = size(A);
>> [R,C,~] = ndgrid(1:S(1),1:S(2),1);
>> X = sub2ind(S,R,C,idx);
>> B = A(X)
B =
1 11 3
13 5 6
16 17 18