Runge kutta 4 Matlab program isn't working

43 Views Asked by At

I need to solve a system of first-order differential equations using Runge Kutta 4 orders (the scheme I've used may not be the most common but it's the one I need to use).

The code doesn't work and I don't know why. I'm using Octave and I have a problem with the command window, so I can't see the error.

I tried with the debug and everything went well for the calculation of k1,k2,k3,k4 but when I got to the calculation of v(i+1, :) the program seemed to crash.

Here's my code, the first part is my file where I define the parameters, my function and where I call my ode4' function. The code for my ode4 function is the second code.

clear all
clc



function dtdy=kernel(t,y,sigma,beta,rho)
  dtdy=zeros(2,1)
  dtdy(1)=sigma*y(2)
  dtdy(2)=rho*y(2)+beta*y(1)
end

sigma=1;
rho=-0.9;
beta=-25;
h=0.08;
t=0:h:10;
y0=[0 0.01];

Rk4=ode4(@(t,y)kernel(t,y,sigma,beta,rho),t,y0);
function[tout,v]=ode4(odefun,tspan,v0)
v=zeros(length(tspan),length(v0));
v(1,:)=v0 %initial condition for y(0)
h=tspan(2)-tspan(1); % extract h value from tspan
tout=tspan;

for i=1:(length(tspan)-1)
 
  k1=odefun(tspan(i),v(i,:));
  k2=odefun(tspan(i)+(h/2),v(i,:)+(h/2).*k1);
  k3=odefun(tspan(i)+(h/2),v(i,:)+(h/2).*k2);
  k4=odefun(tspan(i)+h,v(i,:)+h.*k3);
  v(i+1,:)=v(i,:)+(h/6)*(k1+(2*k2)+(2*k3)+k4);
end
end

If somebody could help me to find the mistake in my code it could be great.

0

There are 0 best solutions below