Using RK4 to solve an equation of one variable only
4 views (last 30 days)
Show older comments
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
0 Comments
Accepted Answer
Alan Stevens
on 7 Jul 2020
Edited: Alan Stevens
on 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 Comments
More Answers (0)
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!