Frey
Frey

Reputation: 325

Select entries from matrix based on row number in MATLAB

I have matrix A=rand(M,N) and row vector B=randi([1 M],1,N). I want to assign entries to C from A according to the row numbers in B. That is C(1,1)=A(B(1,1),1), C(1,2)=A(B(1,2),2), etc. Is there easier way to get C without using a for loop?

Upvotes: 0

Views: 23

Answers (1)

Suever
Suever

Reputation: 65430

You just need to use sub2ind to convert row subscripts, B, and column subscripts, 1:numel(B), into linear indices

C = A(sub2ind(size(A), B, 1:numel(B)));

Upvotes: 1

Related Questions