create vector from matrix without loop

조회 수: 11 (최근 30일)
Sebastian
Sebastian 2013년 5월 12일
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

채택된 답변

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

추가 답변 (2개)

Matt J
Matt J 2013년 5월 12일
편집: Matt J 2013년 5월 12일
C=A( sub2ind([m,n],1:m,B') )

Sebastian
Sebastian 2013년 5월 13일
Thanks guys!

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by