MATLAB: How to find the time delay between two signals

signal delaysignal processingsynchronizationtime shift

This is a program I am using to find the delay between two signals with different sampling frequencies. My time signal is from 1 to 10.
The actual delay in the plot is 1.382 but I am getting 109 when I calculate the cross-correlation and find the max value.
Please help me figure out how to get exact value in this case.
x = sin(2*pi*(1:.025:20));
t1 = linspace(1,10,length(x));
x = rand(1,t1)*x;
y = sin(2*pi*(1:.0123:30));
t2 = linspace(1,10,length(y));
y = rand(1,t2)*y;
y = [zeros(1,100) y(1:end-100)];
figure
plot(t1,x);hold on;plot(t2,y,'-r')
s1 =x;
s2 =y;
c = xcorr(s2,s1); % Cross correlation
lag = mod(find(c == max(c)), length(t1)) % Find the position of the peak

Best Answer

It is impossible for xcorr to find a delay between two signals, if they have a different frequency. This is not a problem of Matlab, but the delay between such signals is not even physically or mathematically defined.
So at first Use an interpolation or up- or downsampling method to get the signals with the same frequency. Then take into account that xcorr replies indices, which are positive integers. The function does not have any information about the frequency of the signals and can in consequence not reply a delay in seconds. But a trivial division allows you to convert the index output to the wanted time.