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 colu
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);
>> I = [2 1];
>> A = [7 11
8 17];
>> ind = sub2ind(size(A), I, 1:numel(I));
>> out = A(ind);
>> out
out =
8 11