Week 3 - Solving second order ODEs
% TO solve ODE equation
close all
clear all
clc
%Inputs
b=0.05;
g=9.81;
l=1;
m=1;
%Initial conditions
h_0=[0;3];
tspan=linspace(0,20,200);
x0=0;
y0=0;
%ODE function
[t,results]=ode45(@(t,theta) ode_func(t,theta,b,g,l,m),tspan,h_0);
counter = 1;
for i =1:length(results(:,1))
x1=l*cos(results(i,1));
y1= l*sin(results(i,1));
plot([x0 x1],[y0 y1]);
hold on
plot(x1, y1,'Marker','o');
hold off
axis([0 3 -3 3]);
xlabel('Time');
ylabel('Plot');
pause(0.3);
M(counter)=getframe(gcf);
counter=counter+1;
end
%Animation
movie(M)
videofile= VideoWriter('Simplependulum Avi','Uncompressed Avi');
open(videofile)
writeVideo(videofile,M)
close(videofile)
ODE function.
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
Code Explanation:
This program illustrates a simple pendulumn. Here we have used the second order differential equation and divided it into two single order differential equation namely theta 1 and theta2.The result of this matrix(theta1 and theta2) will be stored in theta and this will be the output of the ode_func.
ode_func is used in Ode45 which takes this input and returns two values t and results(angle and velocity).
To calculate the arm of pendulumn, one side is fixed-x0=y0=0.the other coordinates is derived using sine and cosine functionality.
A for loop is used to vary the arm as theta varies and the o/p is stored as images and the collection of images is made into a movie.
Youtube link:
Errors Faced:
Here the main problem was to create an image of the arm, refering to previous examples, realised that the coordinates has to be defined and with this we can plot the image.
another main issue was the images were overlapping and was not seen as a video, later when used the hold off command,this problem was solved.
For the marker, with the help documentation,this problem was solved.