フィルターのクリア

How to make a function that uses Runge-Kutta Method

21 ビュー (過去 30 日間)
OvercookedRamen
OvercookedRamen 2019 年 10 月 5 日
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.

採用された回答

Sulaymon Eshkabilov
Sulaymon Eshkabilov 2019 年 10 月 5 日
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 件のコメント
OvercookedRamen
OvercookedRamen 2019 年 10 月 5 日
Thank you so much! You're a life saver.
Sulaymon Eshkabilov
Sulaymon Eshkabilov 2019 年 10 月 6 日
It is a pleasure that I could be of some help.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeFunction Creation についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by