function example1_rk(lambda,N) % EXAMPLE1_RK solve ODE with Runge Kutta method % example1_rk(lambda,N) computes a sequence of time points t % (in the interval [0,1]) and approximate solutions U1 and U2 at those time % points to the problem u'(t)=lambda*u with u(0)=1 (with exact solution % u(t)=exp(lambda*t)). % The approximate solution U1 is computed using the explicit Euler method % with N+1 timesteps and the approximate solution U2 uses the improved % Euler scheme % exact solution uexact=@(t,lambda) exp(lambda*t); figure(1), clf fplot(@(t) uexact(t,lambda),[0,1],'b','linewidth',2), hold on t=linspace(0,1,N+1); dt=t(2)-t(1); % vector for explicit Euler solutions U1=zeros(1,N+1); % initial condition U1(1)=1; % vector for improved Euler solutions U2=U1; for n=1:N U1(n+1)=U1(n)*(1+lambda*dt); U2(n+1)=U2(n)*(1+lambda*dt+(lambda*dt)^2/2); end figure(1) plot(t,U1,'r',t,U2,'g','linewidth',2) xlabel('t','fontsize',20), ylabel('u','fontsize',20) legend('exact solution','explicit Euler','improved Euler','fontsize',20,'location','NorthWest') title(['Solution with N=',num2str(N),' and lambda=',num2str(lambda)],'fontsize',20) % exact solution at grid points Ue=uexact(t,lambda); figure(2),clf plot(t,(U1-Ue),'r',t,(U2-Ue),'g','linewidth',2) xlabel('t','fontsize',20), ylabel('error','fontsize',20) legend('error in explicit Euler','error in improved Euler','location','SouthWest','fontsize',20) title(['Error with N=',num2str(N),' and lambda=',num2str(lambda)],'fontsize',20) disp(['Error in explicit Euler solution at t=1 is ',num2str(abs(U1(end)-Ue(end)))]) disp(['Error in improved Euler solution at t=1 is ',num2str(abs(U2(end)-Ue(end)))])