Clear Filters
Clear Filters

Problem with RK4

1 view (last 30 days)
B.E.
B.E. on 21 Dec 2019
Commented: B.E. on 22 Dec 2019
I have a problem with this code when I choose Nbite equal to 1
function y=RK4(Myfun,s1,s2,Nbite,y0)
h=(s2-s1)/(Nbite-1);
tt=s1:h:s2;
y=zeros(1,Nbite);
y(1)=y0;
for i=1:Nbite-1
k1 = h*Myfun(tt(i), y(i));
k2 = h*Myfun(tt(i) + h/2, y(i) + k1/2 );
k3 = h*Myfun(tt(i) + h/2, y(i) + k2/2 );
k4 = h*Myfun(tt(i+1), y(i) + k3);
y(i+1) = y(i) + (k1+2*k2+2*k3+k4)/6;
end
G=@(t,x) x.*log(1./x)-(1+tanh(100*(x-10))).*cos(t).*sin(2*t)
z=RK4(G,0.0.1,1,1)
ans z= 1????????????????
There is a problem because the time step in the code is worth 0
  4 Comments
Walter Roberson
Walter Roberson on 21 Dec 2019
B.E. is partly right. When Nbite = 1, h does go to infinity, but s1:inf:s2 is defined and is s1 .
But you have y(1)=y0 and your y0 is 1, so you initialize y(1) to 1. Then you loop over i=1:Nbite-1 which is i=1:0 so you do not execute the loop body so you do not change y at all. The answer is just going to be the y0 that you started with.
B.E.
B.E. on 22 Dec 2019
Thank you so much

Sign in to comment.

Answers (0)

Categories

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

Tags

Community Treasure Hunt

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

Start Hunting!