How to make a function that uses Runge-Kutta Method

조회 수: 12 (최근 30일)
OvercookedRamen
OvercookedRamen 2019년 10월 5일
편집: David 2024년 12월 9일
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 CenterFile Exchange에서 Calculus에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by