sum two variables ignoring NaN
조회 수: 85 (최근 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!