Scan each column without for loop in MATLAB

后端 未结 1 677
别那么骄傲
别那么骄傲 2021-01-24 14:40
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

相关标签:
1条回答
  • 2021-01-24 15:19

    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
    
    0 讨论(0)
提交回复
热议问题