Skip to Main Content Skip to Search
Product Documentation

cov - Covariance matrix

Syntax

cov(x)
cov(X)
cov(X,Y)
cov(x) or cov(x,y)
cov(x,1)
cov(x,y,1)

Description

cov(x), if x is a vector, returns the variance of x. For matrix input X, where each row is an observation, and each column is a variable, cov(X) is the covariance matrix. diag(cov(X)) is a vector of variances for each column, and sqrt(diag(cov(X))) is a vector of standard deviations. cov(X,Y), where X and Y are matrices with the same number of elements, is equivalent to cov([X(:) Y(:)]).

cov(x) or cov(x,y) normalizes by N – 1, if N > 1, where N is the number of observations. This makes cov(X) the best unbiased estimate of the covariance matrix if the observations are from a normal distribution. For N = 1, cov normalizes by N.

cov(x,1) or cov(x,y,1) normalizes by N and produces the second moment matrix of the observations about their mean. cov(X,Y,0) is the same as cov(X,Y) and cov(X,0) is the same as cov(X).

Tips

cov removes the mean from each column before calculating the result.

The covariance between two random variables is:

where E is the mathematical expectation and μi = Exi.

Examples

Consider A = [-1 1 2 ; -2 3 1 ; 4 0 3]. To obtain a vector of variances for each column of A:

v = diag(cov(A))'
v =
   10.3333    2.3333    1.0000

Compare vector v with covariance matrix C of A:

C = cov(A)
C =
   10.3333   -4.1667    3.0000
   -4.1667    2.3333   -1.5000
    3.0000   -1.5000    1.0000

The diagonal elements C(i,i) represent the variances for the columns of A. The off-diagonal elements C(i,j) represent the covariances of columns i and j.

See Also

corrcoef | mean | median | std | var | xcorr | xcov

  


Free MATLAB Interactive Kit

Explore how to use MATLAB to make advancements in engineering and science.


Download free kit

Trials Available

Try the latest version of MATLAB and other MathWorks products.


Get trial software
 © 1984-2012- The MathWorks, Inc.    -   Site Help   -   Patents   -   Trademarks   -   Privacy Policy   -   Preventing Piracy   -   RSS