Replace NaN values in a matrix with values from another matrix

25 vues (au cours des 30 derniers jours)
H
H le 24 Mai 2022
Commenté : jjjSAN le 30 Mai 2022
Hello, I have two matrices with the same dimension (let's say 100x100).
One (matrix A) only contains numerical values and the other (matrix B) contains numerical values and NaNs.
I'd like to replace NaN values in matrix B by the corresponding values in matrix A, while keeping the non NaN values in matrix B.
B(B==NaN)=A doesn't work
I've also tried something with a mask:
mask=B;
mask(nan(mask)) = 1;
A=A.*mask;
but it multiplies the non NaN values with the corresponding A values.
I'm sure it can be done very simply but still didn't find how.
Thanks for your help!

Réponse acceptée

David Hill
David Hill le 24 Mai 2022
B(isnan(B))=A(isnan(B));
  2 commentaires
H
H le 24 Mai 2022
Thanks!!
jjjSAN
jjjSAN le 30 Mai 2022
Hello! I'm following this topic as I'm trying to deal with NaNs in a precipitation time series.
This line of command suits very well to me, it works perfectly; I have a time series and I'm substituting NaNs with the values taken from another rain gauge.
My problem is that when I use the new vector created to run a loop it doesn't work, my resulting vector only have NaNs inside! I write my code here:
pr1 = data.rainfall; % My original data with NaNs inside
matrix = readmatrix("completevalues.csv"); % I used this function because
% it gives me back a double type variable
rainfall = pr2(:,3); % My new rainfall data are in the third column
pr1(isnan(pr1)) = rainfall(isnan(pr1)); % it works! I also tried working with rows vector
% instead of column ones and it still works.
data.newrainfall = pr1; % I put my new vector in the original dataset
The latter will be taken out again from the dataset to run a loop but the result is a NaN vector.
Thank you for helping!

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Logical 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!

Translated by