Week 3 - Solving second order ODEs
https://www.youtube.com/watch?v=0jjvml3-occ
clear all
close all
clc
%inputs for the equation
b=0.05;
l=1; %length of pendulum
g=9.81; %gravity
m=1; %mass
%initial condition of pendulum
theta_0=[0;3];
%timespan
t_span=linspace(0,20,500);
% ode function for solving the differential equation
[t,Results]=ode45(@(t,theta) pendulum_damped_ode(t,theta,b,g,l,m),t_span,theta_0);
subplot(5,4,[13,14,17,18]);
plot(t,Results(:,1),'color','b');
hold on;
plot(t,Results(:,2),'color','r');
hold off;
subplot(5,4,[15,16,19,20]);
plot(Results(:,1),Results(:,2));
xlabel('position_radians');
ylabel('angular velocity');
ct=1;
% for loop for creating pendulum swing
for i=1:length(Results(:,1))
%hinged points xo and yo
x0=0;
y0=0;
%pendulum position with repsect to time
x1=1*sin(Results(i,1));
y1=-1*cos(Results(i,1));
subplot(5,4,[1,2,3,4,5,6,7,8,9,10,11,12]);
% plot the fixed line
plot([-1 1],[0 0],'linewidth',4,'color','k');
hold on;
%plot the thread
line([x0 x1],[y0 y1],'linewidth',2,'color','b');
hold on;
%plot the pendulum
plot(x1,y1, '-o','markers',20,'markerfacecolor','r');
hold off;
grid on;
axis([-1.5 1.5 -1.5 0.5]);
pause(0.002)
M(ct)=getframe(gcf)
ct=ct+1;
end
movie(M)
videofile=VideoWriter('pendulum.avi','uncompressed avi');
open(videofile)
writeVideo(videofile,M)
close(videofile)
function code
function [dtheta_dt]= pendulum_damped_ode(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
i got 1 error in getframe,earlier i was losing the figure window before completion so it was throwing error.
when i allowed all 500 intervals there was no error