selecting elements in matrix based on a vector

15 ビュー (過去 30 日間)
Champ
Champ 2012 年 2 月 8 日
編集済み: dpb 2013 年 10 月 5 日
suppose I have a matrix [1,2,3,4; 5,6,7,8; 1,2,3,4; 5,6,7,8] and a select vector that will pick an element from each row of the matrix [1;2;2;3] (so it will pick first column element from the first row, second column element from the second row, second column element from the third row and third column element from the fourth row)
How do I code so that the vector "pick" elements from the matrix and the result becomes [1;6;2;7]

採用された回答

Sean de Wolski
Sean de Wolski 2012 年 2 月 8 日
A(sub2ind(size(A),(1:numel(idx))',idx(:)))
where A is your matrix above and idx is your vector.
Or you could go this route:
diag(A(1:numel(idx),idx))
  1 件のコメント
Champ
Champ 2012 年 2 月 8 日
works like charm. thanks so much

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeOperators and Elementary Operations についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by