Reputation: 23
I have two time series, y1 and y2 and need to find the time lag between them using cross-correlation in Matlab. Then I need to plot the cross-correlation, align the two plots and replot. I have written a bit of Matlab code to do this but I think the cross-correlation plot is weird and I am unable to interpret it. I am not sure what I am doing wrong here, can you please help? Thanks.
Here is my code at this point:
% Generate time series
t = 1:1000;
y1=2*sin(2*pi*t/5);
y2=2*sin(2*pi*t/5 + 2); % y2 has an introduce phase lag of 2
% Plot the two time series
figure (1)
plot (t,y1, 'b-', t,y2, 'r-');
axis ([0 50 -2 2]), grid;
% compute the cross correlation using the function xcorr
maxlag = length(y1); %# set a max lag value here
[c,lags]=xcorr(y1,y2, 'coeff');% compute cross correlation
figure (2);
plot(lags,c)% plot lag versus correlation
Upvotes: 0
Views: 1220
Reputation: 26069
The issue is that your "signal" is just one long sinusoid from 1 to 1000. so the codes works perfectly well, but you don't understand why the plot is a triangular shape. Well, it is because at the first elements the size of the sample overlap is small (say y1(1:5)+y2(end-4:end)) so the amplitude you get at that point is smaller that when the entire signals overlap (say y1(1:end)+y2(1:end)). See sketch of just a box xcorr with a box (which is what you actually do because you have signal throughout your grid from 1 to 1000)
Upvotes: 2