Using RK4 to solve an equation of one variable only

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

 Accepted Answer

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

You were right about the loop but i don't understand what's t(1) doing there because you don't call it on the loop. Could you please explain? Also, the plot interval goes from [1,6] how do i change it do [1,5]?
y(1)=1 initializes y to exist and contain 1.
Inside the loop, on the first iteration, when i = 1, then y(i) is y(1) which will refer to the value you initialized to, y(1)=1
Thank you so much for the reply, I understand now. But still, how do I make the interval from [1,5] instead of [1,6]?
Thank you so much sir.

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Products

Release

R2020a

Asked:

on 7 Jul 2020

Edited:

on 8 Jul 2020

Community Treasure Hunt

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

Start Hunting!