MATLAB Answers

create vector from matrix without loop

9 views (last 30 days)
Hi there, I have a quick question concerning MATLAB: given A matrix A(mxn) and a Vector B(m,1) I want to create a vector C(m,1) in which each row element is the row element of A from a comlumn indexed by B. So suppose A = [ 1 2; 3 4; 5 6] and B = [2 1 1]' than C should be C = [2 35]. How can I do this using as few computational power as possible (without loops?) ?
cheers Sebastian

  0 Comments

Sign in to comment.

Accepted Answer

Azzi Abdelmalek
Azzi Abdelmalek on 12 May 2013
A = [ 1 2; 3 4; 5 6]
B = [2 1 1]'
C=A(sub2ind(size(A),(1:size(A,1))',B))

  0 Comments

Sign in to comment.

More Answers (2)

Matt J
Matt J on 12 May 2013
Edited: Matt J on 12 May 2013
C=A( sub2ind([m,n],1:m,B') )

  0 Comments

Sign in to comment.


Sebastian
Sebastian on 13 May 2013
Thanks guys!

  0 Comments

Sign in to comment.

Sign in to answer this question.