MATLAB: Doubt on Covariance matrix of 3 vectors in MATLAB

covarianceMATLAB

Hi all, The covariance matrix of 3 vectors x y and z is defined by
cov_matrix(x,y,z) =[var(x) cov(x,y) cov(x,z); cov(x,y) var(y) cov(y,z); cov(x,z) cov(y,z) var(z) ];
but what I obtain for
cov(A) does not match with the above equation where A = [x;y;z];
Why is ti so? How can I correct this mistake?I am using matlab 2011a.

Best Answer

You are correct about the diagonal elements var(x) , var(y) and var(z). But the off axis computations is not correct. When you use cov(x,y) directly on two vectors remember that this will return also return a matrix with the variance of x and y on the diagonal and the covariances between them on the off axis.
The cov function cannot be used to calculate the off diagonal elements directly, you can either use some logic to remove the diagonal and place the off axis elements where they belong or better make you own equation (if not there was no need to not use cov directly on A)
x=[-1;-2;4];
y=[1;3;0];
z=[2;1;3];
A=[x,y,z];
The covariance between two columns is:
E[(x-E(x))'*(y-E(y))]
To make the estimate unbiased cov normalizes by N-1.
So then you are ready to create the code:
N=numel(x); %(assume equal lengths)
CovXY=(x-mean(x))'*(y-mean(y))/(N-1);
As long as the vectors x, y and z are not complex then:
CovYX=CovXY;
So
CovXZ=(x-mean(x))'*(z-mean(z))/(N-1);
CovZX=CovXZ;
CovYZ=(y-mean(y))'*(z-mean(z))/(N-1);
CovZY=CovYZ;
YourCovMx=[var(x) CovXY CovXZ;...
CovYX var(y) CovYZ;...
CovZX CovZY var(z)];