Rebuild a matrix from indices

Hi everyone! After I extracted the indices from a matrix, I´d like to rebuild it and store other data in the places marked by the indices. For example, if I had
A = [0 2 2 0 0 ; 2 0 0 2 2 ; 0 2 0 2 2 ; 0 0 0 2 2 ; 2 2 0 2 2];
[i,j] = find(A==2);
I get the indices where the 2's are in the matrix (i for rows and j for columns). What I'm trying to do is change the value of the 2's and store data in that positions. That data has the same indices i and j (they are coordinates UTM). I'm working on a big matrix, around 5000x5000. Thank you.

 Respuesta aceptada

Fabio Freschi
Fabio Freschi el 23 de Feb. de 2017

0 votos

Try linear indexing
% the data
A = [0 2 2 0 0 ; 2 0 0 2 2 ; 0 2 0 2 2 ; 0 0 0 2 2 ; 2 2 0 2 2];
[i,j] = find(A==2);
% new value
newVal = 3;
% replace
A(sub2ind(size(A),i,j)) = newVal;

3 comentarios

Alyssa Webb
Alyssa Webb el 23 de Feb. de 2017
Thank you so much!
Guillaume
Guillaume el 23 de Feb. de 2017
Well, if you're going to use linear indexing, get a linear index directly from find:
idx = find(A == 2);
A(idx) = newval;
But, even simpler, don't bother with find and use logical indexing:
A(A == 2) = newval;
Fabio Freschi
Fabio Freschi el 23 de Feb. de 2017
yes, this is definitely cleaner!

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Matrices and Arrays en Centro de ayuda y File Exchange.

Etiquetas

Preguntada:

el 23 de Feb. de 2017

Comentada:

el 23 de Feb. de 2017

Community Treasure Hunt

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

Start Hunting!

Translated by