I am a total newbe to signal processing and i have a problem which may be quite trivial to most of you guys.
I want to align two short sensor signals (speaking of max. 1000 samples recorded with 20Hz). The signals are sampled with the exact same sample rate and are not necessarily periodic. I use octave to make first experiments and i recognized some confusing behaviour of the xcorr() function in the 'signal' package. If i correlate two short signals the resulting lag value is not really correct. The longer one of the signals is, the better the lag value calculated by the xcorr() function.
Here is what i tested:
pkg load signal
clear all
%generate two short signals
x = -pi:0.05:pi;
sigA = sin(x);
sigB = cos(x);
%plot the original signals
figure 1
subplot(2,1,1);
plot((0:length(sigA)-1), sigA, 'r');
title("sin(x)");
xlabel("Sample index");
grid on;
subplot(2,1,2);
plot((0:length(sigB)-1), sigB, 'b');
title("cos(x)");
xlabel("Sample index");
grid on;
%calculate the cross correlation between signal B and signal A
[c, lag] = xcorr(sigB, sigA);
[~,i] = max(abs(c));
shift = lag(i) %the shifting offset between the two signals
%align the signals
sigA = sigA(abs(shift)+1:end);
maxLength = max(length(sigA), length(sigB)); %for sample index axis range
%plot the aligned signals
figure 2
subplot(2,1,1);
plot((0:length(sigA)-1), sigA, 'r');
title("sin(x) aligned");
xlabel("Sample index");
axis([0, maxLength, -1, 1]);
grid on;
subplot(2,1,2);
plot((0:length(sigB)-1), sigB, 'b');
title("cos(x) aligned");
xlabel("Sample index");
axis([0, maxLength, -1, 1]);
grid on;
The code produces the following figures and calculates a shift of -27 samples:
As you can clearly see, the signal A (sin(x)) is not perfectly aligned! I would have to change the alignment call to
%align the signals
sigA = sigA(abs(shift)+6:end); %where does this offset (1+5) come from?
to align them perfectly:
Now if i generate a longer signal for sigA, this offset disappears completely:
x = -100:0.1:100;
y = -pi:0.05:pi;
sigA = sin(x);
sigB = cos(y);
Then the situation looks like this:
As you can see in the image above, the two signals are perfectly aligned without shifting signal A manually as i had to with the shorter version of signal A.
Now here is an actual signal from my sensor (where signal A is a stored signal and signal B is a subset of signal A, the x axis shows the time in ms):
Same Problem appears here. I would have to shift signal A by 29 samples to the right to align them perfectly.
Why is that? Is cross correlation not the right thing to do for short or non periodic finite signals? Or is there a way to calculate the additional offset to the signal shift?