% Runge-Kutta method % % solves eqn 2.5.6 y'=-2*x*y, y(0)=2 % the exact answer y(x) = 2*exp(-x^2) % clear all; f=inline('-2*x*y'); yx=inline('2*exp(-x.^2)'); x0=0.0; y0=2.0; n=5; xx=zeros(1,n+1); yy=zeros(1,n+1); xn=1.0; h=(xn-x0)/n; xx(1)=x0; yy(1)=y0; for i=1:n x=xx(i); y=yy(i); k1=f(x,y); k2=f(x+0.5*h,y+0.5*h*k1); k3=f(x+0.5*h,y+0.5*h*k2); k4=f(x+h,y+h*k3); xx(i+1)=x+h; yy(i+1)=y+h/6*(k1+2*k2+2*k3+k4); end %figure; plot(xx,yy,'b*'), %title('Runge-Kutta method: Approximate solution'); x=linspace(x0,xn,100); figure; plot(x,yx(x),'r-',xx,yy,'b*'); title('Runge-Kutta method: Exact and computed solutions')