How can I use cross-correlation as a tool to align two signals before subtracting?

6 views (last 30 days)
I have two signals that have a similar behavior but are not aligned. I would like to use cross-correlation to align them. Thereafter, i want to subtract the two signals when aligned.

Answers (1)

dpb
dpb on 2 Mar 2014
Edited: dpb on 2 Mar 2014
Demo of basic idea...
x=rand(1,1000); % a random timeseries
y=circshift(x,[1 -233]); % a copy shifted relative to it
[c,l]=xcorr(x,y,'coeff'); % compute the x-correlation, and lag vector
[~,imx]=max(c);c(imx)=0; % zero out the auto-correlation (0 lag) term
[~,ilg]=max(c), l(ilg) % find the maximum lag otherwise...
ilg =
233
ans =
-767
Since in this case it's an exact copy, it's not surprising you find that the lag is identically the value used in the circular shift--note that it's the 233rd position in the overall correlation vector or the -767th lag; this indicates the shift of the second relative to the first is negative. If had shifted t'other way, would have gotten same values shifted to other side of center (0 lag) position.
The use of the above should be obvious. The reliability of your results will depend heavily upon how similar the actual waveforms are, you may have to do some peak searching and logic to get best guess if the two are only mildly similar. If you've got two waveforms with just a phase shift, however, it'll work nicely.

Community Treasure Hunt

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

Start Hunting!