MATLAB: How to insert an if conditional in ode45

conditionalifode45

Hi, I'm trying to simulate a leaky integrate-and-fire model. I'm using Ode45, it all works well but I want to insert an If conditional so that when the y value is less than a specific value (-50), y must reset to the value -65. I have no idea about how to implement this. Any suggestions? Thanks a lot.
x0=-70;
t0=0;
dt=0.1;
tmax=2;
tvec=t0:dt:tmax;
[t,x]=ode45(@test_ode, tvec, x0)
plot (t,x)
function [dydt]=test_ode(t,y)
dydt=-1/10*y+13
end

Best Answer

Try this:
x0=-70;
t0=0;
dt=0.1;
tmax=20;
% tvec=t0:dt:tmax;
tvec = [t0 tmax];
opts = odeset('Events',@depolEvents);
for k = 1:10
[t{k},x{k}]=ode45(@test_ode, tvec, x0, opts);
x0 = -65;
tvec = [t{k}(end) t{k}(end)+tmax]
% tvec = t{k}(end) : dt : t{k}(end)+tmax;
end
tv = cat(1,t{:});
xv = cat(1,x{:});
figure
plot (tv,xv)
grid
function [dydt]=test_ode(t,y)
dydt=-1/10*y+13;
end
function [position,isterminal,direction] = depolEvents(t,y)
position = y(1) + 50; % The value that we want to be zero
isterminal = 1; % Halt integration
direction = 1; % The zero can be approached from either direction
end
This uses the techniques in ODE Event Location to stop the integration that is restartted in the next increment of the loop.
If it does not do what you want as written (since I may not have understood exactly what you want to do), experiment with it to get the result you want.