I want to build and solve a cascade of ODEs, by which term I mean that the first derivative of the k
-th component of the vector x
of (state) variables with respect to time t
depends on x_{k}(t)
itself and on the preceding x_{k-1}(t)
:
d/dt x_{1}(t) = f(x_{0},x_{1})
d/dt x_{2}(t) = f( x_{1},x_{2})
d/dt x_{3}(t) = f( x_{2},x_{3})
.
.
.
d/dt x_{n}(t) = f( x_{n-1},x_{n}).
where x_{0}(t)
is prescribed for all t
in [0,tmax]
, that is, it is not solved for. And indeed, the f()
function is identical for all the equations.
Although I am able to create such a model manually for a small number n
of equations following the syntax of DifferentialEquations
(see the MWE below), I was wondering if there is a more elegant (Julian) way of assembling such set of differential equations. Preferably one that also helps consequent numerical solution - perhaps the structure could be exploited somehow for solving the ODEs.
using DifferentialEquations
using Plots
pyplot()
f(x,u) = -x + u # but could be nonlinear in general
function cascade(dx,x,x0,t)
dx[1] = f(x[1],x0(t))
dx[2] = f(x[2],x[1])
dx[3] = f(x[3],x[2])
dx[4] = f(x[4],x[3])
dx[5] = f(x[5],x[4])
end
xinit = zeros(5)
ti = 0.0
tf = 10.0
tspan = (ti,tf)
x₀(t) = 0.5-t >= 0.0 ? 0.0 : 1.0
prob = ODEProblem(cascade,xinit,tspan,x₀)
sol = solve(prob)
plot(sol.t,x₀,linewidth=2,label="x0")
plot!(sol,linewidth=2,xaxis="t",yaxis="x(t)",label=["x1" "x2" "x3" "x4" "x5"])