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 CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by