Challenge

Week 4.1 - Solving second order ODEs

Main Code:-

% Write a program in Matlab\Octave that will simulate the pendulum motion
clear 
close 
clc

% inputs
b=0.05;  
g=9.81;  
l=1;     
m=1;     

% initial conditions
theta_0=[0;3];

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

% Solve ODE 
[t,results]=ode45(@(t,theta) ode_funct(t,theta,b,g,l,m),t_span,theta_0);

% Plotting Angular displacement and Angular velocity.
hold on
plot(t,results(:,1),'Color','r') % plot for Displacement Curve
plot(t,results(:,2),'Color','b') % plot for Velocity Curve
xlabel('Time')
ylabel('Plot') 
legend('Displacement Curve','Velocity Curve')


ct=1;
for i=1:length(t)

    % Coordinates of pendulum with respect to angular displacement
    x0=0;
    y0=0;
    x1=l*sin(results(i,1));
    y1=-l*cos(results(i,1));
    
    % Plotting the pendulum movement.
    figure(2)
    plot([x0,x1],[y0,y1])
    hold on
    plot([-1.5 1.5],[0 0],'color','r','LineWidth',3)
    axis([-1.5 1.5 -1.5 0.5])
    plot(x1,y1,'o','MarkerSize',20)
    pause(0.0001)
    hold off

    % Capturing the frames
    M(ct)=getframe(gcf);
    ct=ct+1;
end
% Creating a video file
movie(M)
Videofile=VideoWriter('Pendulum_sec_order_ODE.avi','Uncompressed AVI');
open(Videofile)
writeVideo(Videofile,M)
close(Videofile)

Function Code:-
function [dthetha_dt] = ode_funct(~,theta,b,g,l,m)

theta1=theta(1);        % Storing values of displacement
theta2=theta(2);        % Storing values of velocity

% 2nd order ODE
dtheta1_dt=theta2;
dtheta2_dt=-(b/m)*theta2-(g/l)*sin(theta1);

% Storing the values  
dthetha_dt=[dtheta1_dt ; dtheta2_dt];

end

Error Faced-

No Error

Output:-

Link of Video for Pendlum Motion:-

https://youtu.be/PrPqVG_6W4U

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.