MATLAB: Array indexing with another array in multidimensional matrices

indexingmultidimensional array

Thank you in advance for helping:
I have a multidimensional matrix (let's say 4D as example) and I want to index its values through another matrix which contains all possible combinations, as an example:
A=randi(10,5,4,3,2) %%is 4D matrix
and I want to index its "submatrices" through another vector, without performing for loops. In this specific case my indexing matrix would be:
idx=[1,1;2,1;3,1;1,2;2,2;3,2] %%is indexing matrix
through which I would like to obtain my resulting matrices:
A(:,:,1,1);
A(:,:,2,1);
A(:,:,3,1);
A(:,:,1,2);
A(:,:,2,2);
A(:,:,3,2);
by adding the last two indices with my indexing matrix:
A(:,:,B(1,:));
A(:,:,B(2,:));
A(:,:,B(3,:));
A(:,:,B(4,:));
A(:,:,B(5,:));
A(:,:,B(6,:));
but the two forms don't give the same results and I would like to code a form similar to the last one to obtain the first results, i.e. singe 2D matrices.
Thanks

Best Answer

The issue here is that, when indexing, a vector of numbers acts on a single dimension. When indexing, a comma separates dimensoins, much like in a function you use a comma to separate the different inputs. You are expecting MATLAB to 'know' you want the first column to apply to one dimiension, and the second column to another. Instead, you must explicity state the input for each dimension, separating each with a comma:
A(:,:,B(:,1),B(:,2))