Solving for two variables using 4th order Runga Kutta Method

9 次查看(过去 30 天)
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