Access to matrix elements

7 visualizzazioni (ultimi 30 giorni)
ali eskandari
ali eskandari il 30 Mag 2021
Modificato: Matt J il 30 Mag 2021
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?

Risposta accettata

Matt J
Matt J il 30 Mag 2021
Modificato: Matt J il 30 Mag 2021
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

Più risposte (0)

Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by