Access to matrix elements

3 次查看(过去 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