Replace values in matrix with NaNs?

40 次查看(过去 30 天)
Shayma Al Ali
Shayma Al Ali 2023-8-24
编辑: Voss 2023-8-24
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?

回答(1 个)

Voss
Voss 2023-8-24
Do this:
B(isnan(A)) = NaN;
  1 个评论
Voss
Voss 2023-8-24
编辑:Voss 2023-8-24
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

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Resizing and Reshaping Matrices 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by