MATLAB: Sub2ind Get values of 3D matrix using an index array

2d matrix3d matrixmatrixsub2ind

Hi all,
I have a 800x900x7 matrix (matrix M) and a 800×900 2D array (matrix A) whose elements are the indexes i want to obtain from each row and column in matrix M (so each element in array A is a number from 1 to 7).
The final result should be an 800×900 matrix (matrix F) containing the elements in matrix M which matrix A specifies.
Without using a for loop, how am I able to do this? I'm thinking sub2ind, but any help would be greatly appreciated!
Many thanks

Best Answer

[m,n,k] = size(M);
[q,w] = ndgrid(1:m,1:n);
out = M(sub2ind([m,n,k],q,w,A));