Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Unable to compute autocovariance/autocorrelation using Matlab's in-built functions

501 views
Skip to first unread message

Iwan Toknow

unread,
Aug 5, 2008, 10:47:02 AM8/5/08
to
Hi,

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);

zia

unread,
Aug 5, 2008, 12:52:17 PM8/5/08
to
On Aug 5, 10:47 am, "Iwan Toknow" <iwan2no_removeth...@hotmail.com>
wrote:

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)

Iwan Toknow

unread,
Aug 5, 2008, 4:30:03 PM8/5/08
to
Thanks.. but actually my question is if there is anything
wrong with my code - and if so, what is the mistake.

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

Joachim

unread,
Aug 5, 2008, 5:39:02 PM8/5/08
to
"Iwan Toknow" <iwan2no_r...@hotmail.com> wrote in
message <g7ad8b$qpk$1...@fred.mathworks.com>...

doc xcov

0 new messages