# help in runge kutta 4 2nd order with establishing the functions

2 views (last 30 days)
LG on 16 Jun 2022
Answered: Paul on 16 Jun 2022
% Ecuaciones Diferenciales Ordinarias dy/dx=f(x,y) a resolver --------------
f1 =@(x,y1,y2)
f2 =@(x,y1,y2)
% Condiciones iniciales -----------------------------------------------
%y1(0)=1;
%y2(0)=0;
x=0
xn=5
y1=1
y2=0
h=0.2
% Método de RK4Orden ---------------------------------------------------
while x(end)<=xn
k11= f1(x(end),y1(end),y2(end));
k12= f2(x(end),y1(end),y2(end));
k21= f1(x(end)+.5*h,y1(end)+.5*k11*h,y2(end)+.5*k12*h);
k22= f2(x(end)+.5*h,y1(end)+.5*h*k11,y2(end)+.5*h*k12);
k31= f1(x(end)+.5*h,y1(end)+.5*k21*h,y2(end)+.5*k22*h);
k32= f2(x(end)+.5*h,y2(end)+.5*k22*h,y2(end)+.5*k22*h);
k41= f1(x(end)+h,y1(end)+k31*h,y2(end)+k32*h);
k42= f2(x(end)+h,y2(end)+k32*h,y2(end)+k32*h);
x(end+1)=x(end)+h;
y1(end+1)=y1(end)+1/6*(k11+2*k21+2*k31+k41)*h;
y2(end+1)=y2(end)+1/6*(k12+2*k22+2*k32+k42)*h;
end
% Graficación de la solución ------------------------------------------
plot(x,y1)
hold on
plot(x,y2)
xlabel('tiempo')
title('Carga respecto al tiempo')
##### 2 CommentsShowHide 1 older comment
LG on 16 Jun 2022
where
L=.5
R=6
C=.2
x=time and y1 and y2 are q and i

Paul on 16 Jun 2022
Ok. Let y1 = q and let y2 = qdot (or y2 = q and y1 = qdot if preferred)
Then the first equation we need is
y1dot = qdot = y2. This equation should be implemented as f1
f1 @(x,y1,y2) (y2).
What is the equation for y2dot? That is, can you express y2dot as:
y2dot = f2(x,y1,y2)?
Also, the solution needs to account for E(t) as well.
As an aside, why does the code use x as the independent variable fo solving a differential equation in time? Of course, any variable name is fine, but something like 't' or 'time' would be more clear.

### Community Treasure Hunt

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

Start Hunting!

Translated by