ambiguity in Cross corelation in matlab using xcorr

9 views (last 30 days)
Syed
Syed on 10 Dec 2012
Dear all,
I am was not convinced or may be could not understand the correlation in matlab i.e. xcorr function. So to test I simple made two exactly similar sine wave without any delay, and it gives me delay of 21. I cannot understand why. please first see the code below
if true
fo=200; fs=2500;
t=0:1/fs:.008;
x=sin(2*pi*fo*t);
y=x; %now x and y are exactly the same
%correlation start here xc = xcorr(x,y); [a,delay]=max(xc); subplot(3,1,1); plot(t,x); %xlabel(t); subplot(3,1,2); plot(t,y); subplot(3,1,3); plot(xc);
display(sprintf('maximum of xc is %d',max(xc))); display(sprintf('delay is %d',delay)); end
So I get the delay at the index 21, where I think we should not have any delay. Note that the x and y both have 21 elements. What I understand is, may be matlab implicitly padd zeros to the second element, in this case y,
Also the please clarify one more thing that the maximim value in the vector 'xc' indicates that at this point the peaks of the two points come together right...!
Also please note that in the detail help of xcorr it is mentioned that...
In all cases, the cross-correlation or autocorrelation computed by xcorr has the zeroth lag in the middle of the sequence, at element or row maxlags+1 (element or row N if maxlags is not specified).
What does that mean. How in the world can I find the delay between my two signals, please suggest since I have tried many things but cannot get certain answer.
Thanks in advance, Jaffry

Answers (2)

Wayne King
Wayne King on 10 Dec 2012
Edited: Wayne King on 10 Dec 2012
I think you are confusing the index or element of the vector xc with the lag.
fo=200; fs=2500;
t=0:1/fs:.008;
x=sin(2*pi*fo*t);
y=x; %now x and y are exactly the same
[c,lags] = xcorr(x,y,'coeff');
[val,idx] = max(abs(c));
fprintf('Maximum value occurs at lag %d\n',lags(idx))
You have to keep in mind that the cross-correlation sequence is returned for negative and positive lags.
So you can't just use the index output of max() to find the delay, you then have to find out which delay that index corresponds to in the lag vector.

Syed
Syed on 12 Dec 2012
Thank you for response
So do you have any idea about how to find out the time difference, I have to find the TOF(Time of Flight) for two signals.
One thing that was in my mind was this, let the sampling rate is 1Mhz, then it means time difference b/w two adjacent signals is 1us. so for example the maximum value comes at 63rd index, then the time time at which the peak comes is 63us... Is this approach correct.
Also even this way I cannot find the time lag between two signals,
bests, Jaffry

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!