Scan each column without for loop in MATLAB

2019-03-01 00:21发布

问题:

I = [2 1];
A = [7 11
     8 17];

How can I pick the right value in A without for loop? I is a vector of indices for each column in A. That is I(1) is 8 and I(2) = 11.

回答1:

Use sub2ind to generate linear indices based on the right row and column coordinates, then use these to index into A. In this case, I chooses the right row and you want to choose only one element for each column from the first up to the last:

ind = sub2ind(size(A), I, 1:numel(I));
out = A(ind);

Example

>> I = [2 1];
>> A = [7 11
        8 17];
>> ind = sub2ind(size(A), I, 1:numel(I));
>> out = A(ind);
>> out

out =

     8    11