function RK4(f2,a,b,n,y0) %datos %f =el nombre de la funci�n como string %a =limite inferior %b =limite superior %h =longitud del segmento %y0 =f(a) %x =es el vector x %n =numero de segmentos %resultados %y =es el vector f(x) h=(b-a)/n; n=n+1; y=zeros(n,1); x=zeros(n,1); x(1)=a; y(1)=y0; fprintf(' x y \n'); fprintf('====================\n'); fprintf('%10.6f%10.6f\n',x(1),y(1)); for i=1:n-1 k1=feval('f2',x(i),y(i)); k2=feval('f2',x(i)+h/2,y(i)+h*k1/2); k3=feval('f2',x(i)+h/2,y(i)+h*k2/2); k4=feval('f2',x(i)+h,y(i)+h*k3); x(i+1)=a+h*i; y(i+1)=y(i)+h*(k1+2*k2+2*k3+k4)/6; fprintf('%10.6f%10.6f\n',x(i+1),y(i+1)); end
function dydx=f2(x,y) dydx=(y-x-1)^2+2;
>> RK4('f2',0,2,2,1) x y ==================== 0.000000 1.000000 1.000000 3.535848 2.000000520.722026