MATLAB: Column-wise inexing of matrix

indexindexingMATLAB

Consider the following
A = magic(4);
indx = [1 1 3 2;4 2 1 1; 1 3 2 1];
A(indx)
Because of linear indexing the code above returns:
ans =
16 16 9 5
4 5 16 16
16 9 5 16
But I would like it to return the equivalent of
[A(indx(:,1),1) A(indx(:,2),2) A(indx(:,3),3) A(indx(:,4),4)]
ans =
16 2 6 8
4 11 3 13
16 7 10 13
What is the most efficient, scalable way of doing this? Thiking of larger matrices.

Best Answer

One way that is scalable and matches your example:
A(indx + (0:size(indx,2)-1)*size(A,1))
This uses implicit expansion. On earlier versions of MATLAB you would have to use bsxfun or repmat to get the same result.
Should work as long as indx columns match the columns of A that you want extracted. If not, then you would need to modify the row indexing vector I used to match the actual column indexing you wanted.