Euler's Method for Second Order ODE
Mostrar comentarios más antiguos
Hi, so I am trying to solve the ODE y''+4y^2*y'+3y=cos(t) using Euler's method with step number of 400. Here is my attempt so far:
f=inline('cos(t)-4*y^2*v+3*y','t','y','v')
t(1)=0;y(1)=-1;v(1)=0;
h=40/400
for n=1:401
v(n+1)=v(n)+h*f(t(n),y(n),v(n));
t(n+1)=t(n)+h;
end
[t(:),v(:)]
for n=1:401
s(n+1)=y(n)+h*v(n)
end
plot(t,v)
xlim([0 40])
ylim([-5 5])
where v=y' and f=v'=y''. The code works beautifully for simple ODE's, but I can not get this to work whatever I try to do! The error reads Index exceeds matrix dimensions. Could anyone help me on this, and possibly comment on the second Euler's (whether it will work or not)?
Thank you very much!
Respuestas (1)
Geoff Hayes
el 1 de Nov. de 2014
Phil - you are observing this error because you initialize y as
y(1)=-1;
only, so it is a 1x1 scalar. On the second iteration of the for loop, when n is 2, the code tries to access y(2) and fails because the index exceeds the matrix dimension. Given that you are updating v at each iteration, how should you be doing something similar for y (according to Euler's method)?
Categorías
Más información sobre Mathematics en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!