Week 3 - Solving second order ODEs
AIM:
To animate the motion of the pendulum bob by solving second order ode.
OBJECTIVE:
Animation of the pendulum.
GOVERNING EQUATION:

Let’s convert the above second-order differential equation into a first-order differential equation.

FUCTION CODE:
- function [dtheta_dt] = ode_fun(t,theta,b,g,l,m)
- theta1 = theta(1)
- theta2 = theta(2)
- dtheta1_dt = theta2
- dtheta2_dt = -(b/m)*theta2-(g/l)*sin(theta1)
- dtheta_dt = [dtheta1_dt;dtheta2_dt]
- end
The above governing equation is converted into a function
MAIN CODE:
- clear all
- close all
- clc
- %initial and boundary conditions
- b = 0.1; %damping coefficient kg/s
- g = 9.81; %acceleration due to gravity m/s
- l = 1; %length of the cord in m
- m = 0.1; %mass of the bob in kg
- theta_0 = [0;5];
- t_span = linspace(0,10,100);
- % solver
- [t,results] = ode45(@(t,theta)ode_fun(t,theta,b,g,l,m),t_span,theta_0);
- %ploting
- figure(1)
- plot(t,results(:,1))
- hold on
- plot(t,results(:,2))
- hold off
- ylabel('angular displacement')
- xlabel('time')
- %animating using the data
- ct = 1;
- for i = 1:length(results(:,1))
- theta = results(i,1);
- x0 = 0;
- y0 = 0;
- x1 = 1*sin(theta);
- y1 = -1*cos(theta);
- %plotting the bob
- figure(2)
- plot([-1,1],[0,0],"b-","linewidth",5)
- hold on
- plot([x0,x1],[y0,y1],"b-","linewidth",2)
- axis([-2 2 -2 2])
- plot(x1,y1,"o","MarkerSize",20,"MarkerFaceColor","r")
- hold off
- grid on
- axis([-2 2 -2 2])
- pause(0.01)
- M(ct) = getframe(gcf);
- ct = ct+1;
- end
- %making plots into video
- Video = VideoWriter("pedulum_animation");
- open(Video)
- writeVideo(Video,M)
- close(Video)
EXPLAINING THE CODE:
- Load the initial conditions.
- Ode45 is a solver that uses range kutta method to solve first order differential equation. The initial conditions and boundary conditions are given to the solver. The function that is crated from the first order differential equation is also mentioned.
- We plot the results with respective to t.
- Now to animate the pendulum we have to plot the every position the bob has been to do that we use for loop. The values of the results are used as inputs for the loop and the position of the bob is determined and plotted. We save the plots in a file using getframe function.
- Videowriter function is used to video data from an array.
- writeVideo is used to write video into a file.
ERRORS:
There are no major errors occurred.
RESULTS:
The animation is complete and the link is here
the plot figure 1
