I am not getting graph for RK4

8 views (last 30 days)
Parth Shah
Parth Shah on 18 Oct 2020
Commented: Alan Stevens on 18 Oct 2020
clear t %Clear old steps
clear y %Clear y values from previous runs
t1=0; % Boundary value 1
t2=10;% Boundary value 2
h=0.1
N=(t2-t1)/h; % Number of steps
y10=1;
y20=0;
y30=0;
%y0=100; % Boundary value of y(a)
%Incremental step size
t(1) = t1; % assign initial location
Y1(1) = y10;
Y2(1) = y20;
Y3(1) = y30;% assign boundary condition
for n=1:N % For loop, sets next t,y values
t(n+1) = t(n)+h;
k1 = fgas(t(n),y1(n)); %Calls the function f(t,y) = dy/dt
k2 = fgas(t(n)+(h/2),y1(n)+(h/2)*k1);
k3 = fgas(t(n)+(h/2),y1(n)+(h/2)*k2);
k4 = fgas(t(n)+(h/2),y1(n)+(h/2)*k3);
y1(n+1)=y1(n)+h*((k1/6)+(k2/3)+(k3/3)+(k4/6))
end
plot(t,Y1)
hold on
%title(['RK4 N=',num2str(N)])
  9 Comments
Parth Shah
Parth Shah on 18 Oct 2020
clear t %Clear old steps
clear y %Clear y values from previous runs
t1=0; % Boundary value 1
t2=10;% Boundary value 2
h=0.1
N=(t2-t1)/h; % Number of steps
y10=1;
y20=0;
y30=0;
%y0=100; % Boundary value of y(a)
%Incremental step size
t(1) = t1; % assign initial location
Y1(1) = y10;
Y2(1) = y20;
%Y3(1) = y30;% assign boundary condition
for n=1:N % For loop, sets next t,y values
t(n+1) = t(n)+h;
k1 = fgas(t(n),y10(n)); %Calls the function f(t,y) = dy/dt
k2 = fgas(t(n)+(h/2),y10(n)+(h/2)*k1);
k3 = fgas(t(n)+(h/2),y10(n)+(h/2)*k2);
k4 = fgas(t(n)+(h/2),y10(n)+(h/2)*k3);
y10(n+1)=y10(n)+h*((k1/6)+(k2/3)+(k3/3)+(k4/6))
n=1:N % For loop, sets next t,y values
t(n+1) = t(n)+h;
k1 = fcra(t(n),y20(n)); %Calls the function f(t,y) = dy/dt
k2 = fcra(t(n)+(h/2),y20(n)+(h/2)*k10);
k3 = fcra(t(n)+(h/2),y20(n)+(h/2)*k20);
k4 = fcra(t(n)+(h/2),y20(n)+(h/2)*k30);
y20(n+1)=y20(n)+h*((k10/6)+(k20/3)+(k30/3)+(k40/6))
end
plot(t,y10)
hold on
plot(t,Y2)
hold on
i am adding another function
and getting error in the n=1:N % For loop, sets next t,y values
t(n+1) = t(n)+h; line
before fcra

Sign in to comment.

Answers (2)

Alan Stevens
Alan Stevens on 18 Oct 2020
Looks like you are confusing Y with y.
  7 Comments
Parth Shah
Parth Shah on 18 Oct 2020
function fcra=fcra(t1,y10,y20)
fcra=((-1*y10*y10)-(0.5*y20));
Parth Shah
Parth Shah on 18 Oct 2020
Index exceeds the number of array elements (2).
Error in RungeKutta2 (line 26)
t(n+1) = t(n)+h;

Sign in to comment.


Parth Shah
Parth Shah on 18 Oct 2020
function fcra=fcra(t1,y10,y20)
fcra=((-1*y10*y10)-(0.5*y20));
  10 Comments
Parth Shah
Parth Shah on 18 Oct 2020
I WNAT THIS GRAPH BUT I WANTED TO DO BY RK4 METHOD
Alan Stevens
Alan Stevens on 18 Oct 2020
That's exactly what your code does then!

Sign in to comment.

Categories

Find more on Programming 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!