フィルターのクリア

Using matrix index coming from max function to get values from another matrix

1 回表示 (過去 30 日間)
Adam Pigon
Adam Pigon 2017 年 11 月 8 日
コメント済み: Star Strider 2017 年 11 月 8 日
Dear All, I have the following problem:
A = randn(5,5);
B = randn(5,5);
C = randn(5,5);
D = cat(3,A,B,C);
E = randn(5,5,3);
[M,I] = max(D,[],3);
How to use the index matrix I to get respective elements from matrix E ? It means for every combination of i and j I want to take the value of E(i,j,:) whose index is given by the value of I(i,j).
I will be grateful for any comments!

採用された回答

Star Strider
Star Strider 2017 年 11 月 8 日
This seems to work:
A = randn(5,5);
B = randn(5,5);
C = randn(5,5);
D = cat(3,A,B,C);
E = randn(5,5,3);
[M,I] = max(D,[],3);
IL = sub2ind(size(D), cumsum(ones(size(D,1)),1), cumsum(ones(size(D,2)),2), I);
Check = D(IL); % Check To Be Sure Indexing Is Correct
Result = E(IL);
The ‘Check’ assignment demonstrates that the indexing reproduces ‘M’. It is not necessary for the code, and can be deleted.
  4 件のコメント
Adam Pigon
Adam Pigon 2017 年 11 月 8 日
I have a small additional question : what if my problem takes more dimensions, i.e. matrices A,B,C are like size(A) = (5,5,5) ? How should I proceed then? I cannot fully understand the function sub2ind.
Star Strider
Star Strider 2017 年 11 月 8 日
My code should work for all sizes of 3D matrices, since it uses the size function to create the relevant index matrices. (My code could be extended using the same idea to 4D and higher-dimension matrices. I have not explored that possibility.)
MATLAB actually addresses matrices with ‘linear indexing’, a segment of adjacent memory locations, not subscripts. The sub2ind function converts subscript indices to linear indices, that in many instances are the only effective way to index into a matrix, as with your matrix here. (The related ind2sub function does the reverse.)

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMatrices and Arrays についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by