Categories &

Functions List

Function Reference: nansum

statistics: s = nansum (x)
statistics: s = nanmax (x, 'all')
statistics: s = nanmax (x, dim)
statistics: s = nanmax (x, vecdim)

Compute the sum while ignoring NaN values.

s = nansum (x) returns the sum of x, after removing NaN values. If x is a vector, a scalar value is returned. If x is a matrix, a row vector of column sums is returned. If x is a multidimensional array, the nansum operates along the first nonsingleton dimension. If all values along a dimesion are NaN, the sum is returned returned as 0.

s = nansum (x, 'all') returns the sum of all elements of x, after removing NaN values. It is the equivalent of nansum (x(:)).

s = nansum (x, dim) operates along the dimension dim of x.

s = nansum (x, vecdim) returns the sum over the dimensions specified in the vector vecdim. Each element of vecdim represents a dimension of the input array x and the output s has length 1 in the specified operating dimensions. The lengths of the other dimensions are the same for x and y. For example, if x is a 2-by-3-by-4 array, then nanmax (x, [1 2]) returns a 1-by-1-by-4 array. Each element of the output array is the maximum of the elements on the corresponding page of x. If vecdim indexes all dimensions of x, then it is equivalent to nanmax (x, 'all'). Any dimension in vecdim greater than ndims (x) is ignored.

See also: sum, nanmin, nanmax

Source Code: nansum

Example: 1

 

 ## Find the column sums for a matrix with missing values.,

 x = magic (3);
 x([1, 4, 7:9]) = NaN
 s = nansum (x)

x =

   NaN   NaN   NaN
     3     5   NaN
     4     9   NaN

s =

    7   14    0

                    

Example: 2

 

 ## Find the row sums for a matrix with missing values.,

 x = magic (3);
 x([1, 4, 7:9]) = NaN
 s = nansum (x, 2)

x =

   NaN   NaN   NaN
     3     5   NaN
     4     9   NaN

s =

    0
    8
   13

                    

Example: 3

 

 ## Find the sum of all the values in a multidimensional array
 ## with missing values.

 x = reshape (1:30, [2, 5, 3]);
 x([10:12, 25]) = NaN
 s = nansum (x, "all")

x =

ans(:,:,1) =

     1     3     5     7     9
     2     4     6     8   NaN

ans(:,:,2) =

   NaN    13    15    17    19
   NaN    14    16    18    20

ans(:,:,3) =

    21    23   NaN    27    29
    22    24    26    28    30

s = 407
                    

Example: 4

 

 ## Find the sum of a multidimensional array with missing values over
 ## multiple dimensions.

 x = reshape (1:30, [2, 5, 3]);
 x([10:12, 25]) = NaN
 s = nansum (x, [2, 3])

x =

ans(:,:,1) =

     1     3     5     7     9
     2     4     6     8   NaN

ans(:,:,2) =

   NaN    13    15    17    19
   NaN    14    16    18    20

ans(:,:,3) =

    21    23   NaN    27    29
    22    24    26    28    30

s =

   189
   218