How can I obtain the T and Y for R Runge Kutta method?

3 views (last 30 days)
Hi my friends.
I am new on Function command almost, I have problem that I have to use the Runga-Kutta method to solve it.
I am trying to understand this code, But when I run it, It asks me some variables to input.
Where should put these variables or inputs to run the code and observe the T and Y lists.
I would like to ask your help to guide me in this problem.
thanks.
function R=rk4(f,a,b,ya,M)
% Input: f is the slope function entered as a string 'f'
% a and b are the left and right end points
% ya is the initial condition y(a)
% M is the number of steps
% Output: R=[T',Y'] where T is the vector of abscissas and Y is the vector of ordinates
h=(b-a)/M;
T=zeros(1,M+1);
Y=zeros(1,M+1);
T=a:h:b;
Y(1)=ya;
for j=1:M
k1=h*feval(f,T(j),Y(j));
k2=h*feval(f,T(j)+h/2,Y(j)+k1/2);
k3=h*feval(f,T(j),Y(j));
k4=h*feval(f,T(j)+h,Y(j)+k3);
Y(j+1)=Y(j)+(k1+2*k2+2*k3+k4)/6;
end
R=[T',Y'];
end
% or another version:
function rungekutta
h = 0.5; t = 0; w = 0.5;
fprintf('Step 0: t = %12.8f, w = %12.8f\n', t, w);
for i=1:4
k1 = h*f(t,w);
k2 = h*f(t+h/2, w+k1/2);
k3 = h*f(t+h/2, w+k2/2);
k4 = h*f(t+h, w+k3);
w = w + (k1+2*k2+2*k3+k4)/6;
t = t + h;
fprintf('Step %d: t = %6.4f, w = %18.15f\n ', i, t, w);
end
end
%%%%%%%%%%%%%%%%%%
function v = f(t,y)
v = y^2-t^2+1;
end

Accepted Answer

Jan
Jan on 4 Jan 2022
Edited: Jan on 4 Jan 2022
Store the first version starting with "function R=rk4(f,a,b,ya,M)" in a file called "rk4.m" and save it to a folder, which is included in Matlab's path. Then call it with defining te inputs as explained in the help section of the code:
% Input: f is the slope function entered as a string 'f'
% a and b are the left and right end points
% ya is the initial condition y(a)
% M is the number of steps
Now you can call the function rk4 from other functions or from the command window, e.g. :
f = @(t, x) sin(x + t);
Result = rk4(f, 0, 2*pi, 0, 1000);
plot(Result(:, 1), Result(:, 2));
The second version runs without defining the input arguments, because they are created inside the function already. So simply store the code in one file and call it from the command window.
You can learn the basics reading the Getting Started chapters of the documentation. This is very useful for the start also: https://www.mathworks.com/learn/tutorials/matlab-onramp.html
  2 Comments
James Tursa
James Tursa on 5 Jan 2022
Also note that the second version does not save any intermediate results, so there will be nothing to plot.

Sign in to comment.

More Answers (1)

James Tursa
James Tursa on 5 Jan 2022
The first version has an error. This line:
k3=h*feval(f,T(j),Y(j));
should be this instead:
k3=h*feval(f,T(j)+h/2,Y(j)+k2/2);

Categories

Find more on Loops and Conditional Statements 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!