How can I index the dimensions of a nd-array element-wise by using a 2d matrix which entries represent which dimensions (representing slices or 2d Matrices) to take the values from?
I=ones(2)*2;
J=cat(3,I,I*2,I*3);
indexes = [1 3 ; 2 2] ;
so J is
J(:,:,1) =
2 2
2 2
J(:,:,2) =
4 4
4 4
J(:,:,3) =
6 6
6 6
it works easily using 2 for loops
for i=1:size(indexes,1)
for j=1:size(indexes,2)
K(i,j)=J(i,j,indexes(i,j));
end
end
which yields the desired result
K =
2 6
4 4
but is there a vectorized / smart indexing way of doing this?
%K=J(:,:,indexes) --does not work