Reputation: 2412
In my MATLAB program, I have the occurrences of the m-dimensional variable X given in a matrix as
X = [x_11 x_12 ... x_1m;
x_21 x_22 ... x_2m;
.
.
.
x_n1 x_n2 ... x_nm;]
where each is an case for X.
and the probability of each case is given by:
pX = [p_x1 p_x2 ... p_xn];
I am looking for a simple way to calculate covariance matrix of X (a matrix that shows how the dimensions of X is related to each other).
I hope there is a simple way to calculate it in MATLAB, just like Expected value of X which is calculated by:
EX = pX * X;
Edit:
X is a random variable with discrete occurrences specified by X matrix. pX shows probability of each occurrence.
Upvotes: 1
Views: 4802
Reputation: 5625
EX = px*X;
nmeas = size(X,1);
XB = X - repmat(EX,nmeas,1);
PD = zeros(nmeas, nmeas);
PD(logical(eye(size(PD)))) = px; % thanks http://stackoverflow.com/questions/3963565/matlab-how-to-assign-values-on-the-diagonal
CX = XB'*PD*XB;
PDij is the joint probability of getting measurement xi and xj, which is pXj if j=i, and 0 otherwise.
So
CX1,1 = pX1 * xB11^2 + px2*XB21^2 +...
CX2,1 = CX1,2 = px1 * xB11*xB12 + px2*XB21*XB22 + ...
which is the definition of covariance.
Upvotes: 2