Week 3 - Solving second order ODEs
Aim :- TO solve second order ordinary differential equation using Matlab ?
Answer :-
1.> function code for the main 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
2.> The main code.
clear all
close all
clc
%solving the Second order ODE
b = 0.05;
l = 1;
m = 1;
g = 9.81;
%Initial Condition
theta_0 = [0;5];
%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);
plot(t,results(:,1))
hold on
plot(t,results(:,2))
xlabel('Time')
ylabel('velocity')
legend('Displacement','Angular velocity')
grid on
hold off
displacement = results(:,1);
velocity = results(:,2);
%fixed coordinates
x0 = 1;
y0 = 1;
ct = 1;
for i = 1:length(displacement)
%coordinates
x1= 1-l*sin(displacement(i));
y1= 1-l*cos(displacement(i));
%plot fixed link
plot([0 2],[1 1],'LineWidth',15,'Color','b')
hold on
plot([1 x1],[1 y1],[x1 x1],[y1 y1],'-0','markersize','25','markerfacecolor','r','linewidth','4');
plot(x0,y0,'-0','markersize',3,'markerfacecolor','b')
%axis setting
axis([0 2 -0.5 2])
M(ct)= getframe(gcf);
ct = ct+1;
hold off
end
movie(M)
videofile = VideoWriter('simple pendulum.avi','Uncompressed AVI');
open(videofile)
writeVideo(videofile,M)
close(videofile)