Access to matrix elements

4 visualizaciones (últimos 30 días)
ali eskandari
ali eskandari el 30 de Mayo de 2021
Editada: Matt J el 30 de Mayo de 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?

Respuesta aceptada

Matt J
Matt J el 30 de Mayo de 2021
Editada: Matt J el 30 de Mayo de 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

Más respuestas (0)

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by