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)!
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