Using cov to find a covariance matrix
Show older comments
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
Accepted Answer
More Answers (0)
Categories
Find more on Monte Carlo Analysis in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!