Runga Kutta method 4
5 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
I want to solve this equation by Runga kutta method 4.
d2xd/dt2+0.2dx/dt-2.45xd+0.2908xp=
with intial condition
t=to=0
xd=1
xp=0
from t=0 to 100
3 Commenti
Risposta accettata
Alan Stevens
il 20 Ago 2020
Firstly, you can't have spaces in the name of the m-file. Remove them.
Secondly, remember "length" not "lenght".
Thirdly, pass parameters to the functions in the same order in which you define the functions.
Fourthly, make use of Matlab's error messages!
Here is a working code, but it produces nonsense because of the third point above. Put the parameters in the right order and you might get something sensible.
%input paramters
h=1;
t=1:h:100;
xd=zeros(1,length(t)); %%%%% length not lenght
xp=zeros(1,length(t)); %%%%% length not lenght
vd=zeros(1,length(t)); %%%%% length not lenght
vp=zeros(1,length(t)); %%%%% length not lenght
xdo=1;
vdo=0;
xpo=-1;
vpo=0;
xd(1)=xdo; %%%%% These next four lines must come after the previous four,
vd(1)=vdo; %%%%% and array indices start at 1 not 0 in Matlab.
xp(1)=xpo;
vp(1)=vpo;
%RK4
f1=@(t,xd,xp,vd,vp) vd;
f2=@(t,xd,xp,vd,vp) -0.4198*vd-5.9282*xd-1.5285*xp;
f3=@(t,xd,xp,vd,vp) vp;
f4=@(t,xd,xp,vd,vp) -0.4047*vp+1.5285*xp-7.3774*xd; %%%% xd not xp ?
for i=1:(length(t)-1) %%%%% length not lenght
%%%% The following parameters are not passed to the functions f1, f2,
%%%% etc in the order in which they are defined. You need to correct
%%%% that.
K1xd=f1(t(i),xd(i),vd(i), xp(i),vp(i));
K1vd=f2(t(i),xd(i),vd(i),xp(i),vp(i));
K1xp=f1(t(i),xp(i),vp(i), xd(i),vd(i));
K1vp=f2(t(i),xp(i),vp(i),xd(i),vd(i));
K2xd=f1(t(i)+h/2,xd(i)+h*K1xd/2,vd(i)+h*K1vd/2,xp(i)+h*K1xp/2,vp(i)+h*K1vp/2);
K2vd=f2(t(i)+h/2,xd(i)+h*K1xd/2,vd(i)+h*K1vd/2,xp(i)+h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p+K1vd+2*K2vp+2*K2vd+2*K3vp+2*K3vd+K4vp+K4vd);
end
%plots
plot(t,xd)
hold on
plot(t,xp)
6 Commenti
Più risposte (0)
Vedere anche
Categorie
Scopri di più su Numerical Integration and Differential Equations in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!