Solving for two variables using 4th order Runga Kutta Method

3 views (last 30 days)
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

Answers (1)

Torsten
Torsten on 23 Apr 2022
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

Categories

Find more on Numerical Integration and Differential Equations in Help Center and File Exchange

Products


Release

R2022a

Community Treasure Hunt

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

Start Hunting!