Comparing Time Series data using correlation

I have 2 matrices. Each matrix has a column of time and sensor output at that time. So matrix A has time and sensor output A, and matrix B has time and sensor output B. I want to do a correlation between the two sensors. Unfortunatley, the length of the matrices are slightly different. I try to interpolate the data so that they have a common time vector. However, the correlation of that comes out to be 0. I've read of correlation between two vectors of different lengths. One gets padded with zeros to make them the same size. However, I don't think that will work in my case because it would change the shape of one of the plots. I hope this makes sense. i feel like this would be a common thing but can't seem to find the solution.
Any help would be appreciated.

 Accepted Answer

Both, interpolation and adding zeros will work. But xcorr doesn't need same vector length. For not constant signal sample time the interpolation is needed.
This xcorr example might be usefull for you.
t = 0:0.01:10-0.01;
x = cos(2*pi*0.5*t) + randn(size(t))*0.1;
z = sin(2*pi*0.5*t) + randn(size(t))*0.1;
z([1:350 550:end]) = 0;
[c,lags] = xcorr(x,z,'coeff');
% z = x; z([1:350 550:end]) = [];
% [c,lags] = xcorr(x,z,'none');
subplot(211), plot(t,x,'k',(0:length(z)-1)*0.01,z,'r'), legend('A','B')
subplot(212), plot(lags,c,'k'), xlabel('lags [steps]'), ylabel('corr')

3 Comments

Christian, Thank you for the example. In one case, you padded it with zero, and in another case, you repeat the signal. With my situation, my time vectors are slightly off. I created sort of a test case of my situation to illustrate the point:
clear all
t1 = linspace(0,2*pi);
t2 = linspace(0.1,2*pi+0.1); %slightly shift time vector
a = sin(t1);
b = sin(t2);
plot(t1,a)
hold on
plot(t2,b,'red')
b1 = interp1(t2,b,t1);% interpolating so that time vectors match
[c,lags] = xcorr(b1,a,'coeff');
figure;
plot(lags, c) %why is everything NaN?
When I tried to add an interpolation step prior to cross correlating with your code, I get similarly weird results. It's as if Matlab knows the data was interpolated and doesn't like that. Again, thanks for taking the time to answer my question.
Ahhh! When you interpolate, there may exist some NaNs. If those get carried through to the xcorr function, then everything becomes NaN.
Thank you for all your help!
Change interp1 method to perform extrapolation for out of range values.
b1 = interp1(t2,b,t1,'pchip');
doc interp1

Sign in to comment.

More Answers (0)

Categories

Community Treasure Hunt

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

Start Hunting!