Challenge

Week 3 - Solving second order ODEs

OBJECTIVE
The main objective of this challenge is to write a program that can solve the second order ODE of a simple pendulum and make the animation for the pendulum in terms of angular displacement.

CODE

%program for simple pendulum
clear all
close all
clc

%parameters
b =0.05;
g = 9.81;
l = 1;
m = 0.1;

theta_0 = [0; 3];
t_span = linspace(0,20,500);
%ode45 function
[t,results] = ode45(@(t,theta) ode_func(t,theta,b,g,l,m),t_span,theta_0);

%plotting of angular velocity and displacement
figure(1)
plot (t,results(:,1))
hold on
plot(t,results(:,2))
grid on
title ('motion of pendulum')
xlabel('time')
ylabel('angular velocity(rad/s)/displacement(rad)')
legend('displacement','angular velocity')

angle = results(:,1);
ct = 1;

for i = 1:length(angle)
omega =angle(i);
figure(2)
title('motion of pendulum')

%fixed coordinates of one end of simple pendulum
x0 = 0;
y0 = 0;

%moving coordinates of the bob
x1 = l*cos((3*pi/2)+omega);
y1 = l*sin((3*pi/2)+omega);

%plotting of the bob motion
plot([x0 x1],[y0 y1],'linewidth',3,'Color','g');
hold on;
plot(x1,y1,'o','markers',15,'MarkerFaceColor','k');
hold on;
plot([-3 3],[0 0],'linewidth',2,'Color','b');
hold off
axis([-3 3 -2 2])
grid on
pause(0.1)
M(ct) = getframe(gcf);
ct = ct+1;
end
% program for animation
movie(M)
videofile =VideoWriter('simple_pendulum.avi','Uncompressed AVI');
open(videofile)
writeVideo(videofile,M)
close(videofile)

function [dtheta_dt] = ode_func(t,theta,b,g,l,m)

theta1 =theta(1);
theta2 = theta(2);
dtheta1_dt = theta(2);
dtheta2_dt = -(b/m)*theta2 - (g/l)*sin(theta1);
dtheta_dt = [dtheta1_dt; dtheta2_dt];
end


Explanation
For the first program, the function is based on the derivation to split the 2nd order differentialequation into two 1st order differential equation ,theta1 and theta2 are defined,they are stored as a solution vector where, dtheta_dt =[dtheta1_dt;dtheta2_dt]; is acolumn matrix.

In the main program the initial condition of angular displacement and velocity must be provided to solve the ODE.

ode45 is an inbuilt solver in MATLAB used to integrate differential equations. To solve the differential equation we use an anonymous function.

[t,results] is the function handle of the anonymous function.@(theta) is the input argument of the anonymous function and ode_func(t,theta,b,g,l,m),t_span,theta_0 is the definition of the anonymous function .using the ode45 command the function is solved.

RESULTS

Animation of simple pendulum

https://drive.google.com/file/d/1SrFTNr5d0CW4HMNJLPcjhKSFx7rwHGw3/view?usp=sharing

Your portfolio, next

Ship work like this
in your own course.

Talk to a career counsellor

Free 20-minute call. We'll map the right course to where you want to work.

By submitting you agree to our Terms and Privacy Policy.