manipulate - Defining a recursive function with additional parameters that can be used in a Manipulated ListPlot
I'm trying to code up some plots for Autocorrelation Functions in Time Series Analysis, which can often be defined recursively. The goal is then to have Manipulate sliders that allow you to dynamically change the controlling parameters. Here's an example of the sort of plots I'm trying to emulate:
(here, ϕ1 and ϕ2 are the parameters I want to manipulate.)
For this AR(2) model, the ACF, denoted ρk, can be defined recursively as follows:
ρ0=1
ρ1=ϕ11−ϕ2
ρk=ϕ1ρk−1+ϕ2ρk−2
How do I implement this recursion and ListPlot in Mathematica?
I've tried doing:
ρ[0,φ1_,φ2_]:= 1
ρ[1,φ1_,φ2_]:= φ1/(1-φ2)
ρ[k,φ1_,φ2_]:= φ1 * ρ[k-1,φ1,φ2] + φ2 * ρ[k-2,φ1,φ2]
But then the ListPlot, even when plotted for e.g. {k, 0, 10}, only shows ρ[0] and ρ[1]. I'm still a bit new to coding larger projects in Mathematica (only basic ODE StreamPlots in the past), so I think I'm misunderstanding the proper way to handle defining functions.
Answer
The underlying difference equation for AR(2) is a three-term recurrence with constant coefficients. RSolve[]
can directly solve this, after which you can use the solution along with DiscretePlot[]
for visualization.
I will let someone else implement that approach. Instead, let me show how to use LinearRecurrence[]
along with ListPlot[]
:
Manipulate[ListPlot[Rest[LinearRecurrence[{φ1, φ2}, {1, φ1/(1 - φ2)}, n + 1]],
Filling -> Axis, Frame -> True,
FrameLabel -> {"Lag", "\!\(\*SubscriptBox[\(ρ\), \(k\)]\)"},
PlotRange -> All, PlotStyle -> Black],
{{φ1, 1}, 0, 3}, {{φ2, -1/2}, -1, 1}, {{n, 12}, 2, 20, 1}]
Comments
Post a Comment