Monday, November 07, 2011

Calculate Time Lag from Cross-correlation in Octave - Matlab

Calculation of time lag or time delay between two identical signal is very important in many areas, especially in system identification. By knowing time delay or time lag, we can analysis the signal such as subtract the output signal length according to the time lag. This problem usually appears in signal processing, control system, process, acoustic (determine time lag between sound sources and microphone) or other systems with input and output data.

In the other side, cross-corelation is useful tools. Using cross-correlation we can find the strongest point of correlation between two signal, and then shift the signal according to distance of strongest point to zero position. But the problem is the x-axis in cross-correlation not the time or sampled time (length), it is index. Let's solve by bringing the problem to computation methods such as GNU/Octave or Matlab.

Suppose, we have two signal in case of signal enhancement process. The first signal is true target signal, and the second is enhanced signal. We want to know, the time lag between true target signal and enhanced signal. The time lag can be resulted because of algorithm processing and others.

First, we read sound data in Octave or Matlab. We type,

[signal, fs]=wavread('signal.wav');

[enhance,fs]=wavread('enhance.wav');

And then, calculate the cross-correlation between signal and enhanced signal using the following command, 

[R, lag]=xcorr(signal, enhance);

plot(R)

You'll get the figure as follows,
Plot of Cross Correlation using Octave

The maximum peak in that plot is the point in which two signals has the strongest correlation. So you must shift the enhance signal to the left. But, how many samples the time lag? Find the point of the maximum peak using the following commands,

[a b]=max(R)

And your will get such this result,

a=830.48

b=76918

To know the time lag, find the length of signal or enhance signal (must be same)

length(signal)

And you got the answer,
ans= 76871

That is the zero point. So, the time lag is
time_lag=b-ans

time_lag=47

The time lag is 47 samples (not seconds), just shift or subtract the enhance signal in first 47 samples. That's the time lag according to the cross-correlation method.
Related Posts Plugin for WordPress, Blogger...