The most straight forward approach is to replace
\(\dot{\yb}_{i}\) in
(4.2.2) by its forward difference approximation. This gives
\begin{equation*}
\frac{\yb_{i+1}- \yb_{i}}{h}= \fb(t_{i},\yb_{i})\text{.}
\end{equation*}
Rearranging this gives us a way to obtain \(\yb_{i+1}\) from \(\yb_{i}\) known as Euler’s method:
\begin{equation*}
\yb_{i+1}= \yb_{i} + h \fb(t_{i},\yb_{i})\text{.}
\end{equation*}
With this formula, we can start from \((t_{0},\yb_{0})\) and compute all the subsequent approximations \((t_{i},\yb_{i})\text{.}\) This is very easy to implement, as you can see from the following program.
To use this program we need a function, such as the vector function for the pendulum:
>> dy = @(t,y)[y(2);-.1*y(2)-sin(y(1))+sin(t)]
Save this and then type
>> [T Y] = myeuler(dy,[0 20],[1;-1.5],5);
Here
[0 20] is the time span you want to consider,
[1;-1.5] is the initial value of the vector
y and
5 is the number of steps. The output
T contains times and
Y contains values of the vector at the times. Try
Since the first coordinate of the vector is the angle, we only plot its values:
>> theta = Y(:,1);
>> plot(T,theta)
In this plot it is clear that
\(n=5\) is not adequate to represent the function. Type
then redo the above with 5 replaced by 10. Next try 20, 40, 80, and 200. As you can see the graph becomes increasingly better as
\(n\) increases. We can compare these calculations with MATLAB’s built-in function with the commands
>> [T Y]= ode45(dy,[0 20],[1;-1.5]);
>> theta = Y(:,1);
>> plot(T,theta,'r')