havakok
havakok

Reputation: 1247

How to add two matrices and get rid of Nans

How can I add two matrices and keep only the numbers ignoring the NaN values?

for example:

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

I want some form of plus C=A+B such that:

C=[1 2 3]

Upvotes: 2

Views: 695

Answers (2)

hmofrad
hmofrad

Reputation: 1902

You can achieve this without using any specific function call just by setting the NaNs to 0s and then performing the sum:

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

Edit: Another way of achieving this as @rayryeng suggested in the first comment is to use isnan:

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

Upvotes: 3

EBH
EBH

Reputation: 10440

You can use nansum (you need Statistics and Machine Learning Toolbox):

C = nansum([A;B])

and get:

C =

     1     2     3

Alternatively, you can use sum with an excluding NaN flag:

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

And you will get the same result.

Upvotes: 3

Related Questions