covariance and correlation

2 次查看(过去 30 天)
Hi everybody, I have a 2 time series returns of 1x789 size (X and Y).
I want to compare how similar they are and for this want to calculate the covariance and correlation. Could anybody please show me the code on how to do this?
Best wishes,

采纳的回答

Wayne King
Wayne King 2012-1-24
Hi, In investigating correlation between two time series, you may want to use xcorr() to obtain the cross correlation sequence.
The cross correlation sequence lags one time series with respect to the other and gives the correlation at different lags. This is often a better measure for time series. For example if two time series are identical except that one arrives at a sensor a few milliseconds after another, then the correlation may be small, but is that really accurate. If you lag one with respect to the other you can see that they are perfectly correlated at a given lag.
In the following example, y is a delayed version of x (delayed by ten samples). If you just compute the correlation, it is pretty small (approx. 0.16), but if you use the cross correlation sequence, you see that y and x are perfectly correlated at lag 10 as expected.
x = randn(100,1);
y = [zeros(10,1) ; x(1:90)];
[c,lags] = xcorr(y,x,50,'coeff');
stem(lags,c); xlabel('Lag');
ylabel('Correlation Coefficient');

更多回答(1 个)

Satadru Mukherjee
Satadru Mukherjee 2020-3-30
编辑:Satadru Mukherjee 2020-3-30
Execute the below code , in th cova variable covariance & in the corr variable , correlation result will be stored...
clc
clear all
close all
x=input('Enter the data points:');
a1=mean(x);
z=[];
for i=1:length(x)
z=[z (x(i)-a1)^2];
end
s1=sum(z);
s1=s1/(length(x)-1);
s1=sqrt(s1);
y=input('Enter the data points:');
a2=mean(y);
z=[];
for i=1:length(y)
z=[z (y(i)-a2)^2];
end
s2=sum(z);
s2=s2/(length(x)-1);
s2=sqrt(s2);
x=x-a1;
y=y-a2;
ak=x*y';
cova=ak/(length(x)-1);
corr=cova/(s1*s2);

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by