MATLAB: Covariance and correlation

correlationcovariation

Hi everybody, I have a 2 time series returns of 1×789 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,

Best Answer

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');
Related Question