Challenge

Week 4.1 - Solving second order ODEs

Function code for ode

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
%motion of a simple pendulum with damping


clear all 
close all
clc


%input variables
b = 0.05;
g = 9.81;
l = 1;
m = 0.1;


%initial condition
theta_0 = [0;3];


%time inputs
t_span = linspace(0,10,500);


%to solve ode
[t,y] = ode45(@(t,theta) ode_fun(t,theta,b,g,l,m),t_span,theta_0);

%extracting the element from y array
theta = y(:,1);

%base point of pendulum
     x0 = 0;
     y0 = 0;
     plot(x0,y0,'marker','o')
     axis([-1 1 -2 0])

ct=1;    %initializing ct value

for i = 1:length(y)           %starrting of for loop
   
    x1 = l*sin(theta(i));     %point is that where bob of pendulum is attached
    y1 = -l*cos(theta(i));    %point is that where bob of pendulum is attached
  
    figure(1)
    plot([x0,x1],[y0,y1],'linewidth',2)   %plotting the figure 
    hold on
  
    plot(x1,y1,'marker','o',MarkerSize=20,MarkerFaceColor='r')  %plotting the figure
    hold off
    
    axis([-1 1 -2 0])        %range between x axis and y axis
    title('simple harmonic motion of pendulum')
    xlabel('xaxis')
    ylabel('yaxis')
   
    M(ct)=getframe(gcf);      
    ct = ct+1
    

end

%animation creation

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



​
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.