I'm trying to write a matlab function to solve RK4 and store it in my computer to be called when needed.

1 view (last 30 days)
Below is my attempt at the function but when it is run there are issues. could someone correct it and post their version?
function [x,y] = Rk4(dy_dx,x_1,y_1,x_end,h_step)
%dy_dx = differential function
%x_1 = first x value
%y_1 = first y value
%x_end = final x value
%h_step = step size
%Initialize
syms x y(x) u;
dy_dx(x, u) = subs(dy_dx, y(x), u);
dy_dx = matlabFunction(dy_dx); % lets matlab interpret the value as a number
%Initialize Storage
x_all = [x_1:h_step:x_end];
y_store = zeros(length(x_all));
y_store(1) = y_1;- %makes running this code easier on the computer
%Loop -> Summation
for i = 1:length(x_all)-1
k_1 = dy_dx(x_all(i), y_store(i));
k_2 = dy_dx(x_all(i) + 0.5*h_step, y_store(i) + 0.5*h_step*k_1);
k_3 = dy_dx(x_all(i) + 0.5*h_step, y_store(i) + 0.5*h_step*k_2);
k_4 = dy_dx(x_all(i) + h_step, y_store(i) + h_step*k_3);
y_store(i+1) = y_store(i) + h_step*(k_1 + 2*k_2 + 2*k_3 + k_4)/6;
end
%Results
y_store(length(y_store))
plot(x_all, y_store);
end
  1 Comment
John D'Errico
John D'Errico on 2 Dec 2022
Don't just say there are some issues. That forces someone to spend the time to run it and test it fully, and even then we might not know what you think are the issues. What do YOU think is a problem? If you get an error, then show the COMPLETE error. Everything in red.

Sign in to comment.

Answers (1)

Torsten
Torsten on 2 Dec 2022
Edited: Torsten on 2 Dec 2022
If you call RK4 correctly, it will work.
syms y(x) dy_dx(x)
dy_dx(x) = x + y(x);
x_1 = 0;
y_1 = 1;
x_end = 1;
h_step = 0.01;
[x,y] = Rk4(dy_dx,x_1,y_1,x_end,h_step);
fun = @(x,y) x+y;
[X,Y] = ode45(fun,x_1:h_step:x_end,y_1);
plot(X,Y-y)
grid on
function [x_all,y_store] = Rk4(dy_dx,x_1,y_1,x_end,h_step)
%dy_dx = differential function
%x_1 = first x value
%y_1 = first y value
%x_end = final x value
%h_step = step size
%Initialize
syms x y(x) u
dy_dx(x, u) = subs(dy_dx, y(x), u);
dy_dx = matlabFunction(dy_dx); % lets matlab interpret the value as a number
%Initialize Storage
x_all = [x_1:h_step:x_end];
y_store = zeros(length(x_all),1);
y_store(1) = y_1; %makes running this code easier on the computer
%Loop -> Summation
for i = 1:length(x_all)-1
k_1 = dy_dx(x_all(i), y_store(i));
k_2 = dy_dx(x_all(i) + 0.5*h_step, y_store(i) + 0.5*h_step*k_1);
k_3 = dy_dx(x_all(i) + 0.5*h_step, y_store(i) + 0.5*h_step*k_2);
k_4 = dy_dx(x_all(i) + h_step, y_store(i) + h_step*k_3);
y_store(i+1) = y_store(i) + h_step*(k_1 + 2*k_2 + 2*k_3 + k_4)/6;
end
end

Categories

Find more on Tables in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by