Speed Programming in Matlab/Octave for non computer science engineers
Programe :-
clear all
close all
clc
% input variable
% g = gravity m/s^2;
% l = length of the pendulum in m;
% m = mass of the ball kg;
% b=damping coefficient;
g=9.81;
l=1;
m=1;
b=0.05;
%initial condition
theta_0=[0;3];
%time points
t_span=linspace(0,20,200);
%solve ode
[t,results]=ode45(@(t,theta)ode_fun(t,theta,b,g,l,m),t_span,theta_0);
figure(1)
plot(t,results(:,1))
hold on
grid on
plot(t,results(:,2))
xlabel('time')
ylabel('plot')
%plot for animating motion of simple pendulum
ct=1
for i=1:length(results(:,1))
x0=0
y0=0
x1=1*sin(results(i,1));
y1=-1*cos(results(i,1));
figure(2)
plot([-0.5,0.5],[0,0],'linewidth',3,'color','r');
line([x0,x1],[y0,y1],'linewidth',2,'color','b');
hold on
plot(x1,y1,'o','markers',20,'markerfacecolor','g');
grid on
axis([-1.5 1.5 -1.5 0.5]);
pause(0.01)
hold off
M(ct)=getframe(gcf);
ct=ct+1;
end
%creating the movie of motion of simple pendulum
movie(M)
videofile=VideoWriter('order_diff_eq.avi','uncompressed AVI');
open(videofile)
writeVideo(videofile,M)
close(videofile)
FUNCTION PROGRAME:-
function [dtheta_dt]=ode_fun(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:-
To create your Second order differential equation by using input variable like damping coeffficient,mass, gravity,length.
condition:-
theta1=theta(1)
theta2=theta(2)
dtheta1_dt=theta2;
dtheta2_dt=(-b/m)*theta2-(g/l)*sin(theta1);
dtheta_dt=[dtheta1_dt;dtheta2_dt];
After that give the initial condition for Displacement and Velocity theta_0=[0;3] .
For time calculation we have to define t_span=linspace(0,20,200).
To solve the second order equation [t,results]=ode45(@(t,theta)ode_fun(t,theta,b,g,l,m),t_span,theta_0);
Then you have to plot the result.
To run the call function we have to create the Function command =>[dtheta_dt]=ode_fun(t,theta,b,g,l,m).
To create the animating motion of simple pendulum first of all we have to plot the figure 2 by using the for loop command .
In for loop command we have to describe like this because the x-axis & y-axis must be plotted over
plot([-0.5,0.5],[0,0],'linewidth',3,'color','r');
line([x0,x1],[y0,y1],'linewidth',2,'color','b');
hold on
The marker command has been used for to create the sphere plot(x1,y1,'o','markers',20,'markerfacecolor','g');
grid on
axis([-1.5 1.5 -1.5 0.5]);
pause(0.01)
Then you have use counter command to figure one by one
After that you have to create the Moviefile then simple pendulum started to movie half 180 degree
movie(M)
videofile=VideoWriter('order_diff_eq.avi','uncompressed AVI');
open(videofile)
writeVideo(videofile,M)
close(videofile)
ERRORS WHILE RUNING THE PROGRAMME :-
NO ERROR
RESULTS:-
Displacement and velocity figure1 :
0 => Displacement in zero
3 => Initial velocity in3m/s
Simple pendulum Figure 2 :-