You might be basing your approach on your understanding of the explicit Euler method. If that is the case you would be best served by implementing the (exponential) explicit Euler method.
The solver ode45
, as all of the other matlab ODE solvers (without specific options?) has variable step size which is automatically adapted to the problem and the current state. Additionally, during each step the passed right side ODE function is evaluated multiple times. Further, the step size regulator depends on the smoothness to a high order of the right side function, non-smooth loci lead to a drastic reduction in step size and possibly multiple restarts from the same current state, further contradicting your assumptions.
Thus, even if you succeed in implementing your idea, you are adding essentially random noise to your function, rendering the solver useless as basic assumptions are violated. Even if a result is produced, it will have almost nothing to do with what you wanted to achieve.
The fastest way to achieve something like what you want to produce is to identify the times at to which the x
values are associated and use some interpolation function, zero order hold or linear interpolation, to get the correct value at variable times.
Use solution extension to solve every segment using a smooth right side, changing the constant x(k)
for each segment [ tx(k), tx(k+1) ]
. Define the function to have a parameter, avoiding the hassle of global
variables
function dy = ode_filter(t,y,x)
dy = x - 4*y;
end
then call the integrator for the first segment to initialize and then for all the remaining segments using their constant and the segment end.
sol = ode45(@(t,y)ode_filter(t,y,x(1)), [ tx(1) tx(2) ], y0)
for k in 2:N
sol = odextend(sol,@(t,y)ode_filter(t,y,x(k)),tx(k+1));
end
(Always think about using the options mechanism to set costumized, problem specific error tolerances.)