Replace values in matrix with NaNs?
42 views (last 30 days)
Show older comments
I have two matrices with sizes 720x361. There are NaN values in matrix A that are not present in Matrix B. I'd like to insert NaNs in the same coordinates there are NaNs in matrix A. However, its not working for me.
My code:
B=rand(720,361);
[rows,cols]=find(isnan(A));
B(rows,cols)=NaN;
The "After" should have NaNs over land while keeping the values that are in the ocean. What am I doing wrong?
0 Comments
Answers (1)
Voss
on 24 Aug 2023
Do this:
B(isnan(A)) = NaN;
1 Comment
Voss
on 24 Aug 2023
Edited: Voss
on 24 Aug 2023
Example:
% a matrix with some NaNs:
A = magic(5);
A([1 3 7 10 18]) = NaN
% another matrix the same size:
B = rand(size(A));
B_orig = B; % save the original for later
% your attempt to set elements in B to NaN, using two subscripts:
[rows,cols]=find(isnan(A))
B(rows,cols)=NaN
Now B has NaNs in rows [1 2 3 5] and columns [1 2 4], which is every row in rows and every column in cols, instead of just the individual locations you wanted.
The method in my answer uses logical indexing instead:
B = B_orig; % restore original value
idx = isnan(A) % logical matrix
B(idx) = NaN
You could also convert your rows and cols to linear indices and use those:
B = B_orig; % restore original value
[rows,cols]=find(isnan(A));
idx = sub2ind(size(B),rows,cols)
B(idx) = NaN
See Also
Categories
Find more on Resizing and Reshaping Matrices 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!