covariance between 2 ts over time
显示 更早的评论
I havea matrix(X) with 3 vectors with 380 elements each. I want to see how the covariance of 1st vector(A) and 2(B) with TS3 (C) evolves over time (25 periods used to compute the cov)
I supposed this should be done by means of a circular loop.
The problem is that the Cov(function) gives a matrix as a result .. and this fact translates into an error in the loop procedure. does someone know if there is a fromula to compute the COV without getting all the cov matrix?
the loop code i've written is :
for i = 26:380
for u = 1:3
covaariances(i,u)= ((cov(X(i,u),x(i,3))))
end
end
this results in an error. could someone of you advise me a way to get what I am aiming for??? thank u for ur valuable time
3 个评论
Newuser
2011-4-29
Walter Roberson
2011-4-30
You must still have an error: the (i.25) would not be valid. Perhaps (i+25) ?
Walter Roberson
2011-4-30
x(i:(i-25),3) would be the empty vector, as i is always going to be greater than i-25.
采纳的回答
更多回答(4 个)
Teja Muppirala
2011-4-30
The COV function does return a matrix. But this is not a problem since you can just extract out the relevant pieces.
I think there are running covariance algorithms out there that do this calculation very efficiently, but even just using a plain old loop is very fast (this code is only slow because I'm plotting it).
t = 0.01*(0:379)';
X = [sin(20*t.^2) sin(5*t.^3) sin(2*t.^4)];
figure;
a1 = subplot(2,1,1);
plot(X);
legend({'X1' 'X2' 'X3'});
title('X');
blk = 25;
C = zeros(size(X,1)-blk+1,2);
a2 = subplot(2,1,2);
h = plot(C);
set(h(1),'color',[0 0.5 0]);
set(h(2),'color','r');
title('Running Covariance');
for n = 0:size(X,1)-blk
c = cov(X(n + (1:blk),:));
C(n+1,:) = c(2:3,1);
set(h(1),'Ydata',C(:,1));
set(h(2),'Ydata',C(:,2));
drawnow;
end
legend({'cov(X1 , X2)' 'cov(X1 , X3)'});
linkaxes([a1 a2],'x');
If you're really against calculating the 3x3 covariance matrix, then you could do it using the formula for covariance which you can find on Wikipedia.
Walter Roberson
2011-4-30
0 个投票
Covariance is inherently an operation that returns a matrix. It measures the correlation of every component of the first vector with every component of the second vector.
If you are looking for a single value that tells you how "similar" the two vectors are, then covariance is the wrong measure. Possibly you wish to use kstest2()
Newuser
2011-4-30
0 个投票
2 个评论
Oleg Komarov
2011-4-30
It takes an instant to generate all the covariance matrices! Then you can plot all at once.
Newuser
2011-4-30
类别
在 帮助中心 和 File Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!