sum two variables ignoring NaN

85 Ansichten (letzte 30 Tage)
alpedhuez
alpedhuez am 10 Dez. 2020
Kommentiert: alpedhuez am 11 Dez. 2020
I have table T
Var1 Var2
--------------
1 NaN
NaN 2
I want to add var1 and var2 ignoring NaN:
sum
---
1
2

Akzeptierte Antwort

Image Analyst
Image Analyst am 10 Dez. 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 Kommentare
Image Analyst
Image Analyst am 11 Dez. 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 am 11 Dez. 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.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

David Goodmanson
David Goodmanson am 10 Dez. 2020
Bearbeitet: David Goodmanson am 10 Dez. 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 Kommentare
Image Analyst
Image Analyst am 10 Dez. 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 am 10 Dez. 2020
No I think Image Analyst also gives 0. I want NaN when both are NaNs.

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Characters and Strings finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by