Replace values in matrix with NaNs?
43 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
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 comentarios
Respuestas (1)
Voss
el 24 de Ag. de 2023
Do this:
B(isnan(A)) = NaN;
1 comentario
Voss
el 24 de Ag. de 2023
Editada: Voss
el 24 de Ag. de 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
Ver también
Categorías
Más información sobre Resizing and Reshaping Matrices en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!