Challenge

Week 3 - Solving second order ODEs

Aim- Create a program that solves the ODE equation and gives animation of pendulum.

Procedure:

In this with the help of ODE equation we will solve the problem.

here

g = gravity in m/s2,

L = length of the pendulum in m,

m = mass of the ball in kg,

b=damping coefficient

L=1 metre,

m=1 kg,

b=0.05.

g=9.81 m/s2.

by solving the above equation and converting it into function as below code.

function[dtheta_dt] = ode_func(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

Then creating the code for solving

close all
clear all
clc


L = 1;
m = 1;
b = 0.05;
g = 9.81;

% initial condition
theta_0 = [0;3];

% time points
t_span = linspace(0,20,100);

% solve ode
[t,results] = ode45(@(t,theta) ode_func(t, theta, b,g,L,m),t_span, theta_0);

plot(t,results(:,1))
hold on
plot(t,results(:,2))
ylabel('plot')
xlabel('time')

% Animation 
%using counter variable
ct=1;
% using for loop
for i=1: length(results(:,1))
    x0 = 0;
    y0 = 0;
    x1 = L*sin(results(i,1));
    y1 = -L*cos(results(i,1));
    figure(2)
    plot([-1 1],[0 0], 'linewidth',5,'color','r');
    axis([-2 2 -2 2]);
    line([x0 x1],[y0 y1],'linewidth',3,'color','b');
    hold on;
    plot(x1,y1,'o','markersize',25,'markerfacecolor','g','markeredgecolor','g');
    hold off;
    M(ct) = getframe(gcf);
    %incrementing counter variable
    ct=ct+1;
  % end of for loop  
end


movie(M)
videofile = VideoWriter('pendulam.avi','Uncompressed AVI');
%opening the file
open(videofile);
%writing the file
writeVideo(videofile,M)
%closing the file
close(videofile)

we will get the fig as shown below

Animation link: https://youtu.be/wGlq9mfeAas

Explanation of code:

ode45: to solve the first order ODE

plot: used to generate graph

xlabel: to give label on x

ylabel: to give label on y

for: it creates for loop

end: it permits end of the command

hold on: to plot the graph in single graph

movie: to generate movie

close: command to close the file.

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.

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.