Challenge

Week 3 - Solving second order ODEs

Aim-Write a program in Matlab that will simulate the pendulum motion, just like the one shown in the start of this challenge.

clear all
close all
clc

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

%initial condition
theta_0=[0;3];

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

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

%ploting
plot(t,results(:,1))
hold on
plot(t,results(:,2))
ylabel('plot')
xlabel('Time in second')

%Iteration using for loop to create animation of simple pendulam
ct=1;
theta_1= results(:,1);

for i=1:length(results(:,1))
    %initial co-ordinates
    x_start=0;
    y_start=0;
    theta_2=theta_1(i);

    %final co-ordinates
    x_end=1*sin(theta_2);
    y_end=-1*cos(theta_2);

    %ploting for animation
    figure(2)
    %base of pendulam
    plot([-1,1],[0,0],'linewidth',4,'color','black')
    hold on
    %strining of pendulam
    line([x_start x_end],[y_start y_end],'linewidth',6,'color','b')
    hold on
    %bob of pendulam
    plot(x_end,y_end,'marker','o','markersize',28,'markerfacecolor','r')
    axis([-2 2 -2 2])
    pause(0.03)
    hold off
    M(ct)=getframe(gcf);
    ct=ct+1;
end
%creating a folder
movie(M)
videofile=VideoWriter('simple_pendulam.avi ','Uncompressed AVI');
open(videofile);
writeVideo(videofile,M);
close(videofile);
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

https://drive.google.com/file/d/1_RvBq2RyF8F-BwrqEgFwGkwkVcE-T58c/view?usp=drivesdk

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.