MATLAB: Selecting an element from each column of a matrix using another matrix

columnsmatrixsub2ind

I have a 130×87 matrix (A) and I need to select an element from each column based on the numbers in a 1×87 matrix (B). So if the first number in matrix B is 12, I need the 12th number in the first column of matrix A.

Best Answer

Use sub2ind:
>> A = [0,1,2;3,4,5;6,7,8;9,10,11] % your matrix
A =
0 1 2
3 4 5
6 7 8
9 10 11
>> B = [2,4,3]; % the rows you want
>> X = sub2ind(size(A),B,1:size(A,2));
>> A(X) % get the values
ans =
3 10 8