Implementation of 4-step Runge-Kutta

조회 수: 6 (최근 30일)
Payson
Payson 2023년 5월 7일
답변: Steven Lord 2023년 5월 7일
I am trying to use a runge-kutta function that I wrote previously on a new example.
function [y, t] = rungekutta(f, a, b, y0, h)
t = a:h:b;
y = zeros(size(t));
y(1) = y0;
for i = 1:length(t)-1
k1 = f(t(i), y(i));
k2 = f(t(i) + h/2, y(i) + (h/2)*k1);
k3 = f(t(i) + h/2, y(i) + (h/2)*k2);
k4 = f(t(i) + h, y(i) + h*k3);
y(i+1) = y(i) + h/6*(k1 + 2*k2 + 2*k3 + k4);
end
end
The function takes the function we want to evaluate, the bounds(a, b), the starting point, and the mesh size,
f = @(y,t) -t*y + 4*t/y;
a = 0;
b = 2.5;
h = .1;
y0 = 1;
[answer_rk, t_rk] = rungekutta(f, a, b, y0, h)
The result is a matrix filled with NaN values, this is because the first iteration evaluates k1 as zero. I can't tell if my error is a coding error or a misunderstanding of the Runge-Kutta implementation, could someone help?

채택된 답변

Torsten
Torsten 2023년 5월 7일
이동: Torsten 2023년 5월 7일
Change the order of the input arguments for f:
f = @(t,y) ...
instead of
f = @(y,t) ...

추가 답변 (1개)

Steven Lord
Steven Lord 2023년 5월 7일
You define f as:
f = @(y,t) -t*y + 4*t/y;
You call f as:
k1 = f(t(i), y(i));
Note the order of inputs in your definition and your call. Do you want f to be a function of y then t (as per the definition) or a function of t then y (as per the call)?

카테고리

Help CenterFile Exchange에서 MATLAB Coder에 대해 자세히 알아보기

제품


릴리스

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by