Replace NaN values in a matrix with values from another matrix

24 ビュー (過去 30 日間)
H
H 2022 年 5 月 24 日
コメント済み: jjjSAN 2022 年 5 月 30 日
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!

採用された回答

David Hill
David Hill 2022 年 5 月 24 日
B(isnan(B))=A(isnan(B));
  2 件のコメント
H
H 2022 年 5 月 24 日
Thanks!!
jjjSAN
jjjSAN 2022 年 5 月 30 日
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!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by