title: MATLAB code help. Backward Euler method
body: <p>Here is the <a href="http://en.wikipedia.org/wiki/MATLAB" rel="nofollow noreferrer">MATLAB</a>/<a href="http://en.wikipedia.org/wiki/FreeMat" rel="nofollow noreferrer">FreeMat</a> code I got to solve an <a href="http://en.wikipedia.org/wiki/Ordinary_differential_equation" rel="nofollow noreferrer">ODE</a> numerically using the <a href="http://en.wikipedia.org/wiki/Backward_Euler_method" rel="nofollow noreferrer">backward Euler</a> method. However, the results are inconsistent with my textbook results, and sometimes even ridiculously inconsistent. What is wrong with the code?</p>
  
  <pre><code>function [x,y] = backEuler(f,xinit,yinit,xfinal,h)
  
      %f - this is your y prime
      %xinit - initial X
      %yinit - initial Y
      %xfinal - final X
      %h - step size
  
      n = (xfinal-xinit)/h; %Calculate steps
  
      %Inititialize arrays...
      %The first elements take xinit and yinit corespondigly, the rest fill with 0s.
      x = [xinit zeros(1,n)];
      y = [yinit zeros(1,n)];
  
      %Numeric routine
      for i = 1:n
          x(i+1) = x(i)+h;
          ynew = y(i)+h*(f(x(i),y(i)));
          y(i+1) = y(i)+h*f(x(i+1),ynew);
      end
  end
  </code></pre>