Solve 2nd order ODE using Euler Method
34 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Matt
el 27 de Sept. de 2022
Comentada: Matt
el 4 de Oct. de 2022
VERY new to Matlab...
Trying to implement code to use Euler method for solving second order ODE.
Equation:
x'' + 2*z*w*x' + w*x = 2*sin(2*pi*2*t)
z and w are constants. "t" is time.
Any help would be great.
Thanks!
5 comentarios
James Tursa
el 4 de Oct. de 2022
@Matt - FYI, when you get errors, it is best to post the entire error message along with your code. Regardless, see my answer below ...
Respuesta aceptada
James Tursa
el 4 de Oct. de 2022
Editada: James Tursa
el 4 de Oct. de 2022
You start your loop with i=1, but that means your x_d(i-1) will be x_d(0), an invalid index, hence the error. You need to set initial values for x_d(1) and x(1), and then have your starting loop index be 2. E.g.,
x(1) = initial x value
x_d(1) = initial xdot value
for i=2:n1 % start loop index at 2
x_dd(i-1) = use (i-1) indexes on everything on rhs
x_d(i) = use (i-1) indexes on everything on rhs
x(i) = use (i-1) indexes on everything on rhs
Más respuestas (1)
Davide Masiello
el 27 de Sept. de 2022
Editada: Davide Masiello
el 27 de Sept. de 2022
Hi Matt - a second order ODE can be decomposed into two first order ODEs.
The secret is to set 2 variables y as
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1137885/image.png)
The you have
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1137895/image.png)
An example code is
clear,clc
tspan = [0,1]; % integrates between times 0 and 1
x0 = [1 0]; % initial conditions for x and dx/dt
[t,X] = ode15s(@odeFun,tspan,x0); % passes functions to ODE solver
x = X(:,1);
dxdt = X(:,2);
plot(t,x)
function dydt = odeFun(t,y)
z = 1;
w = 1;
dydt(1,1) = y(2);
dydt(2,1) = 2*z*w*y(2)-w*y(1)+2*sin(2*pi*2*t);
end
1 comentario
Davide Masiello
el 27 de Sept. de 2022
For more info, I suggest reading the documentation at the following link.
Ver también
Categorías
Más información sobre Ordinary Differential Equations en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!