Search code examples
matlabmatrixmatrix-indexing

Vector as column index in matrix


Given a matrix A (mxn) and a vector B (mx1) I want to create a vector C (mx1) in which each row element is the row element of A from a column indexed by B.
Is it possible to do this, without using loops?

A = [1 2; 3 4; 5 6];
B = [2 1 1].';

Then I want:

C = [2 3 5].';

Solution

  • Convert the column subscripts of B to linear indices and then use them to reference elements in A:

    idx = sub2ind(size(A), (1:size(A, 1)).', B);
    C = A(idx);
    

    (for more information, read the part about linear indexing in this answer).