Week 3 - Solving second order ODEs
output video link https://drive.google.com/file/d/1p3bw67fnChXPiIixeX2a8fzp3ilgk_0s/view?usp=sharing
main program:
clear all
close all
clc
%inputs given
b = 0.05;
g = 9.81;
l = 1;
m = 1;
%intial 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);
figure(1)
hold on
plot(t,results(:,1))
plot(t,results(:,2))
xlabel('time')
ylabel('plot')
grid on
%plotting the pendulum
figure(2)
theta2 = results(:,1);
ct=1;
for i = 1:length(theta2)
THETA2 = theta2(i);
%coordinates
x0 = 0;
y0 = 0;
x1 = l*sind(THETA2);
y1 = -l*cosd(THETA2);
plot([-0.5 0.5],[0 0],'linewidth',5,'Color','g');
hold on
plot([x0 x1],[y0 y1],'linewidth',2,'Color','b');
hold on
plot(x1,y1,'o','markers',20,'markerfaceColor','r');
hold off
axis([-1.5 1.5 -1.5 0.5]);
pause(0.02);
M(ct) = getframe(gcf);
ct = ct+1;
grid on
end
movie(M);
Video = VideoWriter('pendulum.avi');
open(Video);
writeVideo(Video,M);
close(Video);
function program for pendulum
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
- At first i gave the initial parameters given and set the intial condition with the angular velocity and displacement.
- Then the time given is 20 sec so span is set from 0 to 20 with 500 values in between them.
- After that the ode function is created where a template is set with the second order equation.
- That ode func is called in the main program with set of intial parameters.
- plot is made for time as x axis and in y axis we have both velocity and displacement.
- further continuing the program to animate the pendulum i have assigned the each value of displacement to theta
- Then telling that i=1:length(theta2) and assigning the coordinates.
- After finishing plotting is done for slab plot([-0.5 0.5],[0 0],'linewidth',5,'Color','g'); and for string plot([x0 x1],[y0 y1],'linewidth',2,'Color','b'); and bob plot(x1,y1,'o','markers',20,'markerfaceColor','r');
- movie is animated by creating the frame and capturing them.
errors came during the assign of ct=1 i used them before theta2 so it didn't generate the movie then i relocated the code it have solved.