Rebuild a matrix from indices
8 views (last 30 days)
Show older comments
Alyssa Webb
on 23 Feb 2017
Commented: Fabio Freschi
on 23 Feb 2017
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.
0 Comments
Accepted Answer
Fabio Freschi
on 23 Feb 2017
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
Guillaume
on 23 Feb 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;
More Answers (0)
See Also
Categories
Find more on Matrices and Arrays in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!