Using cov to find a covariance matrix
11 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
dustin
am 25 Okt. 2014
Bearbeitet: Roger Stafford
am 25 Okt. 2014
In the code below, CX and CY are the covariance matrices. However, when I try to use cov(x,x') or cov(xbar,xbar'), I dont get the covariance matrix back and similarly for Y. How do I use cov to determine the covariance matrices?
% Example 9.6 page 270 Intitutive Prob and Random Processes
clear all
close all
sim = 20000; % number of order pairs to generate for
% X_1 and X_2
x = zeros(2, sim); % pre-allocating x
% generating the order pairs with specified probabilities
for m = 1:sim
u = rand(1,1);
if u <= 0.25
x(1, m) = -8;
x(2, m) = 0;
elseif u > 0.25 && u <= 0.5
x(1, m) = 0;
x(2, m) = -8;
elseif u > 0.5 && u <= 0.75
x(1, m) = 2;
x(2, m) = 6;
else
x(1, m) = 6;
x(2, m) = 2;
end
end
% est mean of x
meanx = [sum(x(1, :))/sim, sum(x(2, :))/sim]'
CX = zeros(2,2); % pre-allocating est Cx
xbar= zeros(2, sim); % pre-allocating xbar
% est covariance matrix of X by eq 9.46
for m = 1:sim
xbar(:, m) = x(:, m) - meanx;
CX = CX + xbar(:, m)*xbar(:, m)'/sim;
end
CX
% A is the eigenvector matrix of Cx given
A = [1/sqrt(2), -1/sqrt(2); 1/sqrt(2), 1/sqrt(2)];
y = zeros(2, sim); % pre-allocating y
% transform random vector X by Y = AX
for m = 1:sim
y(:, m) = A*x(:, m);
end
% est mean of y
meany = [sum(y(1, :))/sim, sum(y(2, :))/sim]'
CY = zeros(2, 2);
ybar = zeros(2, sim); % pre-allocating ybar
% est covariance matrix of Y by eq 9.46
for m = 1:sim
ybar(:, m) = y(:, m) - meany;
CY = CY + ybar(:, m)*ybar(:, m)'/sim;
end
CY
0 Kommentare
Akzeptierte Antwort
Roger Stafford
am 25 Okt. 2014
Bearbeitet: Roger Stafford
am 25 Okt. 2014
If you consult the documentation of 'cov' at
http://www.mathworks.com/help/matlab/ref/cov.html
you will see that it says "cov(X,Y), where X and Y are matrices with the same number of elements, is equivalent to cov([X(:) Y(:)])." This means that writing cov(x,x'), as you have, will produce the covariance of two identical vectors 40000 elements long and will not give you the covariance of x(1,:) against x(2,:). It will have four identical values of a variance value of these combined vectors.
What I think you want is
cov(x(1,:).',x(2,:).')
or
cov(x.')
Also be aware that there are two ways of computing covariance, the "biased" and the "unbiased" formulas. See the above reference.
Finally, note that using 20000 samples which have an actual mean of zero will produce a standard deviation of the expected deviation of a single sample divided by sqrt(20000), so that it will be accurate only to a couple of decimal places.
0 Kommentare
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Statistics and Machine Learning Toolbox finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!