-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRunge-Kutta 4th order Method
38 lines (31 loc) · 1.03 KB
/
Runge-Kutta 4th order Method
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
% Define the Runge-Kutta 4th order method
function y = rungeKutta(f, x0, y0, h, x_n)
n = (x_n - x0) / h;
x = x0:h:x_n;
y = zeros(1, length(x));
y(1) = y0;
for i = 1:n
k1 = h * f(x(i), y(i));
k2 = h * f(x(i) + 0.5 * h, y(i) + 0.5 * k1);
k3 = h * f(x(i) + 0.5 * h, y(i) + 0.5 * k2);
k4 = h * f(x(i) + h, y(i) + k3);
y(i + 1) = y(i) + (1/6) * (k1 + 2 * k2 + 2 * k3 + k4); %General equation of Euler method
end
end
% Main script
x0 = input('Initial value of x :'); % Initial time
y0 = input('Initial value of y :'); % Initial value of y
h = input('step sizes :'); % Step size
x_n =input('Final Destination :'); % Final time
% Prompt the user to input a function
func_str = input('Enter the function f(x, y) as a string (e.g., ''x*y''): ', 's');
f = str2func(['@(x, y) ' func_str]);
% Call the Runge-Kutta method
y = rungeKutta(f, x0, y0, h, x_n);
% Plot the results
x = x0:h:x_n;
plot(x, y, '-o');
xlabel('x');
ylabel('y');
title('Runge-Kutta 4th Order Method');
grid on;