You're trying to change the ODEs from within the integration function by adding large discontinuities (the if
statements). This is bad practice and can lead to all sorts of issues. Don't do it. Instead you need to call ode45
multiple times and change the the ODE function – or the parameters you give it. See my answer here for further details and some examples.
You also seem to be trying to record the "history" of the evaluated solution. You can't do this. You cannot rely on the order that your ODE function gets called by ode45
or how many times it gets called per time step (maybe many times in the case a failed step). What you seem to be trying to do just is not possible with ode45
and the other ODE Suite functions. However, it's likely that whatever want to do can be accomplished in some better, more natural way. Or you may need to implement your own integration scheme – but this is rarely necessary.
If all you're trying to do by recording the value of the previous step, is determine when to switch between the parameter a
and the parameter c
, then you need a way of determining that point accurately (your if
statements, even if they work, will not be accurate). If the switch occurs at a particular point in time, then it's easy: just perform two integrations over the necessary time spans as shown at the link above. If the switch occurs at a condition that depends on the state x
, then you'll need to learn about event functions. You can read about those in the help and documentation, this article from the MathWorks, and also my answers to this question and this question.