0
$\begingroup$

one can use the MMA built-in function ListCorrelate to compute e.g. the autocorrelation function of a discrete data set:

data = RandomVariate[NormalDistribution[0., 1.], 10^2];
ListCorrelate[data, data, {1, 1}, 0]/Range[Length[data], 1., -1.]

Now this function gives me the acf of any time lag possible and thus returns a list of the same length as data. I wonder whether it is possible to still rely on ListCorrelate (or another built-in function I am unaware) but compute the acf only for certain time lags which I specify upon calling ListCorrelate.

[Edit]

The following three ways of computing the acf are equivalent (except for rounding errors):

(*FFT approach*)    
SetOptions[#, FourierParameters -> {1, -1}] & /@ {Fourier, 
   InverseFourier};
acf1[lis_?VectorQ] := 
 Module[{data, acf, len = Length@lis}, 
  data = Join[lis, ConstantArray[0., len]];
  acf = InverseFourier[Abs[Fourier@data]^2];
  acf = Re@acf[[1 ;; len]]/Range[len, 1., -1.]]

(*Built-in function ListCorrelate*)
acf2[lis_?VectorQ] := 
 ListCorrelate[lis, lis, {1, 1}, 0]/Range[Length[lis], 1., -1.]

(*Compiled function*)
acf3 = Compile[{{data, _Real, 1}, {m, _Integer}}, 
   Block[{len = Length[data]}, 
    Sum[1./(len - m)*Compile`GetElement[data, n + m]*
      Compile`GetElement[data, n], {n, 1, len - m}]],
   Parallelization -> True, RuntimeAttributes -> {Listable}, 
   CompilationOptions -> {"InlineExternalDefinitions" -> True}, 
   CompilationTarget -> "C", RuntimeOptions -> "Speed"];

(*Test for equality*)
n = 10;
SameQ[Round[acf1[data], 10.^-n], Round[acf2[data], 10.^-n], 
 Round[acf3[data, Range[0, Length[data] - 1]], 10.^-n]]

Now with respect to timings the compiled function becomes the slowest one if the length of data is increasing. However, with this way of computing the acf I can determine the number of points of the resulting list. Is this possible with another approach that might be faster e.g. using a built-in function?

[Edit]

I stumbled now over the built-in functions CorrelationFunction[] and CovarianceFunction[]. Applied to data they don't give exactly the same values for the ACF. Why is this the case? I assume it has to do with the bias of the estimator? Which one am I supposed to use then?

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.