Using RK4 to solve an equation of one variable only

10 Ansichten (letzte 30 Tage)
Flint
Flint am 7 Jul. 2020
Bearbeitet: Flint am 8 Jul. 2020
I need to solve the equation presented on the code with those initial condition, integration step and interval.
I am with this code at the moment and I need to create a loop.
On the commented section there's a code I found for two variables but I don't know to make it just for one. Can someone please explain?
I just started with MATLAB and Runge-Kutta so any help would be greatly appreciated.
clear; clc
h=0.1;
tinitial=1;
tfinal=5;
y(0)=1;
f=@(y) (1-2*y)*y^2
%rk4 loop - found this code for two variables and tested
%for i=1:ceil(tfinal/h)
%update y
% k1=f(y(i));
% k2=f(t(i)+0.5*h,y(i)+0.5*k1*h);
% k3=f(t(i)+0.5*h,y(i)+0.5*k2*h);
% k4=f(t(i)+ h,y(i)+ k3*h);
% y(i+1)=y(i)+h/6*(k1 + 2*k2 + 2*k3 + k4);
%end

Akzeptierte Antwort

Alan Stevens
Alan Stevens am 7 Jul. 2020
Bearbeitet: Alan Stevens am 7 Jul. 2020
The code you found is, in fact, for just one dependent variable (y). It is also updating the independent variable (t). Try the following:
h=0.1;
tinitial=1;
tfinal=5;
y(1)=1;
f=@(t,y) (1-2*y)*y^2;
t(1) = tinitial;
%rk4 loop
for i=1:ceil(tfinal/h)
%update y
k1=f(t(i),y(i));
k2=f(t(i)+0.5*h,y(i)+0.5*k1*h);
k3=f(t(i)+0.5*h,y(i)+0.5*k2*h);
k4=f(t(i)+ h,y(i)+ k3*h);
y(i+1)=y(i)+h/6*(k1 + 2*k2 + 2*k3 + k4);
t(i+1) = t(i) + h;
end
plot(t,y),grid
xlabel('time'), ylabel('y')
  5 Kommentare
Walter Roberson
Walter Roberson am 8 Jul. 2020
for i=1:ceil((tfinal-tinitial)/h)
Flint
Flint am 8 Jul. 2020
Thank you so much sir.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Produkte


Version

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by