Replace values in matrix with NaNs?
10 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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 Kommentare
Antworten (1)
Voss
am 24 Aug. 2023
Do this:
B(isnan(A)) = NaN;
1 Kommentar
Voss
am 24 Aug. 2023
Bearbeitet: Voss
am 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
Siehe auch
Kategorien
Mehr zu Creating and Concatenating Matrices finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!