Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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].';
like image 529
Stewie Griffin Avatar asked Feb 23 '26 23:02

Stewie Griffin


1 Answers

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

like image 167
Eitan T Avatar answered Feb 26 '26 12:02

Eitan T



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!