Matlab Euler-explicit with adaptable step for ODE system

499 Views Asked by At

I have the following system of differential equations (it is a simplified model for the activation of a neuron, but it is not really important for the question): $$\frac{dV}{dt} = V - \frac{V^3}{3} - n^2 + I_{\text{app}}$$where $I_{\text{app}}$ is a function of time or a constant. And: $$\frac{dn}{dt} = 0.1\left(\frac{2}{1-\exp(-5V)}-n\right)$$ I want to solve this system using Euler's explicit method that I have to make myself and, also, using ode45.

I have done as follows:

function x = nagumo1(t, y, f)
Iapp = f(t);
e = 0.1;
F = 2/(1+exp(-5*y(1)));
n0 = 0;
x = zeros(1, 2);
x(1) = y(1) - (y(1).^3)/3 - y(2).^2 + Iapp;
x(2) = e.*(F + n0 - y(2));
end

which calculates the derivatives at time t, with initial conditions $y = [V, n]$

Now my function Euler Explicit is:

function x =  EulerExplicit1(V0, n0, tspan, Iapp)

format shorteng;

erreura = 10^-2;
erreurr = 10^-2;

h = 0.1;

to =tspan(1, 1) + h;
temps = to;
tf = tspan(1, 2);

y = zeros(1,2);
yt1 = zeros(1, 2);
yt2 = zeros(1, 2);
y = [V0, n0];

z = y;

i = 1;

s = zeros(1, 2);
st1 = zeros(1, 2);

for t = to:h:(tf - h)

   s = nagumo1(to+i*h, y, Iapp);
   y = y + h*s;
   yt1 = y + (h/2)*s;
   st1 = nagumo1(to+(i*h+h/2), yt1, Iapp);
   yt2 = yt1 + (h/2)*st1;

   if abs(yt2-y)>(erreura+erreurr*abs(y))
      test = 0;
   else
      h = h*2;
      test = 0;
   end

   while test == 0

      if abs(yt2-y)>(erreura+erreurr*abs(y)) & h>0.005
         h = h/2;
         s = nagumo1(to+i*h, y, Iapp);
         y = y + h*s;
         yt1 = y + (h/2)*s;
         st1 = nagumo1(to+i*h+h/2, yt1, Iapp);
         yt2 = yt1 + (h/2)*st1;
      else
         test = 1;
      end
   end

   temps(i)=to+i*h;
   z = [ z ; y ];
   i = i+1;

end

x = zeros(size(z));
x = z;

disp('Nombre d iterations:');

disp(i);

temps(i) = 0;

disp(temps);

disp(length(x(:, 1)));

plot(temps, x(:, 1:end), 'r');

grid;


end

My main problem is the plotting of the solution. I have difficulty creating the time vector since the step is varying. I would also like to see how I could implement ode45 for this.

P.S I don't seem to be able to fix the formatting. You're welcome to edit.