Runge-Kutta 3

4 vues (au cours des 30 derniers jours)
Dávid Bak
Dávid Bak le 23 Mar 2020
Commenté : Dávid Bak le 24 Mar 2020
So I'm doing a project for school, where i have to solve the x''-x'-x=sin(t) equation with Runge-Kutta.
intervalmin=0;
intervalmax=1;
numnodes=5;
f=@(t,x) [x(2); x(2)+x(1)+sin(t)];
inival=0;
h=0.1;
t=zeros(1,numnodes);
t(1)=intervalmin;
x=zeros(1,numnodes);
X=zeros(1,numnodes);
x(1)=inival;
X(1)=inival;
for i = 2:numnodes
k1 = f(t(i-1),x(i-1));
k2 = f(t(i-1)+h/2,x(i-1)+(h/2)*k1);
k3 = f(t(i-1)+h,x(i-1)-h*k1+2*h*k2);
x(i)=(x(i-1)+h/6)*(k1+4*k2+k3);
X(i)=(X(i-1)+h/6)*((f(t(i-1),X(i-1)))+4*(f(t(i-1)+h/2,X(i-1)+(h/2)*k1))+(f(t(i-1)+h,X(i-1)-h*k1+2*h*k2)));
t(i) = t(i-1)+h;
end
figure
plot(t,x,'.-b',t,X,'-.r');
The code is this so far, but it has multiple errors like:
Index exceeds the number of array elements (1).
Error in Untitled5>@(t,x)[t(2);t(2)+t(1)+sin(x)]
Error in Untitled5 (line 14) k1=f(t(i-1),x(i-1));
I'm pretty new to matlab, and just can't seem to find a way to make it work.

Réponse acceptée

darova
darova le 23 Mar 2020
Here is the mistake
SOlution
  6 commentaires
darova
darova le 24 Mar 2020
Mistake
Dávid Bak
Dávid Bak le 24 Mar 2020
Oh, now everything's alright, thank you very much, you helped a lot!

Connectez-vous pour commenter.

Plus de réponses (0)

Produits


Version

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by