OK, what this looks like for your output array of B
is that for each location in this output, the corresponding location in A
has a D
-element vector and you want to choose which element to select from this D
-element vector based on the value stored in index
, which is of the same size as B
.
We can achieve this using a combination of meshgrid
and sub2ind
. First use meshgrid
to generate a grid of 3D co-ordinates, which will be the same size as your matrix B
. After, use sub2ind
to determine a set of linear indices to access the fourth dimension of A
. After this, we simply do a straight assignment using the output of sub2ind
, which uses a combination of the output of meshgrid
and index
.
Therefore, try something like this:
[cols,rows,dim] = meshgrid(1:size(A,2), 1:size(A,1), 1:size(A,3));
ind = sub2ind(size(A), rows, cols, dim, index);
B = A(ind);