MATLAB: Changing the parameters of the dynamical system in the middle of simulation

MATLAB

Suppose I want to run
f = @(t,x) [-x(1)*x(2);x(1)*x(2)-x(2);x(2)]
[t,xa]=ode45(f,[0 6], [4 0.1 0]);
this runs the system from time 0 to 6. Suppose now I want to
*run the system from time 0 to 2
*from time 2, want to run
f = @(t,x) [-0.5*x(1)*x(2);0.7*x(1)*x(2)-x(2);x(2)]
How can one write a script? Thank you.

Best Answer

For your case the easiest way to proceed is to simply run the ODE-integration first from 0-2 and then use the end-state as initial conditions for an integration from 2 to your end-time. Something like this:
f0to2 = @(t,x) [-x(1)*x(2);x(1)*x(2)-x(2);x(2)]
f2toend = @(t,x) [-0.5*x(1)*x(2);0.7*x(1)*x(2)-x(2);x(2)]
x0 = [4 0.1 0];
[ta,xa]=ode45(f0to2,[0 2], x0);
x0 = xa(end,:);
[tb,xb]=ode45(f2toend,[2 6], x0);
Then you'll have to cat the solutions together. You might consider running with a preset time-step of your liking instead of giving ode45 the liberty to chose on its own
In general when things change in your ODE you can typically use the events handling to take care of such changes, for example bouncing balls and the like, for an example of that look at ballode.
HTH