Cross-correlation signal alignment

6 views (last 30 days)
I would like to align two pulses through the use of cross-correlation. I create two pulses located at different parts within a sequence of 100 samples. For instance:
sig1 = zeros(1,100);
sig1(71:90) = 1;
sig2 = zeros(1,100);
sig2([21:41]) = 1;
I then do the cross-correlation between both signals
[xc1,l1] = xcorr(sig1,sig2);
[mx1,ix1] = max(xc1);
Usign the lag information from cross-correlation I can align both sequences where the maximum cross-correlation is found.
plot(1:100,sig1,'.-','linewidth',2);hold on;grid on;
plot((1:100)+l1(ix1),sig2,'.-','linewidth',2);hold on;grid on;
But this only seem to work when sig2 is not wrapped around the begin and the end. For the case where sig2 is:
sig2 = zeros(1,100);
sig2([1:10 91:100]) = 1;
Then the procedure doesn't work. Probably I should wrap the lags and the signal to align the sig2 pulse to the master sig2? Perhaps I should do circular cross-correlation in frequency domain or convolution? Thanks

Accepted Answer

William Rose
William Rose on 15 Dec 2022
Edited: William Rose on 16 Dec 2022
[edit: Add comment about circular correlation; correct typos.]
You need to use a circular correlation, because that treats each signal as if it wraps around on itself. Unfortunately, xcorr() does not have a 'circular' option. Therefore try the following to get the circular correlation function:
Here is an answer from @MathWorks Support Team at this site:
Use the inverse FFT of the point-by-point product of the FFT and the conjugate FFT of the signals.
circcorr_ab = ifft(fft(a).*conj(fft(b)));
Here is your code using the function above.
sig1 = zeros(1,100);
sig1(71:90) = 1;
sig2 = zeros(1,100);
sig2([21:40]) = 1;
[xc1,l1] = xcorr(sig1,sig2);
[mx1,ix1] = max(xc1);
subplot(311), plot(1:100,sig1,'.r-');hold on;grid on;
plot((1:100)+l1(ix1),sig2,'xb-');hold on;grid on;
% Make a new sig2
sig2 = zeros(1,100);
sig2([1:10 91:100]) = 1;
% Compute circular cross correlation with inverse FFT
xc2 = ifft(fft(sig1).*conj(fft(sig2)));
% Find max of circulation cross correlation
[mx2,ix2] = max(xc2);
% Plot shifted signal
plot(1:100,sig1,'.r-');hold on;grid on;
plot((1:100)+l2(ix2),sig2,'xb-');hold on;grid on;
% Middle plot looks incomplete
% Extend sig2, then plot sig1 and the extended sig2
% Plot sig1 and extended sig2
plot(1:100,sig1,'.r-');hold on;grid on;
plot((1:(100+abs(l2(ix2))))+l2(ix2),sig2ext,'xb-');hold on;grid on;
The middle plot looks incomplete, so I extended sig2, then plotted sig1 and extended sig2.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!

Translated by