I am new to this forum. I am just trying to understand how to calculate delay (in terms of samples) between two signals using cross-correlation function. I wrote a small Matlab code in order to understand this. But I am finding difficulty in understanding the results.


 fm = 1000; //message signal
 fs = 10 * fm; //sampling frequency
 ts = 1 /fs;
 t = 0:ts:1-ts;


 [r,s] = xcorr(x,y);


The results obtained using this code are as follows.

enter image description here

From the figure, we can observe that the peak is occurring at around 10,000 sample. So, can 10,000 samples be considered as a delay (in samples) between two signals? And does the corresponding time delay is 10000 * 1/10000 = 1 sec in this case?


1 Answer 1


Yes and no. In principle, you can use the peak of your correlation function. However, it is not at 10000. The correlation function is symmetric around 0, so your peak is actually much closer to zero than you think. This is one of the reasons why xcorr returns two paramters, one for the lags at which the function is calculated. The correct way of plotting the the correlation function would thus be a plot(s,r).

Secondly, you should try zooming in a bit. Since your time signals have 10000 samples, your acf has ~20000, making it hard to see the exact maximum. If you do zoom in you'll notice it's not exactly at zero but two samples to the right.

Why two samples? Because you have 10 samples per period and the shift between sine and cosine is a quarter period, so it's actually 2.5 samples. You notice the problem, with the sampling you've chosen it is a little hard to measure the delay precisely.

Try reducing your fm to a small value, like 10, this makes the correlation function easier to interpret. Here is an example:

Example fm=10

In this example, the maximum occurs at sample 247, which is equivalent to 247*ts = 24.7 milliseconds.

In case you wonder about the triangular shape, this has to do with the fact that while at lag 0 (in the middle) we can "compare" the entirety of the two signals whereas for larger lags, we need to truncate both signals to shorter versions. The larger the lag, the fewer samples we have to correlate. For this reason, we typically check the ACF closer to lag zero.

  • $\begingroup$ Hi, thanks for the clarification. $\endgroup$
    – Sampath
    Commented Jul 16, 2020 at 14:45
  • $\begingroup$ You're welcome. Glad if it helped. $\endgroup$
    – Florian
    Commented Jul 16, 2020 at 14:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.