3

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].';
Stewie Griffin
  • 14,409
  • 11
  • 37
  • 67

1 Answers1

6

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).

Community
  • 1
  • 1
Eitan T
  • 32,342
  • 13
  • 69
  • 107