function [t,u]=cranknic(odefun,tspan,y,Nh,varargin) %CRANKNIC Solve differential equations using the % Crank-Nicolson method. % [T,Y]=CRANKNIC(ODEFUN,TSPAN,Y0,NH) with TSPAN=[T0,TF] % integrates the system of differential equations % y'=f(t,y) from time T0 to TF with initial condition % Y0 using the Crank-Nicolson method on an equispaced % grid of NH intervals.Function ODEFUN(T,Y) must return % a column vector corresponding to f(t,y). Each row in % the solution array Y corresponds to a time returned % in the column vector T. % [T,Y] = CRANKNIC(ODEFUN,TSPAN,Y0,NH,P1,P2,...) passes % the additional parameters P1,P2,... to the function % ODEFUN as ODEFUN(T,Y,P1,P2...). tt=linspace(tspan(1),tspan(2),Nh+1); u(:,1)=y; global the_h the_t the_y the_odefun; the_h=(tspan(2)-tspan(1))/Nh; the_y=y; the_odefun=odefun; for the_t=tt(2:end) [w info] = fsolve('cranknicfun',the_y); u = [u w]; the_y = w; end t=tt; clear the_h the_t the_y the_odefun; end function z=cranknicfun(w) global the_h the_t the_y the_odefun; z=w-the_y-0.5*the_h*(feval(the_odefun,the_t,w)+feval(the_odefun,the_t,the_y)); end