Replace values in matrix with NaNs?

40 views (last 30 days)
Shayma Al Ali
Shayma Al Ali on 24 Aug 2023
Edited: Voss on 24 Aug 2023
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?

Answers (1)

Voss
Voss on 24 Aug 2023
Do this:
B(isnan(A)) = NaN;
  1 Comment
Voss
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
A = 5×5
NaN 24 1 8 15 23 NaN 7 14 16 NaN 6 13 NaN 22 10 12 19 21 3 11 NaN 25 2 9
% 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))
rows = 5×1
1 3 2 5 3
cols = 5×1
1 1 2 2 4
B(rows,cols)=NaN
B = 5×5
NaN NaN 0.3915 NaN 0.9488 NaN NaN 0.0499 NaN 0.9620 NaN NaN 0.3112 NaN 0.7506 0.0097 0.8307 0.5469 0.5113 0.2595 NaN NaN 0.8783 NaN 0.6373
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
idx = 5×5 logical array
1 0 0 0 0 0 1 0 0 0 1 0 0 1 0 0 0 0 0 0 0 1 0 0 0
B(idx) = NaN
B = 5×5
NaN 0.5085 0.3915 0.8077 0.9488 0.1175 NaN 0.0499 0.5750 0.9620 NaN 0.2165 0.3112 NaN 0.7506 0.0097 0.8307 0.5469 0.5113 0.2595 0.6478 NaN 0.8783 0.1385 0.6373
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)
idx = 5×1
1 3 7 10 18
B(idx) = NaN
B = 5×5
NaN 0.5085 0.3915 0.8077 0.9488 0.1175 NaN 0.0499 0.5750 0.9620 NaN 0.2165 0.3112 NaN 0.7506 0.0097 0.8307 0.5469 0.5113 0.2595 0.6478 NaN 0.8783 0.1385 0.6373

Sign in to comment.

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!