Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

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?

share|improve this question

3 Answers 3

up vote 3 down vote accepted

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.

share|improve this answer

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.

share|improve this answer

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.