Solving 2nd degree ODE with Euler method in MATLAB

7.2k Views Asked by At

I am trying to solve the equation below;

$$\ddot{x}= -x + sin(t)$$

by the initial conditions;

$$x(0) = 0 \\ \dot{x}(0)= 0$$

my MATLAB code is as follows:

clc
clear all

%define time step and tend

dt = 0.01;
tf = 1.0;

%create arrays for tvec, xvec and uvec

tvec = 0:dt:tf;
xvec = zeros(length(tvec),1);
xvec(1) = 0;
uvec = zeros(length(tvec),1);
uvec(1) = 0;

%run euler
for i = 1:length(tvec)-1
    xvec(i+1) = xvec(i) + dt*uvec(i);
    uvec(i+1) = uvec(i) + dt*(-xvec(i)+sin(i+1));
end

but this code gives me the solution at $x(1.0)$ wrong. Where am I being failed ?

2

There are 2 best solutions below

4
On BEST ANSWER

You may want to try this:

tf = 5;
Nt = 150;
dt = tf/Nt;

t = 0:dt:tf;

x0 = 0;
u0 = 0;

x = zeros(Nt+1,1);
u = x;

x(1) = x0;
u(1) = u0;

for i = 1:Nt;

    u(i+1) = u(i) + dt*(-x(i)+sin(t(i)));
    x(i+1) = x(i) + dt*u(i);

end

plot(t,x,t,u,'k');
legend('x(t)','u(t)');

You use the RHS of the equation at the time $t_i$ because you are using an explicit or forward Euler's scheme. An alternative for improving consistence would be computing $x_{i+1}$ with the information of $u$ at the time $i+1$, i.e:

x(i+1) = x(i) + dt*u(i+1);

You can check that there are some differences but don't expect big changes. You can derive a matrix-form system of equations for a backward or implicit scheme in order to solve the unknowns of: $g(x_{n+1},u_{n+1},t_{n+1}) = f(x_n,u_n)$.

Cheers!

4
On
  1. Use sin(dt*(i)) or sin(dt*(i+1)), not sin(i+1).

  2. This is a first order method, so don't expect to be very close.