Summing two vectors with NaNs

조회 수: 1 (최근 30일)
dormant
dormant 2025년 4월 10일
답변: Thorsten 2025년 4월 11일
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?

답변 (2개)

dpb
dpb 2025년 4월 10일
편집: dpb 2025년 4월 10일
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
C = 8×1
2 3 4 1 NaN NaN 8 9
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
Could encapsulate in a little function to make clean at top level...
mysum=sumeither(A,B)
mysum = 8×1
2 3 4 1 NaN NaN 8 9
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
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

Thorsten
Thorsten 2025년 4월 11일
s = sum([A,B], 2, 'omitnan');
s(isnan(A) & isnan(B)) = nan;

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

태그

제품


릴리스

R2024b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by