Search code examples
matlabfindindices

Extract values from 2d array with indices from another array (without loops)


I have an array [2; 3] and a matrix [ 1 3 4 5; 2 4 9 2]. Now I would like to extract the second element from the first row and the third element from the second row and thus obtain [3 ; 9]. I managed it to do it with a loop, but since I'm working with much larger arrays, I would like to avoid these.


Solution

  • You can use sub2ind to convert each of the column subscripts (along with their row subscripts) into a linear index and then use that to index into your matrix.

    A = [1 3 4 5; 2 4 9 2];
    cols = [2; 3];
    
    % Compute the linear index using sub2ind
    inds = sub2ind(size(A), (1:numel(cols)).', cols);
    
    B = A(inds)
    %   3   
    %   9
    

    Alternately, you could compute the linear indices yourself which is going to be more performant than sub2ind

    B = A((cols - 1) * size(A, 1) + (1:numel(cols)).');
    %   3
    %   9