Categories &

Functions List

Function Reference: nancov

statistics: c = nancov (x)
statistics: c = nancov (x, y)
statistics: c = nancov (…, normalization)
statistics: c = nancov (…, method)

Compute the covariance matrix while ignoring NaN values.

c = nancov (x) returns the covariance matrix of the columns of x, treating each row as an observation, after removing NaN values. If x is a vector, the scalar variance of its non-NaN elements is returned.

c = nancov (x, y), where x and y are of equal length, is equivalent to nancov ([x(:), y(:)]) and returns the 2-by-2 covariance matrix.

c = nancov (…, normalization) specifies the normalization. When normalization is 0 (default), the covariance is normalized by N-1, where N is the number of observations used. When it is 1, it is normalized by N.

c = nancov (…, method) selects how NaN values are handled. With "complete" (the default), any row of the data that contains a NaN value is removed before the covariance is computed. With "pairwise", each element c(i,j) is computed using all rows in which both column i and column j are non-NaN; the resulting matrix may fail to be positive semidefinite.

See also: cov, nanvar, nanstd, nanmean

Source Code: nancov

Covariance matrix of a data set with missing values (complete-case).

 x = [1 2 3; 4 5 NaN; 7 NaN 9; 10 11 12; NaN 14 15]
x =

     1     2     3
     4     5   NaN
     7   NaN     9
    10    11    12
   NaN    14    15
 c = nancov (x)
c =

   40.500   40.500   40.500
   40.500   40.500   40.500
   40.500   40.500   40.500

The same data set using pairwise deletion of missing values.

 x = [1 2 3; 4 5 NaN; 7 NaN 9; 10 11 12; NaN 14 15]
x =

     1     2     3
     4     5   NaN
     7   NaN     9
    10    11    12
   NaN    14    15
 c = nancov (x, 'pairwise')
c =

   15.000   21.000   21.000
   21.000   30.000   39.000
   21.000   39.000   26.250