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.

 Accepted Answer

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 Comments

Thank you so much!
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;
yes, this is definitely cleaner!

Sign in to comment.

More Answers (0)

Categories

Tags

Community Treasure Hunt

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

Start Hunting!