MATLAB: ODE with a parameter that chages at each time step

ode45

Hi all,
I have a problem solving a ODE with Matlab.
The ODE is:
y(t)'of j= [(sigma^2)/(2*k)]*(1-y(t)*k)*(y(t)-[y(t)of j-1])^2;
I've written this code:
mu = 0.20;
r = 0.05;
sigma = 0.40;
T = 10;
k = 0.2;
IC = 0.0;
TSPAN = 0:0.1:T;
TSPANlength = length(TSPAN);
%Number of crahes
N=3;
PiVektor = zeros(N,TSPANlength);
for i=1:1:N
[~, PiVektor(i, :)] = ode23(@(t, pi)myodeN(pi, PiVektor(i-1),k,mu,r,sigma),TSPAN, IC);
PiVektor(i,:) = fliplr(PiVektor(i,:));
figure(1);
hold on
plot(TSPAN,PiVektor(i,:));
end
function dpidt = myodeN(pi,piNminus1,k,mu,r,sigma)
dpidt = [(sigma^2)/(2*k)]*(1-pi*k)*(pi-piNminus1)^2;
end
The problem is that in this way the ODE is always calculated using just the first value from the previous calculation.
Is it possibile to change the value of my parameter at each time step?
Thanks a lot,
Ilaria

Best Answer

So you will have a sequence of ODEs to solve starting with the one for 0-crashes and then you want to plug in that solution into the solution for the 1-crash ODE?
If so I would call the ode-solver with
[tOut{i}, pOut{i}] = ode23(@(t, pi)myodeN(t,pi,{tOut{i-1},pOut{i-1},k,mu,r,sigma),TSPAN, IC);
and then modify your myodeN to something like this:
function dpidt = myodeN(t,pi,TnPprev,k,mu,r,sigma)
dpidt = [(sigma^2)/(2*k)]*(1-pi*k)*(pi-interp1(TnPprev{1},TnPprev{2},t))^2;
That way you interpolate a value for piNminus1 for times t from the "piNminus1" values (that you have values for at the choosen times). You could also use the single-output format of ode-solvers and then instead of explicitly interpolating use deval to calculate the values of piNminus1 for any given time.
HTH