# How to make a function that uses Runge-Kutta Method

56 vues (au cours des 30 derniers jours)
OvercookedRamen le 5 Oct 2019
Hello, I am trying to create a function that can take in a function and solve it using Runge-Kutta's method. For example, I should be able to input dy/dx = x+y , y(0) = 1 and get an answer from the funtion. I've been working with this equation for a while, I just cannnot figure out how to format this into a function. Here is what I have.
function [OutputX,OutputY] = FunctionBeta_Executor(h,x,y,FunctionA)
h=1.5; % step size
x = 0:h:3; % Calculates upto y(3)
y = zeros(1,length(x));
y(1) = 5; % initial condition
FunctionA = F_xy; % change the function as you desire
for i=1:(length(x)-1)
i=1:(length(x)-1) % calculation loop
k1 = F_xy(x(i),y(i));
k2 = F_xy(x(i)+0.5*h,y(i)+0.5*h*k1);
k3 = F_xy((x(i)+0.5*h),(y(i)+0.5*h*k2));
k4 = F_xy((x(i)+h),(y(i)+k_3*h));
y(i+1) = y(i) + (1/6)*(k1+2*k2+2*k3+k4)*h; % main equation
end
end
% For example, FunctionA might be dy/dx = x+y , with inital conditions y(0)=1.
##### 0 commentairesAfficher -1 commentaires plus anciensMasquer -1 commentaires plus anciens

Connectez-vous pour commenter.

### Réponse acceptée

Sulaymon Eshkabilov le 5 Oct 2019
Hi,
Here is the corrected code:
function [x, y] = FunctionBeta_Executor(F)
% Note that F function expression is defined via Function Handle: F = @(x, y)(x+y)
% change the function as you desire
h=0.15; % step size (smaller step size gives more accurate solutions)
x = 0:h:3; % x space
y = zeros(1,length(x)); % Memory allocation
y(1) = 5; % initial condition
for i=1:(length(x)-1)
% i=1:(length(x)-1) % calculation loop
k1 = F(x(i),y(i));
k2 = F(x(i)+0.5*h,y(i)+0.5*h*k1);
k3 = F((x(i)+0.5*h),(y(i)+0.5*h*k2));
k4 = F((x(i)+h),(y(i)+k3*h));
y(i+1) = y(i) + (1/6)*(k1+2*k2+2*k3+k4)*h; % main equation
end
figure, plot(x, y) % To see the solution results
end
Now you can test the above function with the followings, e.g. in the command window:
>> F = @(x, y)(x+y);
>> [OutputX,OutputY] = FunctionBeta_Executor(F);
Good luck.
##### 2 commentairesAfficher 1 commentaire plus ancienMasquer 1 commentaire plus ancien
Sulaymon Eshkabilov le 6 Oct 2019
It is a pleasure that I could be of some help.

Connectez-vous pour commenter.

### Catégories

En savoir plus sur Programming dans Help Center et File Exchange

### Community Treasure Hunt

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

Start Hunting!