Access to matrix elements

3 ビュー (過去 30 日間)
ali eskandari
ali eskandari 2021 年 5 月 30 日
編集済み: Matt J 2021 年 5 月 30 日
I have two matrices, A and B. I want to extract values of matrix A based on indexes of B.
Consider B like a pixel position in an image.
A = magic(4)
A =
16 2 3 13
5 11 10 8
9 7 6 12
4 14 15 1
B = [2 1; 3 3; 2 4]
This means that I want to have a matrix C like below.
C = [2 6 14]
I've done it with for loop:
for i=1:length(B)
C(i) = A(B(i,2),B(i,1));
end
but I'd rather avoid a for loop. How can I do that?

採用された回答

Matt J
Matt J 2021 年 5 月 30 日
編集済み: Matt J 2021 年 5 月 30 日
A = magic(4)
A = 4×4
16 2 3 13 5 11 10 8 9 7 6 12 4 14 15 1
B = [2 1; 3 3; 2 4] ;
C=A( sub2ind(size(A), B(:,2), B(:,1) ) ).'
C = 1×3
2 6 14

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by