%% Delay Between Two Correlated Signals
% Two sensors at different locations measure vibrations caused by a car as it crosses a bridge.
% Load the signals and the sample rate, F_s=11025\;\rm Hz. Create time vectors and plot the signals. The signal from Sensor 2 arrives at an earlier time than the signal from Sensor 1.

load sensorData

t1 = (0:length(s1)-1)/Fs;
t2 = (0:length(s2)-1)/Fs;

subplot(2,1,1)
plot(t1,s1)
title('s_1')

subplot(2,1,2)
plot(t2,s2)
title('s_2')
xlabel('Time (s)')

%
% The cross-correlation of the two measurements is maximum at a lag equal to the delay.
% Plot the cross-correlation. Express the delay as a number of samples and in seconds.

[acor,lag] = xcorr(s2,s1);

[~,I] = max(abs(acor));
lagDiff = lag(I)
timeDiff = lagDiff/Fs

figure
plot(lag,acor)
a3 = gca;
a3.XTick = sort([-3000:1000:3000 lagDiff]);

%
% Align the two signals and replot them. Add 1 to the lag difference to account for the one-based indexing used by MATLAB®.

s1al = s1(-lagDiff+1:end);
t1al = (0:length(s1al)-1)/Fs;

subplot(2,1,1)
plot(t1al,s1al)
title('s_1, aligned')

subplot(2,1,2)
plot(t2,s2)
title('s_2')
xlabel('Time (s)')

% Copyright 2012 The MathWorks, Inc.