Example of the Euler Method in 2D
We will use the Euler method to solve the damped pendulum equation
which we first rewrite as a system
for initial conditions , , and . Set up initial conditions and parameters
Set up time stepping
t=linspace(0,tFinal,nSteps+1);
Initialize θ & y
theta(1)=theta0; y(1)=y0;
Loop through and run the Euler method. Note that this code uses a function (defined at the bottom of this file) to evaluate the right-hand side.
[delta_x, delta_y] = pendulumODE(theta(k),y(k),gamma);
theta(k+1) = theta(k) + h * delta_x;
y(k+1) = y(k) + h * delta_y;
Plot the results
xlabel('t'); legend('\theta','y')
Plot the solution in the phase plane
xlabel('\theta');ylabel('y');
Function used to evaluate the differential equation
function [delta_x, delta_y] = pendulumODE(x,y,gamma)
delta_y = -gamma*y-sin(x);