Summing two vectors with NaNs
2 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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 Kommentare
Antworten (2)
dpb
am 10 Apr. 2025
Bearbeitet: dpb
am 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 Kommentare
Siehe auch
Kategorien
Mehr zu Logical finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!