Challenge

Week 4.1 - Solving second order ODEs

CODE :

close all
clear all
clc



%%Inputs

%Gravitational Acceleration
g = 9.81

%Length of Pendulum
L = 1

%Mass
m = 1

%Damping cofficient
b = .05

%Time points
t_span = linspace(0,20,1000);

%Initial condition
theta_0 = [0;3];

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



%%Animation creation

ct = 1

for i = results(:,1).'
  i
a = cosd(i);
b = sind(i);


x0 = 0;
y0 = 0;

x1 = L*b;
y1 = -L*a;

%%Plotting Animation

plot([x0 x1],[y0 y1],'-O', 'LineWidth',2,'Color','r')
title('Pendulum Motion','FontSize',20)
ylabel('Y Axis','FontSize',15)
xlabel('X Axis','FontSize',15)

axis([-0.05 0.05 -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)
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/1)*sin(theta1);
  dtheta_dt = [dtheta1_dt;dtheta2_dt];

VIDEO LINK :

https://youtu.be/1O5QAPDvFL0

EXPLANATION :

At 1st I have given the input values of the variables and after that I to solve the values of time vs theta I have put the values into the ode equation. I have prepared another sheeet to define the function 'ode_func' which is being used for the ode45 solver equation. Lastly for the animation I have plotted the graphs of the position of pendulum into a for loot to get all the graphs for each values of t and theta and stored those frames in M variable. Then created movie using movie command.

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.