matrix indexing without loop

2 ビュー (過去 30 日間)
mcdull hall
mcdull hall 2018 年 8 月 2 日
コメント済み: mcdull hall 2018 年 8 月 2 日
Hello,
Suppose I have two matrices, A and B:
A = [2 3 1 4;
1 4 1 3];
B = [1 2 3 4;
4 3 2 1];
Now I get the max indices for the matrix A:
[~,ind] = max(A,[],2);
I want to obtain the corresponding values of matrix B with ind:
for ii = 1:2
v(ii) = B(ii,ind(ii));
end
How to get the values of B without a for loop?

採用された回答

Walter Roberson
Walter Roberson 2018 年 8 月 2 日
v = B(sub2ind(size(B), 1:size(B,1), ind))
  1 件のコメント
mcdull hall
mcdull hall 2018 年 8 月 2 日
By the way, it should be:
v = B(sub2ind(size(B), (1:size(B,1))', ind))
Thanks.

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by