cross-correlation with time lag
Related to your question: If you wish to do general cross-correlation (not with a fixed lag of 1), you can use the following functions:
xcorrlag[dat1_, dat2_] := Position[#, Max@#] &[xcorr[dat1, dat2]] - Length[dat1]
xcorr[dat1_, dat2_] := ListCorrelate[dat1, dat2, {-1, 1}, 0]
xcorr[dat_] := xcorr[dat, dat]
Here, xcorr
called with a single List
as an argument will calculate the auto-correlation. With 2 List
s, it will do cross-correlation.
The function xcorrlag
will return the lag at which the largest cross-correlation does occur - useful if you wish to figure out by how much one signal might be delayed versus the other signal.
You can do the cross-correlation between two sequences using ListCorrelate
a = {1, 2, 3, 4, 5};
b = {5, 4, 3, 2, 1};
ListCorrelate[a, b, 1]
This does circular correlation, so you may want to look at the options to get the exact calculation you are looking for.
Try this:
a.RotateLeft[b, 1]
(*45*)
For any other time delay $k$, use a.RotateLeft[b, k]
instead.
If the lists are extremely long and you are trying to compute the cross-correlation with a variety of delays, you can look into an FFT-based convolutive method.