function [t,x]=backeuler(f,x0,t0,tf,h)
   t=[t0:h:tf];
   x=zeros(length(x0),length(t));
   x(:,1)=x0;
   for k=1:length(t)-1
       x(:,k+1)=backeuler_step(f,x(:,k),t(k),h);
   end 
endfunction

function xk1=backeuler_step(f,xk,tk,h)
   xk1=xk;//initial guess
   xk_l=euler_step(f,xk1,tk+h,-h);
   it=0;
   while norm(xk_l-xk)>1e-6*(norm(xk)+1e-3)&it<10
       J=jacobiant(f,xk1,tk+h);
       invH=pinv(eye(J)-J*h);
       xk1=xk1-invH*(xk_l-xk)
       xk_l=euler_step(f,xk1,tk+h,-h);
       it=it+1;
    end
endfunction



function xk1=euler_step(f,xk,tk,h)
    k1=f(xk,tk);
    xk1=xk+h*k1;
endfunction

function J=jacobiant(f,x,t)
 //estimates the Jacobian df/dx evaluated at (x,t) 
  n=length(x);
  J=zeros(n,n);
  fx=f(x,t);
  for i=1:n
    x1=x;
    dx=0.00001*x1(i)+1e-10;
    x1(i)=x1(i)+dx;
    J(:,i)=(f(x1,t)-fx)/dx;
  end
endfunction  