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 ?
You may want to try this:
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:
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!