Challenge

Week 3 - Solving second order ODEs

https://youtu.be/mDeB1oztqZY

%solving second order ODEs of a function
clear all
close all
clc
 
%input
b=0.05 % damping corfficient
g=9.81 % gravity (m/s^2) 
L=1  % length of the spring (meter)
m=1  % mass of the bob (kg) 
%intial condition
% angular displacement is 0 and angular velocity is 5
theta_0=[0;5]
%time_span
%pendulum oscillates between 0-20 second
t_span=linspace(0,20,600)
%solving ODEs
[t,results]=ode45(@(t,theta)ode_func(t,theta,b,g,L,m),t_span,theta_0);

% plotting
figure (1)
hold on
plot(t,results(:,1))
plot(t,results(:,2))
title('Damped Haromonic Motion of a Pendulum')
legend('Angular Displacement','Angular Velocity')
ylabel('plot')
xlabel('Time(seconds)')

% for loop
% before starting thr for loop, a counter valu was defined 
ct=1;
for i=1:length(results(:,1))
    x_start=0
    y_start=0
    x_end=1*sin(results(i,1))
    y_end=-1*cos(results(i,1))
    %plotting the animation
    figure(2)
    plot([-1 1],[0 0],'linewidth',5)
    hold on
    plot([x_start x_end],[y_start y_end],'linewidth',3)
    plot(x_end,y_end,'o','markersize',20,'markerfacecolor','y')
    title('Animation of transient behaviour of a pendulum')
    axis([-1.5 1.5 -1.5 1])
    pause(0.03)
    hold off
    M(ct)=getframe(gcf)
    ct=ct+1
end
% Animation of the pendulam
movie(M)
videofile=VideoWriter('Pendulum Animation.avi','uncompressed avi')
open(videofile)
writeVideo(videofile,M)
close(videofile)





%code explation
% A function program which will be called in the main programto solve 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
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.