sum two variables ignoring NaN

87 views (last 30 days)
alpedhuez
alpedhuez on 10 Dec 2020
Commented: alpedhuez on 11 Dec 2020
I have table T
Var1 Var2
--------------
1 NaN
NaN 2
I want to add var1 and var2 ignoring NaN:
sum
---
1
2

Accepted Answer

Image Analyst
Image Analyst on 10 Dec 2020
Try this:
var1 = [1;2;3;nan];
var2 = [4;nan;6; 15];
t = table(var1, var2)
% Initialize with var1
theSum = t.var1;
% If any are nan, replace with value from var2.
badRows = isnan(theSum)
theSum(badRows) = t.var2(badRows)
% If both are not nan, make it the sum
goodRows1 = ~isnan(t.var1)
goodRows2 = ~isnan(t.var2)
goodRows = goodRows1 & goodRows2;
theSum(goodRows) = t.var1(goodRows) + t.var2(goodRows)
You get:
t =
4×2 table
var1 var2
____ ____
1 4
2 NaN
3 6
NaN 15
theSum =
5
2
9
15
If one is nan, you get the other one which is not a nan.
If both are nans, you get a nan.
If both are not nan, you get the sum.
  2 Comments
Image Analyst
Image Analyst on 11 Dec 2020
You said in your comment to David that my solution also gives 0 instead of nan (which you want) when both are nan. That is not true. Look with this new sample data where there is a row where both are nan.:
var1 = [1;2;3;nan; nan];
var2 = [4;nan;6; 15; nan];
t = table(var1, var2)
% Initialize with var1
theSum = t.var1;
% If any are nan, replace with value from var2.
badRows = isnan(theSum)
theSum(badRows) = t.var2(badRows)
% If both are not nan, make it the sum
goodRows1 = ~isnan(t.var1)
goodRows2 = ~isnan(t.var2)
goodRows = goodRows1 & goodRows2;
theSum(goodRows) = t.var1(goodRows) + t.var2(goodRows)
You get:
theSum =
5
2
9
15
NaN
and you can see the last row, where both are nan, has a nan for the 4th element of the output vector.
alpedhuez
alpedhuez on 11 Dec 2020
I meant
var1 = [1; 2; 3; nan; nan];
var2 = [4; nan; 6; 15; nan];
Var1 = t.var1
Var2 = t.var2
theSum = sum([Var1, Var2], 2, 'omitnan')
does not provide NaN.

Sign in to comment.

More Answers (1)

David Goodmanson
David Goodmanson on 10 Dec 2020
Edited: David Goodmanson on 10 Dec 2020
Hi alpedhuez,
sum(Var1,Var2,2,'omitnan')
Here the '2' indicates that you are summing rows rather than columns (the default is summing columns). If all the entries in a row are nan, then you get 0.
  2 Comments
Image Analyst
Image Analyst on 10 Dec 2020
Didn't work. Forgot brackets. I think you meant:
var1 = [1; 2; 3; nan; nan];
var2 = [4; nan; 6; 15; nan];
Var1 = t.var1
Var2 = t.var2
theSum = sum([Var1, Var2], 2, 'omitnan')
The difference from mine is that if both are nan's, mine will give a nan, while yours gives a zero.
alpedhuez
alpedhuez on 10 Dec 2020
No I think Image Analyst also gives 0. I want NaN when both are NaNs.

Sign in to comment.

Categories

Find more on Characters and Strings in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!