Challenge

Week 3 - Solving second order ODEs


%sub_function for the ode
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



%clearing the screen,command line,workspace and closing all plates
clear all
close all
clc
%inputs
b=0.01
l=1 %length of the string in m
g=9.81 %gravity in m/s
m=1 %mass in kg

%initial conbdition
theta_0 =[0;3];

%time
t_span=linspace(0,20,500)

%[t,result]=ode45('challenge_2nd_ode','t_span','theta_0')
[t,result]=ode45(@(time,theta) ode_func(t_span,theta,b,g,l,m),t_span,theta_0)

subplot(5,4,[13,14,17,18]);
plot(t,result(:,1),'color','b')
hold on
plot(t,result(:,2),'color','r');
hold off
subplot(5,4,[15,16,19,20]);
plot(result(:,1),result(:,2))
xlabel('positions radians')
ylabel('angular velocity')

ct=1

for i=1:length(t_span)
  x0=0
  y0=0
  x1=1*sin(result(i,1))
  y1=-1*cos(result(i,1))
  subplot(5,4,[1,2,3,4,5,6,7,8,9,10,11,12])
 
  plot([x0 x1],[y0 y1],'linewidth',2,'color','b')
  hold on
  axis([-1.5 1.5 -1 0.2 ])
 
  %r=0.75 %plotting circle then maping the corner to the string 
 %cir_deg=linspace(0,2*pi,100)
%xc=r*cos(cir_deg)
%yc=r*sin(cir_deg)
%plot(x1+xc,y1+yc,'linewidth','2')
%hold off

plot(x1,y1,'-o','markers',20,'markerfacecolor','r')
%plotting the bob using marker and face color
hold off
%r=0.25; %plot a curved rctangle and color into inner 
%rectangle ('position',[(x1-(r/2)),(y1-r/2),r,r],'curvature',[1,1],'facecolor','r','linewidth','3')
%hold on
%axis equal

grid on
axis([-1.5 1.5 -1.5 0.5])
 

M(ct)=getframe(gcf);
ct=ct+1  
 
end


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

The link for the video file created throug MATLAB

https://youtu.be/7ftXRRdosBA

The first portion of the code is for creating a subfunction for the ode where the formula to solve the pendulum problem is been provided.

The second portion shows the main program for creating the annimation and video file of the pendulum from the problm.

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.