<P>function Y = ode4(odefun,tspan,y0,varargin)<BR>%ODE4 Solve differential equations with a non-adaptive method of order 4.<BR>% Y = ODE4(ODEFUN,TSPAN,Y0) with TSPAN = [T1, T2, T3, ... TN] integrates <BR>% the system of differential equations y' = f(t,y) by stepping from T0 to <BR>% T1 to TN. Function ODEFUN(T,Y) must return f(t,y) in a column vector.<BR>% The vector Y0 is the initial conditions at T0. Each row in the solution <BR>% array Y corresponds to a time specified in TSPAN.<BR>%<BR>% Y = ODE4(ODEFUN,TSPAN,Y0,P1,P2...) passes the additional parameters <BR>% P1,P2... to the derivative function as ODEFUN(T,Y,P1,P2...). <BR>%<BR>% This is a non-adaptive solver. The step sequence is determined by TSPAN<BR>% but the derivative function ODEFUN is evaluated multiple times per step.<BR>% The solver implements the classical Runge-Kutta method of order 4. <BR>%<BR>% Example <BR>% tspan = 0:0.1:20;<BR>% y = ode4(@vdp1,tspan,[2 0]); <BR>% plot(tspan,y(:,1));<BR>% solves the system y' = vdp1(t,y) with a constant step size of 0.1, <BR>% and plots the first component of the solution. <BR>%</P>
<P>if ~isnumeric(tspan)<BR> error('TSPAN should be a vector of integration steps.');<BR>end</P>
<P>if ~isnumeric(y0)<BR> error('Y0 should be a vector of initial conditions.');<BR>end</P>
<P>h = diff(tspan);<BR>if any(sign(h(1))*h <= 0)<BR> error('Entries of TSPAN are not in order.') <BR>end </P>
<P>try<BR> f0 = feval(odefun,tspan(1),y0,varargin{:});<BR>catch<BR> msg = ['Unable to evaluate the ODEFUN at t0,y0. ',lasterr];<BR> error(msg); <BR>end </P>
<P>y0 = y0(:); % Make a column vector.<BR>if ~isequal(size(y0),size(f0))<BR> error('Inconsistent sizes of Y0 and f(t0,y0).');<BR>end </P>
<P>neq = length(y0);<BR>N = length(tspan);<BR>Y = zeros(neq,N);<BR>F = zeros(neq,4);</P>
<P>Y(:,1) = y0;<BR>for i = 2:N<BR> ti = tspan(i-1); if ~mod(i,100), disp(['t = ' num2str(ti)]), end<BR> hi = h(i-1);<BR> yi = Y(:,i-1);<BR> F(:,1) = feval(odefun,ti,yi,varargin{:});<BR> F(:,2) = feval(odefun,ti+0.5*hi,yi+0.5*hi*F(:,1),varargin{:});<BR> F(:,3) = feval(odefun,ti+0.5*hi,yi+0.5*hi*F(:,2),varargin{:}); <BR> F(:,4) = feval(odefun,tspan(i),yi+hi*F(:,3),varargin{:});<BR> Y(:,i) = yi + (hi/6)*(F(:,1) + 2*F(:,2) + 2*F(:,3) + F(:,4));<BR>end<BR>Y = Y.';<BR></P> |