Solving for two variables using 4th order Runga Kutta Method

조회 수: 17 (최근 30일)
Caroline Kenemer
Caroline Kenemer 2022년 4월 23일
답변: Torsten 2022년 4월 23일
I need to use a 4th order Runga Kutta method to find variables u and t.
du/dr = f(r,t)
dt/dr = f(r,t,u)
u(j+1) = +
where
and
where

답변 (1개)

Torsten
Torsten 2022년 4월 23일
Define your functions for du/dr and dt/dr in the line f = @(r,y) ... and adapt the settings in the calling program according to your needs.
rstart = 0.0;
rend = 1.0;
h = (rend - rstart)/20;
R = (rstart:h:rend).';
Y0 = [1 -1];
B = 4;
f = @(r,y) [y(2) -exp(-B*r)-y(1)+5*exp(-2*r)-2*exp(-(B+2)*r)+exp(-B*r)+r];
Y = runge_kutta_RK4(f,R,Y0);
plot(R,Y)
function Y = runge_kutta_RK4(f,R,Y0)
N = numel(R);
n = numel(Y0);
Y = zeros(N,n);
Y(1,:) = Y0;
for i = 2:N
r = R(i-1);
y = Y(i-1,:);
h = R(i) - R(i-1);
k0 = f(r,y);
k1 = f(r+0.5*h,y+k0*0.5*h);
k2 = f(r+0.5*h,y+k1*0.5*h);
k3 = f(r+h,y+k2*h);
Y(i,:) = y + h/6*(k0+2*k1+2*k2+k3);
end
end

카테고리

Help CenterFile Exchange에서 Numerical Integration and Differential Equations에 대해 자세히 알아보기

제품


릴리스

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by