title: Fourth-order Runge–Kutta method (RK4) collapses after a few iterations
body: <p>I'm trying to solve:</p>
  
  <pre><code>x' = 60*x - 0.2*x*y;
  y' = 0.01*x*y - 100* y;
  </code></pre>
  
  <p>using the fourth-order Runge-Kutta algorithm.</p>
  
  <p>Starting points: <code>x(0) = 8000, y(0) = 300</code> range: <code>[0,15]</code></p>
  
  <p>Here's the complete function:</p>
  
  <pre><code>function [xx yy time r] = rk4_m(x,y,step)
  A = 0;
  B = 15;
  
  h = step;
  iteration=0;
  t = tic;
  
  xh2 = x;
  yh2 = y;
  
  
  rr = zeros(floor(15/step)-1,1);
  xx = zeros(floor(15/step)-1,1);
  yy = zeros(floor(15/step)-1,1);
  AA = zeros(1, floor(15/step)-1);
  
  while( A &lt; B)
  
  
      A = A+h;
      iteration = iteration + 1;
  
      xx(iteration) = x;
      yy(iteration) = y;
      AA(iteration) = A;
      [x y] = rkstep(x,y,h);
  
  
      for h2=0:1
          [xh2 yh2] = rkstep(xh2,yh2,h/2);
      end
      r(iteration)=abs(y-yh2);
  
  
  
  end
  time = toc(t);
  
  xlabel('Range');
  ylabel('Value');     
  hold on
  plot(AA,xx,'b');
  plot(AA,yy,'g');
  plot(AA,r,'r');
  fprintf('Solution:\n');
  fprintf('x: %f\n', x);
  fprintf('y: %f\n', y);
  fprintf('A: %f\n', A);
  fprintf('Time: %f\n', time);
  
  end
  
  function [xnext, ynext] = rkstep(xcur, ycur, h)
      kx1 = f_prim_x(xcur,ycur);
      ky1 = f_prim_y(xcur,ycur);
  
      kx2 = f_prim_x(xcur+0.5*h,ycur+0.5*h*kx1);
      kx3 = f_prim_x(xcur+0.5*h,ycur+0.5*h*kx2);
      kx4 = f_prim_x(xcur+h,ycur+h*kx3);
  
      ky2 = f_prim_y(xcur+0.5*h*ky1,ycur+0.5*h);
      ky3 = f_prim_y(xcur+0.5*h*ky2,ycur+0.5*h);
      ky4 = f_prim_y(xcur+h*ky2,ycur+h);
  
      xnext = xcur + (1/6)*h*(kx1 + 2*kx2 + 2*kx3 + kx4);
      ynext = ycur + (1/6)*h*(ky1 + 2*ky2 + 2*ky3 + ky4);
  end
  
  function [fx] = f_prim_x(x,y)
  fx = 60*x - 0.2*x*y;
  end
  
  function [fy] = f_prim_y(x,y)
  fy = 0.01*x*y - 100*y;
  end
  </code></pre>
  
  <p>And I'm running it by executing: <code>[xx yy time] = rk4_m(8000,300,10)</code></p>
  
  <p>The problem is that everything collapses after 2-3 iterations returning useless results. What am I doing wrong? Or is just this method not appropriate for this kind equation?</p>
  
  <p>The semicolons are intentionally omitted.</p>
  
  <hr>
  
  <p>Looks like I didn't pay attention to actual <code>h</code> size. It works now! Thanks!</p>