Solving second order ODEs using Matlab
Aim : To Solve a Second Order Differential Equation And Animate Using Matlab.
The second order Differential Equation
d^2(theta)/dt^2 + b/m * d(theta)/dt + g/L *sin(theta) .
In the above equation,
g = gravity in m/s2,
L = length of the pendulum in m,
m = mass of the ball in kg,
b=damping coefficient.
Inputs:
L=1 metre,
m=1 kg,
b=0.05.
g=9.81 m/s2.
Explanation:
1. A Higher order Differnetial Equation is suppressed into a number of first Order Differential Equations .
2.Here the Differential Equation is of Second Order so It is Suppressed into two First Order Differential Equations to solve a second order differential equation using Matlab.
3. Here the second Order Differential Equations tells about the rate of change of pendulum in a given time ,
so the Input Variables time , Displacement i.e theta are given :
theta_0 = [0;5];
t_span = linspace(0,10,100);
4.To solve above Differential Equation is used which is
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
Programm to solve the second order Differential Equation using Matlab is as follows:
clear all
close all
clc
%state variables
b = 0.05;
g = 9.81;
l = 1;
m =0.1;
%intial condition
theta_0 = [0;5];
% time points
t_span = linspace(0,10,100);
%solve ode
[t, results] = ode45(@(t,theta) ode_func(t,theta,b,g,l,m),t_span,theta_0);
plot(t,results(:,1))
hold on
plot(t,results(:,2))
ylabel('plot')
xlabel('time')
% Illstating Animation of pendulum.
ct = 1;
for i = 1:length(results(:,1))
% Generating the Data.
x0 = 0;
y0 = 0;
x1 = 1*sin(results(i,1));
y1 = -1*cos(results(i,1));
% plot the entire pendulum trajectory.
figure(2)
plot([-1,1],[0,0],'linewidth',2,'color','g');
hold on
line([x0 x1],[y0 y1],'linewidth',2,'color','r');
hold on
plot(x1,y1,'o','markersize',15,'markerfacecolor','b');
axis([-1.5 1.5 -1.5 0.5]);
pause(0.10);
hold off
M(ct)=getframe(gcf);
ct = ct+1;
end
% Creating a Movie.
movie(M)
videofile = VideoWriter('fwk.avi','Uncompressed AVI');
open(videofile)
writeVideo(videofile,M)
close(videofile)
output:

Animation Youtube Link: