sum two variables ignoring NaN
82 次查看(过去 30 天)
显示 更早的评论
I have table T
Var1 Var2
--------------
1 NaN
NaN 2
I want to add var1 and var2 ignoring NaN:
sum
---
1
2
0 个评论
采纳的回答
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
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.
更多回答(1 个)
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
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.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Characters and Strings 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!