C = cov(x)
C = cov(x,y)
C = cov(x,1)
C = cov(x,y,1)
C = 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(:)]).
C = cov(x) or C = 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.
C = cov(x,1) or C = 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).
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.