miércoles, 7 de diciembre de 2022

Runge-Kutta(Order 4) Algorithm using MATLAB (m-file)

https://www.matlabcoding.com/2019/02/runge-kuttaorder-4-algorithm-using.html



Runge-Kutta(Order 4) Algorithm using MATLAB (m-file)


MATLAB Programs:

% Runge-Kutta(Order 4) Algorithm
 % Approximate the solution to the initial-value problem
 % dy/dt=y-t^2+1 ; 0<=t<=2 ; y(0)=0.5;

 f = @(t,y) (y-t^2+1);
 a = input('Enter left end ponit, a:  ');
 b = input('Enter right end point, b:  ');
 n = input('Enter no. of subintervals, n: ');          % n=(b-a)/h
 alpha = input('Enter the initial condition, alpha:  ');

 h = (b-a)/n;
 t = a;
 w = alpha;
 fprintf('  t         w\n');
 fprintf('%5.3f %11.7f\n', t, w);

 for i = 1:n
   k1 = h*f(t,w);
   k2 = h*f(t+h/2.0, w+k1/2.0);
   k3 = h*f(t+h/2.0, w+k2/2.0);
   k4 = h*f(t+h,w+k3);
   w = w+(k1+2.0*(k2+k3)+k4)/6.0;
   t = a+i*h;
   fprintf('%5.3f %11.7f\n', t, w);
   plot(t,w,'b*'); grid on;
   xlabel('t values'); ylabel('w values');
   hold on;
 end


OUTPUTS:

Untitled3_rk4
Enter left end ponit, a:  0
Enter right end point, b:  2
Enter no. of subintervals, n: 10
Enter the initial condition, alpha:  0.5
  t         w
0.000   0.5000000
0.200   0.8292933
0.400   1.2140762
0.600   1.6489220
0.800   2.1272027
1.000   2.6408227
1.200   3.1798942
1.400   3.7323401
1.600   4.2834095
1.800   4.8150857
2.000   5.3053630
>> 

No hay comentarios:

Publicar un comentario