Replace values in matrix with NaNs?
40 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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 commentaires
Réponses (1)
Voss
le 24 Août 2023
Do this:
B(isnan(A)) = NaN;
1 commentaire
Voss
le 24 Août 2023
Modifié(e) : Voss
le 24 Août 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
Voir également
Catégories
En savoir plus sur Resizing and Reshaping Matrices dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!