Solving for two variables using 4th order Runga Kutta Method

Réponses (1)

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

Catégories

En savoir plus sur Numerical Integration and Differential Equations dans Centre d'aide et File Exchange

Produits

Version

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by