MATLAB: How to slice 2d matrix based on a vector of indices of each row

accessMATLABslicing

For example: A = [1,2,3,4;5,6,7,8;9,10,11,12]; B=[2,1,4]. Each element in B means the desired element index of each row in A. That's to say, I want to get the 2nd element of A(1,:), 1st element of A(2,:), 4th element of A(3,:). How can I get this result with an efficient slicing method instead of a time-consuming for loop? Thanks.

Best Answer

A = [1,2,3,4; 5,6,7,8; 9,10,11,12];
B = [2,1,4];
C = A(sub2ind(size(A), 1:3, B))
sub2ind creates the "linear index" from the size of the matrix and the row and column indices.