Week 4.1 - Solving second order ODEs
code
%A function program for solving ODE
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
explanation
a function is a group of statement ,matlab fuction are define in seperate files. name of the fuction and file name should be same
code
%solving 2nd order ODEs
close all
clear all
clc
b=0.05; %dambing co-efficient
g=9.81; %gravity (m/s^2)
l=1; %length of the spring in meter
m=1; %mass of the ball in kg
%initial condition
%angular dispalcement is 0 and alngular velocity is 3 rad/sec
theta_0=[0;3];
%time span
% pendulum oscillates b/w 0-20 sec
t_span =linspace(0,20,600);
%solving ODE
[t,results]=ode45(@(t,theta)ode_func(t,theta,b,g,l,m),t_span,theta_0);
%ploting
figure(1)
hold on
plot(t,results(:,1))
plot(t,results(:,2))
title('Damped Harmonic Motion of a Pendulum')
legend('angular displacement','angulur velocity')
xlabel('time in seconds')
ylabel( 'plot')
%for loop
%before stating the for loop counter value will define
ct=1;
for i=1:length(results(:,1))
x_start = 0;
y_start = 0;
x_end = 1*sin(results(i,1));
y_end=1*cos(results(i,1));
%ploting the animation
figure(2)
plot([-1 1],[0 0],'linewidth',5)
hold on
plot([x_start x_end], [y_start y_end],'linewidth',5)
plot(x_end ,y_end,'o','markersize',30,'markerfacecolor','k')
title('Animation of oscilating the pendulum')
axis([-2 1.5 -2 2])
pause(0.03)
hold off
M(ct)=getframe(gcf);
ct=ct+1
end
%animation of the pendulum
movie(M)
videofile=VideoWriter('ode main.avi','uncompressed avi');
open(videofile)
writeVideo(videofile,M)
close(videofile)
explation
first define the veriables
define the initial conditions (angulur displacement and angulur velocity)
next step to slove ode,ode45 is a in bulid fuction , [t,results] it means result calutate with the time
after calcuted the result plot will be creat