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