sum two variables ignoring NaN
Show older comments
I have table T
Var1 Var2
--------------
1 NaN
NaN 2
I want to add var1 and var2 ignoring NaN:
sum
---
1
2
Accepted Answer
More Answers (1)
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
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
on 10 Dec 2020
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!