# cross-correlation with time lag

I have two lists with some data.

a={1,2,3,4,5}
b={5,4,3,2,1}


Now I want to compute the cross correlation of the two lists with a time lag of 1, like it is mentioned on wikipedia: https://en.wikipedia.org/wiki/Cross-correlation

The only function I found in mathematica is CorrelationFunction, but this one seems to only compute the autocorrelation of a lists with itself. So I was wondering if there is another function or how do do this. Can anybody help me out?

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.

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 Listas an argument will calculate the auto-correlation. With 2 Lists, it will do cross-correlation.

The function xcorrlagwill 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.

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.

You can try

a = {1, 2, 3, 4, 5};
b = {5, 4, 3, 2, 1};
temporalData = TemporalData[{Transpose[{a, b}]}, Automatic];
correlations = CorrelationFunction[temporalData, {-4, 4}]["Values"]


The cross correlations are given by correlations[[;;,1,2]]

See this related answer for more detail.