Challenge

Week 4.1 - Solving second order ODEs

Code :-

clear all
close all
clc

l = 1;     % Length of pendulum in m
m = 1;     % Mass of pendulum in kg  
b = 0.05;  % Damping coefficient.
g = 9.81;  % Gravity in m/s2

%Initial Condition  of angular displacement
theta_0 = [0;3];
%Time Input 
t_span = linspace(0,10,500);
%Function Call
[t,y] = ode45(@(t,theta) ode_func(t,theta,b,g,l,m),t_span,theta_0)

%Extracting element of from y array 
theta = y(:,1);

figure(1)
plot(t,y(:,1))
hold on
plot(t,y(:,2))
hold off
xlabel('Time in second')
ylabel('Angular displacement/angular velocity')

%Initial value of counter variable
ct = 1;
%Using for loop for the simulation of pendulum
for i = 1:length(t);
    x0 = 0;
    y0 = 0;
    x1 = l*sin(y(i,1));
    y1 = -l*cos(y(i,1));
    %Reference line 
    figure(2)
    plot([-0.5,0.5],[0,0],'Linewidth',3,'color','b');
    hold on 
    %Pendulum Ball or bob 
%     plot(x1,y1,'Marker','o','MarkerEdgeColor','Color','g','MarkerSize',10,'Linewidth',8)
    plot(x1,y1,'Marker','o','Color','g','MarkerSize',10,'Linewidth',8)
    %Rope 
    plot([0 x1],[0,y1],'Linewidth',1.5)
    %Joint between Rope and Reference line
    plot(0,0,'-o','MarkerFacecolor','m','MarkerSize',5)
    xlabel('X axis')
    ylabel('Y axis')
    legend('Reference Plane','Ball','Rope','Joint')
    title('Simulation of Pendulum')
    axis([-1.5 1.5 -1.5 1.5]);
    pause(0.01)
    M(ct)=getframe(gcf);
    ct=ct+1;   
    hold off
end 

movie(M);
videofile  = VideoWriter('Simulation_of_Pendulum.avi','Uncompressed AVI');
open(videofile);
writeVideo(videofile,M);
close(videofile);

Function 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

Output :-

Problems facing while writing the code :-

The error occured in the function as well as in code. I first tried to find the error by checking the command window but only few of them were resolved but rest of them were resolved one by one.

Output Fig1 :-

Output Fig 2 :-

Video Link For Simulation of Pendulum:-

https://drive.google.com/file/d/1xeXEAzwrKbRKDDl4tI-9C7OIi9xeQaaA/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.