You are on page 1of 114

COMPUTATIONAL LAB

(ME-106)
INTRODUCTION
TO
MATLAB
By
K.Kiran Kumar
Assistant professor
Mechanical Engineering Department
B.S.Abdur Rahman University
Email:- kiranmek3@gmail.com
Ph.no:- 9047475841

WHAT IS MATLAB?

MATLAB (MATrix LABoratory) is basically a high level language


which has many specialized toolboxes for making things easier for us.
MATLAB is a program for doing numerical computation. It was
originally designed for solving linear algebra type problems using
matrices. Its name is derived from MATrix LABoratory.
MATLAB has since been expanded and now has built-in functions for
solving problems requiring data analysis, signal processing, optimization,
and several other types of scientific computations. It also contains
functions for 2-D and 3-D graphics and animation.
Powerful, extensible, highly integrated computation, programming,
visualization, and simulation package.
Widely used in engineering, mathematics, and science.
Why?

FEATURES
MATLAB is an interactive system for doing
numerical computations. MATLAB makes use of
highly respected algorithms and hence you can be
confident about your results.
Powerful operations can be performed using just
one or two commands. You can also build your
own set of functions. Excellent graphics facilities
are included.
o

MATLAB TOOLBOXES
Signal & Image Processing
Math and Analysis
Optimization
Signal Processing
Requirements Management Interface
Image Processing
Statistics
Communications
Neural Network
Frequency Domain Identification
Symbolic/Extended Math
Higher-Order Spectral Analysis
System Identification
Partial Differential Equations
Wavelet
PLS Toolbox
Filter Design
Mapping
Spline
Control Design
Data Acquisition and Import
Control System
Data Acquisition
Fuzzy Logic
Instrument Control
Robust Control
-Analysis and Synthesis
Excel Link
Model Predictive Control
Portable Graph Object

SIMULINK

A simulation tool for dynamic systems

Input

Output
System

Simulink library Browser:

Collection of sources, system modules, sinks

WHAT ARE WE INTERESTED IN?

MATLAB is too broad tool used in industry and Research for real
time interfacing of sensors and machine vision etc. and
programming the real time systems for active control of the
system behavior.
For our course purpose in this Laboratory we will have brief
overview of basics and learn what can be done with MATLAB at
beginner level.

WHY DO WE
NEED TO
PERFORM
ANALYSIS IN
MATLAB ???

AREAS WHERE MECHANICAL


ENGINEERS USE MATLAB

Solving kinematics, kinetics and complete


dynamic systems control of Automotive
suspension , Thermal systems etc.,

AERO PLANE SUSPENSION


M

OF LANDING GEAR

Mg

Fs

Fc

Yo

Ys

Yin

d 2 yo
M
Mg Fc Fs
2
dt

BASICS
Displacement

distance
35 Metres

Speed
65 m/s

D
Time

Velocity
V
Time

0-60 m/s
in 8.6
second

Acceleration

A
Time

UNDAMPED FREE VIBRATION


Displacement

d = D sinnt

Displacement

D
Time

Frequency

1
T

Period, Tn in [sec]
k

Frequency, fn= T in [Hz = 1/sec]


n

n= 2 fn =

k
m

CONTINUED
Natural frequency of a simple single degree of
freedom undamped system is given by the
equation
N = square root of (stiffness / mass)

Usually we do not want structures to vibrate in


resonance

COMPONENTS OF A CAR
For comfortable ride in a car requires analysis of
car frame and many other components, e.g.
exhaust systems (bellows), shock absorber, tire
etc.
Let us look into a shock absorber in more detail

We know what a typical shock absorber does


saves us from unpleasant vibration.

Let us look at a quarter bus/truck/car model


xs

ms
ks

cs
mu
kt

xu

u = road profile input


ks = suspension spring constant
kt = tire spring constant
cs = suspension damping constant
mu = unsprung mass
ms = sprung mass
xu = displacement of unsprung mass
xs = displacement of sprung mass

FOUR WHEELER SUSPENSION SYSTEM


Consider the following suspension system.
Solve for y given yin

Mg

y
ys
Suspension system

yin

15

SUSPENSION SYSTEM IN FOUR


WHEELER

CONTINUED

CONTINUED

CONTINUED

CONVENTIONAL PASSIVE SUSPENSION

zs

sprung mass
(body) Ms

suspension spring
unsprung mass
(wheel, axle) Mu
tyre stiffness Kt

suspension damper

zu

zr

MATLAB MODEL FOR


BUS SUSPENSION
Designing an automatic suspension system for a bus

MATLAB SCREEN

VARIABLES
No need for types. i.e.,
int a;
double b;
float c;
Accuracy and comfort is very high with matlab codes.
>>x=5;
>>x1=2;

ARRAY, MATRIX

LONG ARRAY, MATRIX

GENERATING VECTORS FROM FUNCTIONS

MATRIX INDEX

OPERATORS (ARITHMETIC)

MATRICES OPERATIONS

THE DOT OPERATOR


By

default and whenever possible MATLAB


will perform true matrix operations (+ - *). The
operands in every arithmetic expression are
considered to be matrices.
If, on the other hand, the user wants the scalar
version of an operation a dot must be put in
front of the operator, e.g., .*. Matrices can still
be the operands but the mathematical
calculations will be performed element-byelement.
A comparison of matrix multiplication and
scalar multiplication is shown on the next slide.

OPERATORS (ELEMENT BY ELEMENT)

DOT OPERATOR EXAMPLE


>> A = [1 5 6; 11 9 8; 2 34 78]
A =
1
5
6
11
9
8
2
34
78
>> B = [16 4 23; 8 123 86; 67 259 5]
B =
16
4
23
8
123
86
67
259
5

DOT OPERATOR EXAMPLE (CONT.)


>> C = A * B
C =
458
784
5530

% normal matrix multiply

>> CDOT = A .* B
CDOT =
16
88
134

2173
3223
24392

483
1067
3360

% element-by-element
20
1107
8806

138
688
390

THE USE OF . -OPERATION

MATLAB FUNCTIONS

COMMON MATH FUNCTIONS

BUILT-IN FUNCTIONS

FOR HANDLING ARRAYS

MATLAB BUILT-IN ARRAY FUNCTIONS

Standard Arrays
eye(2)

Other such arrays:

ans =

ones(n), ones(r, c)

1
0

0
1

zeros(n), zeros(r, c)
rand(n), rand(r,c)

eye(2,3)
ans =

1
0

0
1

0
0

RANDOM NUMBERS GENERATION

COMPLEX NUMBERS HANDLING


FUNCTIONS

MATRIXES AND VECTORS


x = [1,2,3] , vector-row,
y=[1;2;3], vector-column,
x=0:0.1:0.8 , vector x=[0,0.1,0.2,0.3....0.8],
A = [1,3,5;5,6,7;8,9,10], matrix,
A(1,2), element of matrix, 1. row, 2. column,
A(:,2), second column of matrix,
A(1,:), first row of matrix ,
C=[A;[10,20,30]] matrix with additional row,
B=A(2:3,1:2), part of matrix,
x, transpose.

42

MATRIXES AND VECTORS


size(A), matrix size,
det(A), determinant,
inv(A), inverse matrix,
eye(3), unit matrix,
zeros(3,4), matrix of zeros,
rand(3,5), matrix of random values,
sum(A), sum of elements,
A*x, matrix-vector product (if dimensions are
corresponding),
A.*B, element multiplication of two matrixes.
help sqrt, looking for known command,
help, help topics are shown,

43

INTRODUCTION TO M-FILES PROGRAMMING


Type-1
programming

Program:clc;
clear all;
p=10,000;
t=2;
r=11;
I=(p*t*r)/100;
Solution:I = 2200

Type-2
Programming
Program:clc;

clear all;
p=input('enter the value of p:');
t=input('enter the value of t:');

r=input('enter the value of r:');


I=(p*t*r)/100
Solution:-

Input:
enter the value of p:10000
enter the value of t:2
enter the value of r:11

Output:
I = 2200

GRAPHICS AND DATA DISPLAY

2-D plotting functions


>> plot(x,y)

% linear Cartesian

>> semilogx(x,y)

% logarithmic abscissa

uses base 10 (10n for axis units)

>> semilogy(x,y)

% logarithmic ordinate

uses base 10 (10n for axis units)

>> loglog(x, y)
% log scale both dimensions
uses base 10 (10n for axis units)

>> polar(theta,rho) % angular and radial

CONTINUED..

2-D

display variants

Cartesian coordinates
>>
>>
>>
>>
>>

bar(x,y)
barh(x,y)
stem(x,y)
area(x,y)
hist(y,N)

% vertical bar graph


% horizontal bar graph
% stem plot
% color fill from horizontal axis to line
% histogram with N bins (default N = 10)

Polar coordinates
>> pie(y)
>> rose(theta,N) % angle histogram, N bins (default 10)

GRAPHICS AND DATA DISPLAY


3-D

Plotting syntax

Line
>> plotfunction(vector1, vector2, vector3)
Vector lengths must be the same

Example
>> a = 1:0.1:30;
>> plot3( sin(a), cos(a), log(a) )

Pie
>> pie3(vector)
One dimensional data, but 3-D pie perspective

GRAPHICS AND DATA DISPLAY


3-D

surface plotting functions

>> contour(x,y,Z) % projection into X-Y plane


>> surf(x,y,Z)

% polygon surface rendering

>> mesh(x,y,Z)

% wire mesh connecting vertices

>> waterfall(x,y,Z)
like mesh but without column connection lines
used for column-oriented data

BASIC TASK: PLOT THE FUNCTION


SIN(X) BETWEEN 0X4

PLOT THE FUNCTION BETWEEN 0X4

PLOT THE FUNCTION e-X/3SIN(X)


BETWEEN 0X4

DISPLAY FACILITIES

CONTD..

LINE SPECIFIERS IN THE plot() COMMAND

plot(x,y,line specifiers)

Line
Style

Specifier

Solid
dotted
:
dashed
dash-dot

--.

Line
Color

red
green
blue
Cyan
magenta
yellow
black

Specifier

r
g
b
c
m
y
k

Marker Specifier
Type

plus sign
circle
asterisk
point
square
diamond

+
o
*
.
s
d

Plots
x = 1:2:50;
y = x.^2;
plot(x,y)

2500

2000

1500

1000

500

10

15

20

25

30

35

40

45

50

Plots
plot(x,y,'*-')
xlabel('Values of x')
ylabel('y')
2500
2000

1500

1000

500

10

15

20

25
30
Values of x

35

40

45

50

MULTIPLE GRAPHS
t=0:pi/100:2*pi;
y1=sin(t);
y2=sin(t+pi/2);
plot(t,y1,t,y2);
grid on

1
0.8
0.6
0.4
0.2
0
-0.2
-0.4
-0.6
-0.8
-1

MULTIPLE PLOTS
t=0:pi/100:2*pi;

y1=sin(t);
y2=sin(t+pi/2);
subplot(2,2,1)
plot(t,y1)

grid on
subplot(2,2,2)
plot(t,y2);
grid on

subplot(i,j,k)
i is the number of rows of subplots in the plot
j is the number of columns of subplots in the plot
k is the position of the plot

INTERESTING FEATURE OF GENERATING


SINE CURVE

x = 0:0.05:6;
y = sin(pi*x);
Y = (y >= 0).*y;
plot(x,y,':',x,Y,'-')

1
0.8
0.6
0.4
0.2
0
-0.2
-0.4
-0.6
-0.8
-1

CONTINUED..

x = 0:0.05:6;
y = sin(pi*x);
Y = (y >= 0).*y;
plot(x,y,.',x,Y,'-')

1
0.8
0.6
0.4
0.2
0
-0.2
-0.4
-0.6
-0.8
-1

OPERATORS (RELATIONAL, LOGICAL)

POLYNOMIALS

MATLAB FUNCTIONS FOR POLYNOMIALS

Contd..
Representing Polynomials:
x4 - 12x3 + 25x + 116
P = [1 -12 0 25 116];
roots(P)
ans =
11.7473
2.7028
-1.2251 + 1.4672i
-1.2251 - 1.4672i

r = ans;
PP = poly(r)
PP =
1.0000 -12.0000 -0.0000 25.0000 116.0000

Polynomial Multiplication
a = x3 + 2x2 + 3x + 4
b = 4x2 + 9x + 16
a = [1 2 3 4];
b = [4 9 16];
c = conv(a,b)
c=
4 17 46 75 84 64

Evaluation of a
Polynomial
a = x3 + 2x2 + 3x + 4
polyval(a, 2)
ans =

26

Symbolic Math
syms x
int('x^3')
ans =
1/4*x^4
eval(int('x^3',0,2))
ans =

Solving Nonlinear Equations


nle.m
Function of the program:-

function f = nle(x)
f(1) = x(1) - 4*x(1)*x(1) - x(1)*x(2);
f(2) = 2*x(2) - x(2)*x(2) + 3*x(1)*x(2);
Program:x0 = [1 1]';
x = fsolve('nle', x0)
Solution:x=
0.2500
0.0000

TO FIND EIGEN VALUES AND EIGEN


VECTORS OF MATRICES

CONTINUED

SOLVING LINEAR EQUATIONS

(TRY MANUALLY)

Solve manually and tell me what is the answer..?

That is find out x=


y=
z=

SOLVING SET OF SIMULTANEOUS EQUATIONS

DIFFERENTATION

SOLVING DIFFERENTIAL EQUATIONS

PERFORMING INTEGRATION

NUMERICAL INTEGRATION

Numerical integration of the integral f (x) dx is called


quadrature. MATLAB provides the following built-in functions
for numerical integration:

quad:

It integrates the specified function over specified limits, based on


adaptive Simpson's rule.
The general call syntax for both quad and quadl is as follows:

Syntax:-

integral = quad(function, a, b)
dblquad: (It calculates double integration)

MATLAB provides a function dblquad. The calling syntax for


dblquad is:

Syntax:I = dblquad(function_xy, xmin, xmax, ymin, ymax)

FLOW CONTROL

CONTROL STRUCTURES

CONTROL STRUCTURES

CONTROL STRUCTURES

IF STATEMENT
(EXAMPLE)
n = input(Enter the upper limit: );
if n < 1

disp (Your answer is meaningless!)

end
x = 1:n;
term = sqrt(x);
y = sum(term)

Jump to here if TRUE


Jump to here if FALSE

EXAMPLE PROGRAM TO EXPLAIN IF LOOP


% Program to find whether roots are imaginary or not%
clc;
clear all;

a=input('enter value of a:');


b=input('enter value of b:');

c=input('enter value of c:');


discr = b*b - 4*a*c;
if discr < 0

disp('Warning: discriminant is negative, roots are imaginary');


end
Solution:-

Input:
enter value of a:1
enter value of b:2

enter value of c:3


Output:

Warning: discriminant is negative, roots are imaginary

EXAMPLE OF IF ELSE STATEMENT


Program:A = 2;
B = 3;
if A > B
'A is bigger'
elseif A < B
'B is bigger'
elseif A == B
'A equals B'
else
error('Something odd is happening')
end
Solution:ans =
B is bigger

IF STATEMENT EXAMPLE
Here are some examples based on the familiar quadratic formula.
1. discr = b*b - 4*a*c;
if discr < 0
disp('Warning: discriminant is negative, roots are imaginary');
end

2. discr = b*b - 4*a*c;


if discr < 0

disp('Warning: discriminant is negative, roots are imaginary');


else
disp('Roots are real, but may be repeated')
end
3. discr = b*b - 4*a*c;

if discr < 0
disp('Warning: discriminant is negative, roots are imaginary');

elseif discr == 0
disp('Discriminant is zero, roots are repeated')
else
disp('Roots are real')
end

EXAMPLE OF FOR LOOP


Problem: Draw graphs of sin(n x) on the interval 1 x 1 for
n = 1,2,....,8.We could do this by giving 8 separate plot

commands but it is much easier to use a loop.

Program:x=-1:0.05:1;
for n=1:8
subplot(4,2,n);

plot(x, sin(n*pi*x));
end

EXAMPLE OF FOR & WHILE LOOP


1.) % example of for loop%
Program:for ii=1:5
x=ii*ii
End

Solution:
1 4 9 16 25
2.) %example of while loop%
Program:x=1
while x <= 10
x = 3*x
End
Solution:
x=1 x=3 x= 9 x=27

3.) %example of while loop%


x=1
while x <= 100
x = 3*x
end
Solution:X= 1 3
9
27

SWITCH STATEMENT

EXAMPLE

Program:n=input(enter the value of n: );


switch(rem(n,3))
case 0
m = 'no remainder'
case 1
m = the remainder is one'
case 2
m = the remainder is two'
otherwise
error('not possible')
end
Solution:enter the value of n: 8
m =the remainder is two

SPRING/MASS/DAMPER SYSTEM EXAMPLE

88

PROBLEM SOLVED BY USING


MATLAB AND SIMULINK

INTRODUCTION

PROBLEM

PROBLEM

FUNCTION OF THE PROGRAM


function f=programone (t,z)
m=3;
c=8;
k=100;
dzdt=[z(2); -(c/m)*z(2)-(k/m)*z(1)];

MAIN BODY OF THE PROGRAM


% For a single degree of freedom system in free vibration
clc;
clear all;
%Enter initial conditions
z0=[5;15];
%Enter time span for solution
tspan=[0 10];
%Call solver
[t,z]=ode45(programone',tspan,x0);
%Set up plot
plot(t,z(:,1));

RESULT
single degree of freedom spring mass damper system behaviour
6
displacement
5

displacement in mm

4
3
2
1
0
-1
-2
-3

10
time in seconds

15

DEMONSTRATION OF THE CONCEPT


WITH SIMPLE EXAMPLE

DEMONSTRATION OF THE CONCEPT


WITH SIMPLE EXAMPLE

DEMONSTRATION OF THE CONCEPT


WITH SIMPLE EXAMPLE

DEMONSTRATION OF THE CONCEPT


WITH SIMPLE EXAMPLEPROBLEM
(OSCILLATOR)

MODELLING PENDULUM WITH DAMPING

USING STATE SPACE TRANSFORM

CONTINUED

TEST
TO IDENTIFY THE LEVEL OF UNDERSTANDING
PROBLEM:- BY CONSIDERING NONLINEAR DAMPING

FORMATTING PLOTS
(Used for comparing and Interpreting
Theoretical and Experimental Results)

A plot can be formatted to have a required appearance.


With formatting you can:

Add title to the plot.


Add labels to axes.
Change range of the axes.
Add legend.

Add text blocks.


Add grid.

FORMATTING PLOTS
There are two methods to format a plot:

1.

Formatting commands.
In this method commands, that make changes or additions to the
plot, are entered after the plot() command. This can be done in
the Command Window, or as part of a program in a script file.

2.

Formatting the plot interactively in the Figure Window.


In this method the plot is formatted by clicking on the plot and

using the menu to make changes or add details.

FORMATTING COMMANDS
title(string)
Adds the string as a title at the top of the plot.

xlabel(string)
Adds the string as a label to the x-axis.

ylabel(string)
Adds the string as a label to the y-axis.

axis([xmin xmax ymin ymax])


Sets the minimum and maximum limits of the x- and y-axes.

FORMATTING COMMANDS
legend(string1,string2,string3)
Creates a legend using the strings to label various curves (when
several curves are in one plot). The location of the legend is
specified by the mouse.

text(x,y,string)
Places the string (text) on the plot at coordinate x,y relative to the
plot axes.

gtext(string)
Places the string (text) on the plot. When the command executes
the figure window pops and the text location is clicked with the
mouse.

EXAMPLE PROGRAM
clc;

Light Intensity as a Function of Distance


1200

clear all;

Theory
Experiment

x=[10:0.1:22];

1000

xd=[10:2:22];
yd=[950 640 460 340 250 180 140];

plot(x,y,'-','LineWidth',1.0)

INTENSITY (lux)

y=95000./x.^2;

800
Comparison between theory and experiment.
600

400

hold on
plot(xd,yd,'ro--','linewidth',1.0,'markersize',10)200

hold off
xlabel('DISTANCE (cm)')

10

12

14
16
18
DISTANCE (cm)

20

ylabel('INTENSITY (lux)')
title('\fontname{Arial}Light Intensity as a Function of Distance','FontSize',14)

axis([8 24 0 1200])
text(14,700,'Comparison between theory and
experiment.','EdgeColor','r','LineWidth',2)

legend('Theory','Experiment',0)

22

24

OPEN WEB RESOURCES

Mathworks Information
Mathworks: http://www.mathworks.com
Mathworks Central: http://www.mathworks.com/matlabcentral
http://www.mathworks.com/applications/controldesign/
http://www.mathworks.com/academia/student_center/tutorials/launchpad.
html
Matlab Demonstrations
http://www.mathworks.com/cmspro/online/4843/req.html?13616
http://www.mathworks.com/cmspro/online/7589/req.html?16880
Select Help-Demos in Matlab
Matlab/Simulink student Select Help in Matlab on extensive help about
Matlab, Simulink and toolboxes
http://www.mathworks.com/academia/student_center/homework/
http://www.mathworks.com/academia/student_center
Other Matlab and Simulink Books
Mastering Matlab 6, Hanselman & Littlefield, Prentice Hall
Mastering Simulink 4, Dabney & Harman, Prentice Hall
Matlab and Simulink Student Version Release 14

OPEN WEB RESOURCES


www.mathworks.com/
www.mathtools.net/MATLAB
www.math.utah.edu/lab/ms/matlab/matlab.html
www.mit.edu/afs/athena.mit.edu/software/matlab/
www.utexas.edu/its/rc/tutorials/matlab/
www.math.ufl.edu/help/matlab-tutorial/
www.indiana.edu/~statmath/math/matlab/links.html
www.eng.cam.ac.uk/help/tpl/programs/matlab.html

OPEN WEB RESOURCES


Messner

approach,

and Tilbury, Controls Tutorial for MATLAB and SIMULINK: A Web-based


Prentice-Hall, 1999.

Sigmon and Davis, MATLAB Primer, 6th Edition, CRC Press, 2001
Gockenback, A Practical Introduction to MATLAB, 2nd Edition, CRC Press, 2005.

http://www.mathworks.com/access/helpdesk/help/techdoc/matlab.html

http://www.mathworks.com/access/helpdesk/help/toolbox/simulink/

http://www.mathworks.com/access/helpdesk/help/pdf_doc/matlab/getstart.pdf

http://www.mathworks.com/access/helpdesk/help/pdf_doc/matlab/using_ml.pdf

http://www.mathworks.com/access/helpdesk/help/toolbox/control/control.shtml

http://www.mathworks.com/academia/student_version/

http://www.mathworks.com/academia/student_version/companion.html

http://travis.eng.man.ac.uk/barry/control2/lab/SIMULINK.htm
http://matlab.kimhua.co.kr/digest/dec98/nonlinear.html

OPEN WEB RESOURCES

http://www.scsolutions.com/feedback.html

http://www.math.mtu.edu/~msgocken/intro/intro.html

http://www-personal.engin.umich.edu/~tilbury/tutorials/matlab_tutorial.html

http://www.eng.fsu.edu/~cockburn/matlab/matlab_help.html

http://www.engin.umich.edu/group/ctm/working/mac/simulink_basics/
http://www.messiah.edu/acdept/depthome/engineer/Resources/tutorial/matlab/simu.html
http://rclsgi.eng.ohio-state.edu/courses/me780/handouts/simulink.pdf
http://www.mae.ncsu.edu/homepages/buckner/simulink2.pdf
http://www.tutorgig.com/showurls.jsp?group=896&index=0
http://www.rpi.edu/dept/chem-eng/WWW/faculty/bequette/lou/simtut/simtut_html.html
http://www.math.siu.edu/matlab/tutorials.html

OPEN WEB RESOURCES


http://wolfman.eos.uoguelph.ca/~jzelek/matlab/ctms/
http://www.engin.umich.edu/group/ctm/
http://www.me.cmu.edu/matlab/html/
http://www.math.utah.edu/lab/ms/matlab/matlab.html
http://www.indiana.edu/~statmath/math/matlab/
http://spicerack.sr.unh.edu/~mathadm/tutorial/software/matlab/
http://www.math.ufl.edu/help/matlab-tutorial/matlab-tutorial.html
http://www.cs.ubc.ca/spider/cavers/MatlabGuide/guide.html

http://www.class.umd.edu/enme/403/0101/t1.html

http://www.math.mtu.edu/~msgocken/intro/intro.html

http://www.engin.umich.edu/group/ctm

THANK YOU
Any Questions ?

You might also like