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.
0001 function y = nansum(x,dim) 0002 %NANSUM Sum, ignoring NaNs. 0003 % Y = NANSUM(X) returns the sum of X, treating NaNs as missing values. 0004 % For vector input, Y is the sum of the non-NaN elements in X. For 0005 % matrix input, Y is a row vector containing the sum of non-NaN elements 0006 % in each column. For N-D arrays, NANSUM operates along the first 0007 % non-singleton dimension. 0008 % 0009 % Y = NANSUM(X,DIM) takes the sum along dimension DIM of X. 0010 % 0011 % See also SUM, NANMEAN, NANVAR, NANSTD, NANMIN, NANMAX, NANMEDIAN. 0012 0013 % Copyright 1993-2004 The MathWorks, Inc. 0014 % $Revision: 2.10.2.4 $ $Date: 2004/07/28 04:38:44 $ 0015 0016 % Find NaNs and set them to zero. Then sum up non-NaNs. Cols of all NaNs 0017 % will return zero. 0018 x(isnan(x)) = 0; 0019 if nargin == 1 % let sum figure out which dimension to work along 0020 y = sum(x); 0021 else % work along the explicitly given dimension 0022 y = sum(x,dim); 0023 end