Finding out lag in signals

1 view (last 30 days)
Koustubh Shirke
Koustubh Shirke on 22 Sep 2020
Edited: Delprat Sebastien on 22 Sep 2020
Hi ,
I have two time domain signals in matlab workspace ?
How can I find out the lag between these two signals in seconds ?
Regards,
Koustubh

Answers (1)

Delprat Sebastien
Delprat Sebastien on 22 Sep 2020
Edited: Delprat Sebastien on 22 Sep 2020
One approach is to find the max of the signals correlation. Alternatively, there is a finddelay function (cf doc) Here is some code for you using max of correlation.
Thsi will work on simple signal. Depending on the amount of noise and quality of the data, this approach may not be so robust in practice.
clear all
close all
clc
% 1) Générate noisy signal
s=0.01;
t=0:s:10;
TheoreticalDelay=0.5;
w1=4;
w2=10;
mu=0.5;
f=@(t) sin(w1*t).*cos(w2*t)+randn(size(t))*mu;
x1=f(t);
x2=f(t-TheoreticalDelay);
% 2) Compute correlation and find delay
[C21,lags]=xcorr(x2,x1);
[~,iDelay]=max((C21))
EstimatedDelay=lags(iDelay)*s;
fprintf('Theoretical delay : %.2f s\n',TheoreticalDelay);
fprintf('Estimated delay : %.2f s\n',EstimatedDelay);
figure;
subplot(3,1,1);
plot(t,x1,'r',t,x2,'b');
grid on;legend('x1','x2');xlabel('Time(s)');
subplot(3,1,2);
plot(lags*s,C21);
hold on;
plot(lags(iDelay)*s,C21(iDelay),'r*');
legend('correlation','max');
grid on;
xlabel('Time(s)');
subplot(3,1,3);
plot(t+EstimatedDelay,x1,'r',t,x2,'b');
grid on;legend('x1 sync with x2','x2');xlabel('Time(s)');

Community Treasure Hunt

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

Start Hunting!