Replace NaN values in a matrix with values from another matrix

34 views (last 30 days)
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!

Accepted Answer

David Hill
David Hill on 24 May 2022
B(isnan(B))=A(isnan(B));
  2 Comments
jjjSAN
jjjSAN on 30 May 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!

Sign in to comment.

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!