Summing two vectors with NaNs
8 views (last 30 days)
Show older comments
I need to sum two vectors that might contain NaNs. If one vector has a Nan and the other has a number, I want the sum to be the number.
The sum function doesn't have this option.
A = [ 1 2 3 NaN NaN NaN 7 8 ]';
B = [ 1 1 1 1 NaN NaN 1 1 ]';
C = sum( [A,B], 2, 'omitnan' )
C =
2
3
4
1
0
0
8
9
C = sum( [A,B], 2, 'includenan' )
C =
2
3
4
NaN
NaN
NaN
8
9
I want the result to be this:
C =
2
3
4
1
NaN
NaN
8
9
Any suggestions how to achieve this?
0 Comments
Answers (2)
dpb
on 10 Apr 2025
Edited: dpb
on 10 Apr 2025
A = [ 1 2 3 NaN NaN NaN 7 8 ]';
B = [ 1 1 1 1 NaN NaN 1 1 ]';
Check which rows are ok...
isOK=isfinite(A)|isfinite(B);
C=sum([A,B],2,'omitnan');
C(~isOK)=nan
Could encapsulate in a little function to make clean at top level...
mysum=sumeither(A,B)
function s=sumeither(A,B)
% returns sum of finite elements of vectors A,B
assert(isvector(A)&&isvector(B),'Both inputs must be vectors')
assert(numel(A)==numel(B),'Both inputs must be same length')
M=[A(:) B(:)]; % catenate to array, be sure are columns
s=sum(M,2,'omitnan'); % add up the finite elements
s(all(isnan(M),2))=nan; % mark the missing rows
end
0 Comments
See Also
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!