MATLAB: 3d matrix element extraction

matrix index

Given a 10x10x3 matrix, I would like to extract the 3rd dimension for the 5 specific rows and columns, for example:
row indices a=[1 3 5 7 9]
column indices b=[2 4 6 8 10]
And store the result in a 5×3 matrix. How can I achieve this?

Best Answer

[~,~,p]=size(m); % array depth for generality
ix=sub2ind(size(m),repmat(a,1,p),repmat(b,1,p),repmat(1:p,1,length(a))); % doc sub2ind for details
subm=m(ix);
reshape and/or reorder as desired; above will be vector of length p*length(a) in order as in the list of subscript vectors.
ADDENDUM
If you preallocate, I'd expect a loop to not be terribly slow, either.