Search code examples
matlabmatrixindices

Get list of values of matrix from indices list in Matlab


I have a matrix like this:

A = [35,  1,   6,  26;
     3,   32,  7,  21;
     31   9,   2,  22;
     8,   28,  3,  17];

and a list of indices like this:

B = [1,  1;
     1,  2;
     2,  2;
     1,  3];

I want to get list of values from matrix A with indices in B

C = [35, 1, 32, 6]

I use this code:

C = A(B==1)

But the C is :

[35, 3, 8, 1]

Where am I wrong?


Solution

  • You can use sub2ind to convert your row,col indexing to linear indexing.

    A = [35,  1,   6,  26;
         3,   32,  7,  21;
         31   9,   2,  22;
         8,   28,  3,  17];
    
    B = [1,  1;
         1,  2;
         2,  2;
         1,  3];
    
    linear_ind = sub2ind(size(A), B(:,1), B(:,2));
    C = A(linear_ind)
    

    Which will result in

    C =
        35
         1
        32
         6