I've written the following code to compute the
autocovariance and autocorrelation (for lag 1). Could
someone please tell me if there's anything wrong? I can't
seem to find any errors.
However, I tried to double check my results using Matlab's
in-built functions, i.e. xcov(a,1) and xcorr(a,1) but I
haven't been able to get the same results. Could someone
please explain why?
Thanks a lot!
Sam
Here's the code I've written:
a = [0.0047;
0.0082;
0.0047;
-0.0017;
-0.0002;
-0.0086;
-0.0071;
0.0034;
-0.0050;
0.0005;
-0.0059;
-0.0264;
-0.0089;
-0.0033;
-0.0058;
0.0068;
0.0073;
0.0099;
0.0104;
0.0079;
0.0085;
0.0160;
0.0096;
0.0071;
0.0066;
0.0042;
-0.0033;
-0.0117;
-0.0082;
-0.0197]
a_bar = mean(a);
N = size(a,1);
Lag = 1;
AutoCovarTemp = (a(1:N-Lag,1)-a_bar).*(a(1+Lag:N,1)-a_bar);
AutoCovariance_1 = sum(AutoCovarTemp,1)/N
Lag = 0;
AutoCovarTemp = (a(1:N-Lag,1)-a_bar).*(a(1+Lag:N,1)-a_bar);
AutoCovariance_0 = sum(AutoCovarTemp,1)/N
AutoCorrelation_1 = (AutoCovariance_1/AutoCovariance_0);
Try the following code.
N = length(a);
cov0 = sum((a - mean(a)).*(a - mean(a)))/(N)
cov0mat = cov(a,a,1);
cov0mat(2,1)
cov1 = sum((a(1:end-1) - mean(a(1:end-1))).*(a(2:end) -
mean(a(2:end))))/(N-1)
cov1mat = cov(a(1:end-1),a(2:end),1);
cov1mat(2,1)
More specifically, using my code, when I enter a particular
time series, I get just ONE number as a result, i.e. the
autocovariance.
Using Matlab's xcov however, I get a long list of numbers.
I don't quite understand what that is happening. How do I
use Matlab's in-built functions to get the autocovariance
for say lag 1? I just want the single value that my
algorithm is giving - assuming it's correct.
Thanks again!
Sam
doc xcov