-
Notifications
You must be signed in to change notification settings - Fork 2
/
nansum.m
34 lines (28 loc) · 993 Bytes
/
nansum.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
function y = nansum(x,dim)
%NANSUM Sum, ignoring NaNs.
% Y = NANSUM(X) returns the sum of X, treating NaNs as missing values.
% For vector input, Y is the sum of the non-NaN elements in X. For
% matrix input, Y is a row vector containing the sum of non-NaN elements
% in each column. For N-D arrays, NANSUM operates along the first
% non-singleton dimension.
%
% Y = NANSUM(X,DIM) takes the sum along dimension DIM of X.
%
% See also SUM, NANMEAN, NANVAR, NANSTD, NANMIN, NANMAX, NANMEDIAN.
% Copyright 1993-2004 The MathWorks, Inc.
% Find NaNs and set them to zero. Then sum up non-NaNs. Cols of all NaNs
% will return zero.
if nargin == 1 & size(x,1) ~= 1
dim = 1;
elseif nargin == 1 & size(x,1) == 1
dim = 2;
end
x0 = x;
x(isnan(x)) = 0;
if nargin == 1 % let sum figure out which dimension to work along
y = sum(x);
else % work along the explicitly given dimension
y = sum(x,dim);
end
logic = all(isnan(x0),dim);
y(logic) = NaN;