如何添加两个矩阵并摆脱 Nans

How to add two matrices and get rid of Nans

我如何添加两个矩阵并只保留忽略 NaN 值的数字?

例如:

A=[NaN 2 NaN];
B=[1 NaN 3];

我想要某种形式的加号 C=A+B 这样:

C=[1 2 3]

您可以使用 nansum(您需要 Statistics and Machine Learning Toolbox):

C = nansum([A;B])

并得到:

C =

     1     2     3

或者,您可以将 sum 与排除 NaN 标志一起使用:

C = sum([A;B],'omitnan')

你会得到相同的结果。

您可以在不使用任何特定函数调用的情况下实现这一点,只需将 NaNs 设置为 0s,然后执行求和:

A(A~=A)=0
B(B~=B)=0
C=A+B

Edit:@rayryeng 在第一条评论中建议的另一种实现方法是使用 isnan:

A(isnan(A))=0
B(isnan(B))=0
C=A+B