2
votes

I'm trying to understand how the cross correlation in matlab, mainly xcorr, works. This an example code:

t = -4*pi:0.1:4*pi;
y1 = sin(t*pi);
y2 = sin(t*pi - 0.7*pi);
[acor,lag] = xcorr(y1,y2,50);
[~,I] = max(abs(acor));
lagDiff = lag(I)

and the answer is:

  3

Now you multiply the the delta t by 3 so you get (0.1*3) and the time lag is 0.3, while the true answer is 0.7*3.14 which is roughly 2.2 I cant figure out what I'm doing wrong

thanks in advance

1
Why is t defined as t = -4*pi:0.1:4*pi;? And then you multiplying by pi again.Lokesh A. R.

1 Answers

2
votes

You have two things wrong:

  1. You should not use abs in the maximization.
  2. 0.7*3.14 is the true phase lag, not the true time lag. The true time lag is -0.7 (note also the minus sign).

Let me elaborate these two points.

  1. You need to use

    [~,I] = max(acor)
    

    that is, remove abs. Using abs you may be finding the lag at which the signals give a very large negative correlation, which is not what you want.

    With this modification, you get I=44 and lagDiff=-7.

    Now, according to your definition of t, your sampling period is 0.1. So the result lagDiff=-7 (in samples) corresponds to -0.7 seconds.

  2. Your reasoning about the true answer is not correct. The true answer is not 0.7*3.14, but -0.7. To see why, note that your definition

    y2 = sin(t*pi - 0.7*pi);
    

    is equivalent to

    y2 = sin((t-0.7)*pi);
    

    Comparing with

    y1 = sin(t*pi);
    

    it's clear that y2 is y1 with time advanced by 0.7 seconds; or delayed by -0.7 seconds.

In conclusion, the result given by the code without abs is in accordance with the true answer: -0.7 seconds.