0
$\begingroup$

I have a bunch of ODEs I am trying to solve using ode45 in MATLAB. I have hidden the details of the equations to keep it simple (so as to build a general algorithm)!

\[\frac{dR}{dt}= F_{1}(R,N) \quad\text{........................(Eq.1)}\] \[\frac{dN_{1}}{dt}= F_{2}(t) \quad\text{.............................(Eq.2)}\] \[\frac{dN_{2}}{dt}= F_{3}(R,N) \quad\text{.......................(Eq.3)}\] \[\frac{dN}{dt}= \frac{dN_{1}}{dt} \quad \text{or} \quad \frac{dN_{2}}{dt} \quad \text{based on a criteria of } max(-\frac{dN_{1}}{dt},\frac{dN_{2}}{dt}) \] So, basically I want is, to solve for R, N for 2 cases. The ODE solver should stop when the criteria is met and should restart with Case 2 by solving a different ODE set. \[\text{Case 1}: \frac{dR}{dt}; \frac{dN_{1}}{dt}\] \[\text{Case 2}: \frac{dR}{dt}; \frac{dN_{2}}{dt}\]

I know I need an event function to do this. Unfortunately, I am new to this for which your help is solicited (to check if my code is functioning properly). I also can't think of any test functions to test the algorithm. Let me know if any other info is required.

clc
clear

y0   = [0.1,0.1,0.1,0.21]; %random initial nos.
t0   = 0;                  %random no.
tEnd = 10;                 %random no.

opt = odeset('RelTol', 1e-3);

y = y0;
t = t0;

State = 1;

while t(end) < tEnd
    yprime = myFunction(t, y, State);
    
    if yprime(2) > yprime(3)
        State = 1;
    else
        State = 2;
    end
    
    
    fcn = @(t,y) myFunction(t, y, State);
    
    opt = odeset('Events', @(t, y) myEvents(t,y,State));
    [at, ay] = ode45(fcn, [t(end), tEnd], y(end, :),opt);
   
    t = cat(1, t, at(2:end));
    y = cat(1, y, ay(2:end, :));
end

plot(t,y(:,4))


function [yprime] = myFunction(t, y, State)
yprime = [5*y(1); 4*y(4) + 77*t ; 30*y(4) - 7*t]; %random funcs.
if State == 1
    yprime(4) = yprime(2);
    disp('state is 1')
else
    yprime(4) = yprime(3);
    disp('state is 2')
end
end


function [val,isterm,dir] = myEvents(t,y,State)

fun = myFunction(t, y, State);

val      =  fun(2) - fun(3);
isterm   =  0;
dir      =  0;

end
$\endgroup$
2
  • $\begingroup$ I don't have a working Matlab to test this, but your code seems ok. Have you tried it ? You can easily try it and verify after the fact that the transitions between the different ODEs were correctly performed by looking the zero-crossings of your event function. $\endgroup$ – Laurent90 Apr 16 at 21:28
  • $\begingroup$ Thanks @Laurent90. The program seems to be working but are the event function handlers fine? $\endgroup$ – Ronnie1993 Apr 17 at 14:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.