Summing two vectors with NaNs

4 visualizzazioni (ultimi 30 giorni)
dormant
dormant il 10 Apr 2025
Risposto: Thorsten il 11 Apr 2025
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?

Risposte (2)

dpb
dpb il 10 Apr 2025
Modificato: dpb il 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
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 il 11 Apr 2025
s = sum([A,B], 2, 'omitnan');
s(isnan(A) & isnan(B)) = nan;

Tag

Prodotti


Release

R2024b

Community Treasure Hunt

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

Start Hunting!

Translated by