Replace values in matrix with NaNs?
49 ビュー (過去 30 日間)
古いコメントを表示
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;
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1464427/image.jpeg)
The "After" should have NaNs over land while keeping the values that are in the ocean. What am I doing wrong?
0 件のコメント
回答 (1 件)
Voss
2023 年 8 月 24 日
Do this:
B(isnan(A)) = NaN;
1 件のコメント
Voss
2023 年 8 月 24 日
編集済み: Voss
2023 年 8 月 24 日
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
参考
カテゴリ
Help Center および File Exchange で Resizing and Reshaping Matrices についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!