sum two variables ignoring NaN

38 ビュー (過去 30 日間)
alpedhuez
alpedhuez 2020 年 12 月 10 日
コメント済み: alpedhuez 2020 年 12 月 11 日
I have table T
Var1 Var2
--------------
1 NaN
NaN 2
I want to add var1 and var2 ignoring NaN:
sum
---
1
2

採用された回答

Image Analyst
Image Analyst 2020 年 12 月 10 日
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 件のコメント
Image Analyst
Image Analyst 2020 年 12 月 11 日
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 2020 年 12 月 11 日
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.

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

その他の回答 (1 件)

David Goodmanson
David Goodmanson 2020 年 12 月 10 日
編集済み: David Goodmanson 2020 年 12 月 10 日
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 件のコメント
Image Analyst
Image Analyst 2020 年 12 月 10 日
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 2020 年 12 月 10 日
No I think Image Analyst also gives 0. I want NaN when both are NaNs.

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

カテゴリ

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