4th order Runge-Kutta code that can solve for several intial conditions
Mostra commenti meno recenti
I created a code that solves differential equations using 4th order runge-kutta method. This code can only take one intial condition. I want to make the code such that it can accept many initial conditions input as a vector and solve for each of them and store all the results in a matrix. Please help.
% Initial conditions
t0=0;
x0=0;
y0=1;
dt=0.1;
tz=10;
t_range= t0:dt:tz;
x_rk=zeros(1,length(t_range));
y_rk= zeros(1,length(t_range));
x_rk(1)=x0;
y_rk(1)=y0;
for i=1:length(t_range)-1
x_rk(i+1)=rk_method_x(x_rk(i),y_rk(i),dt);
y_rk(i+1)=rk_method_y(x_rk(i),y_rk(i),dt);
end
%% PLots
figure;
plot (t_range, x_rk,'b-o','MarkerSize',5);
hold on
plot (t_range, y_rk,'y-o','MarkerSize',5);
%% Functions
function dxdt= f(x,y)
dxdt= 5*x-3*y;
end
function dydt=g(x,y)
dydt= -6*x+2*y;
end
function x1=rk_method_x(x0,y0,dt)
k11=f(x0,y0);
k12=g(x0, y0);
k21=f(x0+0.5*dt*k11,y0+0.5*dt*k12);
k22=g(x0+0.5*dt*k11,y0+0.5*dt*k12);
k31=f(x0+0.5*dt*k21,y0+0.5*dt*k22);
k32=g(x0+0.5*dt*k21,y0+0.5*dt*k22);
k41=f(x0+dt*k31, y0+dt*k32);
k42=g(x0+dt*k31,y0+dt*k32);
x1=x0+dt*((k11/6)+((k21+k31)/3)+(k41/6));
end
function y1=rk_method_y(x0,y0,dt)
k11=f(x0,y0);
k12=g(x0, y0);
k21=f(x0+0.5*dt*k11,y0+0.5*dt*k12);
k22=g(x0+0.5*dt*k11,y0+0.5*dt*k12);
k31=f(x0+0.5*dt*k21,y0+0.5*dt*k22);
k32=g(x0+0.5*dt*k21,y0+0.5*dt*k22);
k41=f(x0+dt*k31, y0+dt*k32);
k42=g(x0+dt*k31,y0+dt*k32);
y1=y0+dt*((k12/6)+((k22+k32)/3)+(k42/6));
end
Risposta accettata
Più risposte (0)
Categorie
Scopri di più su Language Fundamentals in Centro assistenza e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!