B
ASIC
E
NGINEERING
';ERIES
AND
OOLS
INTRODUCTION
TO
~ATLAB
7
FOR
ENGINEERS
WILLIAM
J.
PALM
III
Rip
By
Computer
Killer
Numbered Examples:
Chapters
One to Five
Number and Topic
Chapter
One
1.1
- 1
Volume
of
Vectors and displacement
Aortic pressure model
Transportation route analysis
Current and power dissipation
in
resistors
A batch distillation process
2.3-7 Height versus velocity
2.4-1 Manufacturing cost analysis
2.4-2 Product
co
t analysis
2.5-1 Earthquake-resistant building design
2.6-1 An environmental database
2.7-1 A student database
Chapter
Three
3.2-1 Using global variables
3.2-2 Optimization
of
an
irrigation channel
Number and Topic
Chapter
Four
4.3-1
Height and speed
of
a projectile
4.5-1
5.6-3
5.6-4
Load-line analysis
of
electrical circuits
Frequency-response plot
of
a low-pass
filter
Plotting orbits
A cantilever beam deflection model
Temperatme dynamics
Hydraulic resistance
Estimation
of
traffic flow
Modeling bacteria growth
Breaking strength and alloy
composition
Response
of
a biomedical instrument
Numbered Examples:
Chapters
Six to Ten
Number and Topic
Chapter
Six
6.1-1 Gauss elimination
6.2-1 Left-division method with three
of
thread
7.2-1
Mean
and standard deviation
of
heights
7.2- 2 Estimation
of
height distribution
7.3- 1 Optimal production quantity
7.3- 2 Statistical analysi and manufacturing
tolerances
7.
4-1
Robot path control using three knot
points
Number and Topic
Chapter
Eight
8.2-1 Velocity from an accelerometer
8.2-2 Evaluation
o[
Fre 'nel's cosine integral
8.5-1 Response
of
an
RC circuit
8.5-2
Decayin
+
fU)
Simulink model
of
a
tWO-Jl1a~s
system
SiJl1ulink model
of
a rocket-propelled
sled
9.4-2 Model
of
a relay-controlled motor
9.5-1 Re!>ponse with a dead zone
9.6-1 Model
of
a nonlinear pendulum
Chapter
Ten
10.2-1
10.
2-2
10.3-1
Intersection
of
two circles
Positioning a robot arm
Topping the
Green
Imroduction
to
Engineering Design a
nd
Problem
Solving,2/e
ISBN 0072402210
Eisenberg . .
A Beoinner Guide
to
Technical
CommUJ1\CalIOn
ISBN" 0070920451
Finklestein
Pocket Book
or
Technical Writing for Engineer a
nd
Scientists. 2e
ISBN 0072976837
Gottfried
Spreadsheet Tools for Engineer
LI
in
g Excel
ISB
N 0072480688
Palm
Introduction
to
e
ISBN 0072463775
Eide/JenisonIMashaw/Northup
Engineering Fundame
nt
al and Problem Solving,
4/e
ISB 0072430273
Hoi tza pple/Reece
Founda
ti
On>
of
En
gi
neering.
2/e
ISBN 0072480823
Holtzapple/Reece
Concepts
in
Engineering
ISBN 0073011770
MartinlSchinzinger
Etilics in Engineering, 4/e
ISBN 0072831 154
Introduction to MATLAB 7
for Engineers
WiUiam
J.
a
Caracas
Kuala
Lumpur
Lisbon
Lo
nd
on
Madrid
Mexico
City
Mil
an
Montreal
New
Delhi
Santiago
Seoul
Singapore
Sydney
Taipei
Toronto
ABOUT
THE
AUTHOR
William
J.
Palm
11/
is Professor of M
En
g
in
ee
rin
g a
nd
Astronautical Sciences
from
Northweste
rn
University
in
Evanston, Illinoi
s.
During
hi
s
33
years
as
a f
ac
ulty
memb
er,
he h
as
taug
ht
and
MATLAB.
These include System Dynamics (McGraw-Hill, 2005).
He wrote a chapter
on
control
sys
tem
s
in
the
Mechanical Engineers' Handbook
(M. Kutz, ed.,
Wiley
, 1999),
and
was
a special contributor
to
the
fifth editions
of
Statics
and
Dynami
cs,
both
by
J.
L. Meriam
Research Center
at
the
University of Rhode Island
from
1985
to
1993, and is
the
coholder of a patent
fo
r a robot hand. He served
as
Acting Department Chair
from
2002
to
2003
.
Hi
s industrial experience
is
in
a
utom
ated manufacturing;
modeling
and
simulation of
naval
1.7 Problem-Solving Methodologies 52
1.8 Summru·y 60
Problems
61
CHAPTER
2
Numeric, Cell,
and
Structure
Arrays
69
2.1
Arrays 70
2.2 Multidimensional Arrays
81
2.3 Element-by-Element Operations
83
2.4 Matrix Operations 97
2.5 Polynomial Operations Using Arrays 107
2.6 Cell Arrays 112
2.7 Structure Arrays 117
2.8 Summary
123
Problems 125
CHAPTER3
Functions
and
Files 141
3.1
Elementary Mathematical Functions
4.6
The
swi
tch
Structure
225
4.7
Debugging MATLAB Programs
228
4.8
Applications
to
Simulation
234
4.9
Summary
239
Problems
241
CHAPTER
5
Advanced Plotting
and
Model Building 259
5.1
xy
Plotting Functions
260
5.2
Subplots and Overlay Plots
6.2 Matrix Methods for Linear Equation 365
viii
Contents
6.3 Cramer's Me
th
od 377
6.4
U
nd
e
rd
etermined S
ys
tems
6.5 Overdetenllined S
ys
tems
6.6 Summary 398
Problems 403
C
HAPTER7
Probability, Statistics, and
Interpolation
417
38
0
394
9.4
Pi
ecewise-Linear Models 550
7.3 Random Number Generation 436
10.1 Symbolic Expressions and Algebra 587
7.4 Interpolation 444
10.2 Algebraic and Transcendental
7.5 Summa
ry
457 Equations 596
Problem 458 10.3 Calculus 603
CHAPTERS
Numerical Calculus and Differential
Equations
465
8.1 Review
of
Integration and
Differentiation 466
8.2 Numerical Integration
471
8.3 Numerical Differentiation
478
8.4
Analytical Solutions
to
Differential
Equations 483
8.5
Numerical Methods for Differential
Equations
490
8.6
Guide
to
Commands and Functions in
This Text
649
APPENDIXB
Animation and Sound in MATLAB
661
APPENDIX
C
Formatted Output in MATLAB 672
APPE
DIX
D
References
675
APPENDIXE
Some Project
Suggestions
www.mhhe.com/palm
Answers
to
Selected Problems
676
Index
679
PREFACE
F
or
me
the
ame
logical, relational,
conditional, and loop structures as
other
programming languages, such as Fortran,
C,
BASIC
, and
Pa
scal. Thus it can be used to teach programming principles. In
most schools a MATLAB
cour
se has replaced
th
e traditional Fortran course, and
MATLAB is the principal computational tool us
ed
throughout the curriculum. In
some techni
ca
l specialties, such as signal processing and control systems, it
is
the
standa
rd
software package
for
analysis and
de
impossible witb
traditional
programming
languages. MATLAB
is
also extensible; currently more
than
20
"toolboxes" in various application areas can be used with
MATLAB
to
add new
commands
and capabilities.
MATLAB is available for
MS Windows and Macintosb personal
computers
and for
otber
operating systems. It
is
compatible
across all tbese platfonllS, which
enable
s users to share their programs, insights, and ideas.
TEXT
OBJECTIVES
AND
PREREQUISITES
This text
methodology as practiced by the engineering profession in general and as applied
to the use
of
computers
to solve problems in particular.
This
methodology is
introduced
in
Chapter
I.
MATLAB is " registered trademark
of
The MathWorks. lnc.
Ix
Pr
eface
The reader is a
ss
umed
to
h
av
e some knowledge
of
algebra a
nd
trigonometry ;
kn
ow
ctl lcal
,C
IICU
lts, and
basic sta
ti
cs and
dy
namics is req uired
to
u
nd
ers
ta
nd some of the eXdmples.
TEXT
ORGANIZATIO
N
This text is
an
u
pd
ate to
th
e author's pr
ev
ious
tex
t.
' In addition
nd
me
nu
structures. It also
1I1t
ro-
duces the pro
bl
e
m-
solving methodology. Chapter 2 introduces
th
e con
c.e
pt
of
an
arr
ay,
which is the fundame
nt
al
data eleme
nt
in
MATLAB,
a
n~
desc
nb
fu
nctions, and users can define
tb
elr own functIons and
save them as a
fi
le for reuse.
Chapter 4 treats programmi ng wi
th
MATLAB and covers relation
al
and logi-
cal operator
s,
conditional statements, for and
whi
Ie loops, and
th
e switch structure.
A major application
of
th
e chapter's material is
in
si
mul
ation,
to
which a section
is devoted.
these s
ta
n
da
rd
s,
so they are emphasized. The chapter
th
en covers MATLAB commands
fo
r pro
du
cing
di
fferent types
of
pl
ot
s and fo r
controlling
th
e
ir
appearance. F
un
ction
di
scovery, w
hi
ch uses data plots to
its modeling coverage.
Chapter 6 covers the solution
of
linear algebraic equa
ti
ons, which
ar
ise in
applica
ti
ons
in
a
ll
fie
ld
s
of
eng
in
eering. "Ha
nd
" solution me
tb
ods are reviewed
fi
rs
t.
This r
ev
y.
The chapter
th
en shows how to u
se
MATLAB to solve systems of
lin
ear e
qu
a
ti
ons
th
at have a unique solution. The
use of MATLAB with
un
de
rd
etermined a
nd
overdetermined systems is c
ove
red
in
two optional sec
ti
on
s.
Chapter 7 r
ev
ons. The chapt
er
concludes with lin
ea
r
" n
fl
vd
ll
C
li
on
10
MArViB
6 for
En
gin
ee
r
s,
McG
r
aw-
Hili
.
Ne
w
Yo
rk.
2000
interpreting
th
e nume
ri
cal method
s.
Numerical integration and differenti a
ti
on
methods are tre
at
ed. Ordinary differential equation solvers in
th
e core MATLAB
program are
co
vered, as we
ll
as
th
e l
inear
-system solvers in
th
e
Co
ntrol System
toolbox.
Chapt
er 9 introduces Simulink: which is a graphi
er 10.
Chapter 10 covers symbol
ic
me
th
ods for manipulating al
ge
br
aic
ex
pr
essions
and for solving al
ge
braic and transcendental equa
ti
ons,
ca
lculus, differential e
qu
a-
tions, and matrix al
ge
bra probl ems. The calculus appli
ca
ti
ons include int
eg
ra-
tion and differentia
Ap
pendix A
co
ntains a guide to the
co
mm
ands and func
ti
ons introdu
ce
d
in the text. Appendix B is an introduc
ti
on to producing animation and sound
with
MA
TLA£.
Whil
e not essential to l
ea
rning MATLAB,
th
ese
features are
helpful for
ge
nerating student interes
t.
Appendix C summarizes functions f
or
ching a fres
hm
an MATLAB c
our
se.
Ans
wers to
se
le
ct
ed problems and an
ind
ex
app
ea
r at the end of
th
e tex
t.
AU
fi
gures, tables, equations, and exercises have b
ee
n
number
ed according
to their chapter a
nd
se
ction. F
rst f
our
cha
pt
ers constitute a
cour
se in the essentials of
MAT
LAB.
The
remaining six cha
pt
ers
ar
e independent of each
other
, and may be covered in any
order, or may be
omitt
ed if ne
ce
ssary.
The
se
ch
apters provide additional
cov
erage
and examples
of
features,
which
ha
ve
been
designed
to
en
han
ce
it
s u
se
fuln
ess
as
a
reF
ere
nc
e.
• Throuahout
each
of
the
chapter
s,
num
e
rou
de
sc
riptions of specific
MATLAB
commands.
• Appendix A
is
a complete s
umm
ary
of
all
the
cO
ll1l~
ands
a
nd
functions
described
in
the
text
, grouped
by
category, along with the number of tbe
page
on
wbich
they
argin
or
in
sec
ti
on headings where they
are
introduced.
• The
ind
ex
has
four
section : a
Ii
ting of
sy
mbol
s,
an
alphabetical
li
st of
MATLAB
co
mmand
s a
nd
functions, a
li
se
relatively st
rai
ghtforward exercises allow readers
to
a
ess
their
gra
p of
the
material
as
soon
as
it
is
covered.
In
mo
st ca es the
answer
to
the
exercise
is
given
with
the
exercise. Students should work
The e problems
are
denoted
by
an
asteri k next
to
their number (for
example.
15*).
Two
features
have
been
included
to
motivate
the
student toward MATLAB
and
the engineering profession:
•
Mo
t of
the
examples
and
the
problem deal with engineering applications.
The~e
nt
that illustrates
th
e cha
ll
enging
and
interesting
opportunities
th
at awai t eng
in
eers
in
th
e
21
st century. A description of the
ac
hi
evement, its
re
lat
ed
eng
in
eering
di
sc
ipline
structors who have adopt
ed
this text for a course. Thi s ma
nu
al contains the complete so
luti
ons to a
ll
the Test
Your
Understanding
exe
rci
ses and
to
all the chapter problem
s.
The text website
(at http://www.
mhh
e.com/palm) also
ha
s downloadable
file
s con taining the major
programs
in
th
e t
ex
anonymou~
re
viewer
s.
patiently reviewed the manuscript a
nd
sugges
ted
many helpful corrections and
additions.
Steven Ciccarelli,
Rochester Institute
of
Technology
Dwight D
avy,
Case Western Reserve University
Yueh-Jaw Lin, The University
of
Akron
Armando Rodrique
z,
Arizona
Stale University
Thomas Sullivan, Carnegie Mellon University
Daniel Valentine, Clarkson University
Elizabeth Wyler,
Thomas
Nelson
Community
father
was
always there for support before he passed
away. Finally. I want
to
thank
my
wife, Mary Louise. and
my
children. Aileene,
Bill, and Andy, for their understanding and
!>upport
of
this project.
William
J.
Palm
III
KingMon.
Rhod
e Is
land
April,2004
xiii
Introduction to MATLAB 7 for Engineers
Engineering in
the
21
st
Century
d more capable
of
interacting with their environment, in-
stead
of
just observing
it.
NASA's
pl
anetary rover Sojourner landed on Mars on July 4, 1997, and ex-
cited people on Earth w
hil
e they watched
it
successfu
ll
y explore the Martian
surface
to
determine whee
l-
so
il
interactions,
to
analyze rocks and so
il
, and to
return
im
scoveries
of
the 21st centur
y,
th
ey obtained strong evidence
th
at water once existed on Mar in sig
nifi
ca
nt
amount
s.
About the size
of
a golf cart, the n
ew
rovers have six wheels,
eac
h with
its own motor
s.
They have a top speed
of
5 centimeters per second on flat hard
ground and can travel
up
to
about 100 meters per day. Needing 100 watts to move,
th~y
ments for
geo
.
log~cal
studie
s.
Nine cameras provide hazard avoidance, navigation,
a~d
panoramic views. The on-boa
rd
computer
ha
s 128 MB
of
DRAM
and coor-
dmate all the s
ub
systems including communications.
All engineering
di
sciplines we.
re
in
volved with the rover
s'
design and launc
h.
Th~
MATLAB Neural Network, Signal Proce
Script
Files and the EditorlDebugger
1.5
The
MATLAB Help System
1.6
Programming
in
MATLAB
1.7
Problem-Solving
Methodologies
1.8
Summary
Problem
s
CHAPTER
This is the
most
important chapter in the book.
By
the time you have finished this
chapter
, you wi]]
be
able to use MATLAB to solve
many
kinds
of
engineering
Section 1.7 discusses methodologies for approaching
engineering
problems, with
particular
emphasis
on a methodology to use with
computer
software such as
MATLAB. A
number
of
practice problems are given at the
end
of
the chapter.
*MATLAB is a registered trademark
of
The MathWork
s.
Inc.
1
3
CHAPTER
1 An Overview of MATLAB
How to U
se
T
hi
s Book
The book's ch
h
~pters,
111
that
orde
r.
Ch
a
pt
er 2
cove
rs ar
rays,
w
hi
ch
are
th.e
b~s
l
C
butldll1
g blocks
111
M~T
L
A
B
.
Ch
ti
on
s.
Ch
a
pt
er 4
cove
rs progra
mmll1
g uS
lI1
g
re
l
atIO
nal and 1
00
lcal opel atol s,
co
nditi
onal stateme
nt
s, a
nd
l
oo
p
s.
.
orm
a
tion
.
Thi
s
sec
tion
will
g
uid
e
yo
u to
th
e
a
ppropn
a
t
~
chapter.
Ch
a
pt
ers 5
thr
ough
10
are
ss
lOn
s of
ho
w to use MATLAB
to
so
l
ve
seve
ral
c
ommon
typ
es
of eng
in
ee
rin
g
probl
em
s.
Ch
apter 5 covers
t
~
o
a
Chapter 6
tr
ea
ts
the
solution of linear alge-
br
aic e
qu
a
ti
on
s,
including c
as
es
havin
g nonunique solutions Chapter 7 covers
probability, s
tati
s
tic
s,
a
nd
int
erpolation applications. Chapter 8 lIltroduces nume
r-
ic
al methods for
ear algebra,
and
transforms.
Reference and Learning Aids
The
book
has
been
designed as a reference as
we
ll
as
a learning tool. The special
features
useful
for
the
se purposes
are
as
fo
ll
ows
.
• Throughout
each
chapter
margin
notes identify where
new
These usually requi re more
effort
than
the
Te
st
Your
U
nd
ersta
ndin
g exercises.
• Each chapter
co
ntain
s t
ab
l
es
s
umm
ar
iz
in
g
the
MATLAB
commands
intr
od
ary
of what
you
sho
uld
be
a
bl
e
to
do
after complet
in
g that
chapter,
and
• A
li
st of
key
terms
you
s
hould
know.
• Appendix A
con~ains
tables of
MATLAB
commands, gro
in
c
lud
ed.
Th
e
fir
st is an
ind
ex
of
MAT
LAB commands and
sy
mbol
s;
th
e seco
nd
is an ind
ex
of to
pi
cs.
Software Upd
at
es
and
Accuracy
Software publishers can release software updates faster
, 7.2,
a
nd
so
fo
rth
,
th
at will change some of
th
e program's features. The best way
to
protect
yo
urself aga
in
st obsolete info
rm
ation is
to
c
he
ck the "What's Ne
w?
"
file
provided w
ith
th
e program, a
The MathWorks,
Inc
.,
of Natick, Massachuse
tt
s,
and
is
ava
il
ab
le for MS Windows and other com-
puter system
s.
The MATLAB interactive environment
al
l
ow
you
to
manage
va
ri
able
s,
import and export data, perform calc
ul
ations, generate plot
s,
and de-
purchased separatel
y,
but
a
ll
run under the core MATLAB program. Toolboxes deal with applications such
as
image and signal processing, financial analysis, control systems design, and
fuzzy logic. An
up
-to
-d
ate
li
st can
be
fo
und
at The MathWorks webs
it
e, which
is
discussed later
in
this chapte
r.
Thi text uses material from the core MATLAB
program, from two of the t
ool
boxes (the Control Systems
on
MATLAB, and requires MATLAB
to
run.
This book does not explain
how
to
install MATLAB. If you
purcha<;ed
it for
yo
ur own computer, the installation
is
easily done with the instructions that come
with
the , oftware. If you will be u ing MATLAB
in
a computer lab, it will have
been
in
sta
ll
ed for you.
In the next section we introduce MATLAB
by
means
of
some imple se ·sions
to
illustrate its interactive nature. basic syntax, and features.
thi
s
text
we
u
se
typewriter
font
to
r
ep
rese
nt
MATLAB
~ommands,
~ny
text
that
yo
u type
in
th
e
co
mputer, a
nd
any
MATLAB
responses~hat
a
ld
fa~e
typ
e for three plIlposes.
to
represent
vec
tor a
nd
matri
ces
in
norm
al mathematIcs text (for example, Ax = b),
to
represent a
key
on
th
e keyboard (for exa
mpl
e,
Enter), a
nd
to represent
the.
name
of a
sc
r
how
thi
s action w
ith
a eparate
sy
mbol.
Starting MATLAB
To
start
MATLAB
on
a
MS
Window
s
sys
tem
, do
ubl
e-cli
ck
on the
MAT
LAB icon.
You
w
ill
th
en
ea
r.
These are
th
e
. ;
~
-
- -
LJ(Q](8J
F1Ie
Ed,t
Debuo
De<ktop
Wmow
Help
Shortcut
~Ho
w
to"'dd
,
GJC1ftJ
~8
FIIe.
J
b~n
Jdemo
s
»
plot
lx,
vi
Fig
ur
e 1.1-1 The default
MATLA
B Dc ktop.
1.1
MATLAB Inleraclivo Sessions
Command window, the Command
Hi
story window, and the Current Directory
wi
nd
ow.
Across
th
e top
of
the Desktop are a
row
of
me
nu
names, '
Ind
a row of
icons ca
in
structions
of
v'l
ri
ous typ
es
ca
ll
ed
comma
nds.
jimetions
, a
nd
statements. Later we wi
II
discuss
th
e
di
rf
erences between these tyres, but for
now.
to
simplify the discussion,
we
wi
ll
ca
e cursor
i
~
WINDOW
located just aftcr
th
e prompt. If
it
is not, use
th
e
mou
se to
mov
e the
c ur
~o
r
.
The
prompt
in
the Student Edition looks
li
ke
EDU».
We
wi
ll
use
to acce s tile
s.
Do
ubl
e-
c
li
ck
in
g on a
fil
e na
me
wi
th th
e
ex
tension
.m
wi
ll
open
th
at
file
in
the MATLAB
Editor. The Editor
is
discussed
Directory windo
w.
The
Workspace w
ind
ow
di
splays the varia
bl
es created
in
th
e Command window.
Double-click on a
va
ri
a
bl
e name to open
th
e Array Editor, which is
di
scussed
in
Chapter 2.
The fourth window
in
the d
ef"a
ult De
nd
drag
it
to
th
e Co
mm
a
nd
window or the Editor. Double-cl icking on
a keys troke executes
it
in
th
e Command window.
You
can a
lt
er the a
pp
e,m
lIl
ce
or
th
e Desktop if
yo
u wish. For example,
to
eliminate a wind
th
e default configuration, click on the View menu, then click on
Desktop Layout, and . elect Default.
E
ntering
Commands
and
Expressions
To sec how simple
it
i. to use MATLAB, try entering a
few
commands on your
computer. If you make a typing
mi
stake. just press
th
e Enter key until you get
th
e prompt, and then retype
th
e line. Or, because MATLAB retains your
pre
v
iou
~
keystroke.
in
a command file, you can use the up-arrow key
(t
e line you
wa
nt, you can edit
it
using
th
e l
ef
t- a
nd
ri
ght
-a
rrow keys
(<-
and
~),
and the Backspace key, and the
SESSION
VARIABLE
CHAPTER
1
An
Ove
rv
iew of
MATLA
B
k
ec
the
Comma
nd wi ndow
Hi
st?ry
~i n~
ow'
hY
Ol~
l
can
~t~P~:
n~l~u
se
holdin
a
d
ow
n the l
ef
t mouse button, and
by hlghhghtmg t e
me WI 1 . '
'"
draaaina the
lin
e
to
the Command W
ind
nd
the MATLAB response looks like the fo
ll
o':
lll
g on .the
screen (we ca
ll
this interac
ti
on between you a
nd
MATLAB
an
II1t
erac
ll
ve
SeSSlOl1
,
or si
mpl
y a session).
»
8/10
ans
=
0 . 800 0
MATLAB uses high precision for its computations, but by default it usually
di
th
e number 5.316 x 10 as
5 .
316e+02
.
MATLAB has assianed the answer to a vari
ab
le ca
ll
ed
ans,
which is an
abbreviation for
answel~
A variable
in
MATLAB is a symbol used to
co
ntain a
value.
You
can use the va
ri
a
bl
e
ans
for further calculations; for exa
mpl
e, u
to
write ma
th
ema
ti
cal expression
s.
We will soon see
why this is
an
advantage.
You
can assign
th
e result
to
a va
ri
a
bl
e
of
your
own
choos
in
g,
say
r,
as follow
further calculations.
For
exa
mple,
»
s=20
*r
16
When
we do not s
pecif
y a variable
name
for a result, MATLAB uses
th
e
symbol a n s as a temporary variable containing the most recent an
swer
.
MATLAB has hundreds
of
functions available.
One
of
th
ese
is the s
quar
e
root function,
sqrt
( 9 ) .
We will s
ee
more
MATLAB functions in this chapter;
an
extensive list
of
math-
ematica
l functions is given in Chapter 3.
Oth
er
types
of
functions are covered
throughout the text.
Order
of
Precedence
A scal
ar
is a single number. A scal
ar
variable is a variable that contains a sin- SCALAR
9
g
le
number. MATLAB uses the symbols + - * / A for addition, subtraction,
sents right divisio
n.
, which is the normal division operator familiar to you. Typing
15!3
returnstheresult
ans
= 5.
MATLAB
ha
s another division operator, called l
eft
division, which
is
denot
ed
by the
ba
cksla
sh
(\
).
The
left division operator is useful for solving
se
ts
of
linear
algebraic equations, as we will see in Section 1.3. A good
way
to
ithmetic operations
Symbol Operation
MATLAB
form
exponentiation: a
b
a
~b
multiplication: ab a
*b
ri
ght division: al b =
~
alb
left division: a \b =
~
a \ b
addition: a + b
a~b
subtraction: a - b
a-b
10
CHAPTER
1
An
OveNiew
of
MATLAS
Ta
bl
ir.
Ex
po
n
enti
a
tion
,
ev
aluated
fr
om le
ft
to
rI
g
ht.
Mul
tip
li
ca
ti
on and
di
vision
with
e
qu
al
pr
t.
d to a
lt
er
thi
s ord
er.
E
va
lu
ation beg
in
s with
th
e innermost pair
of
parentheses,
~
~~
proceeds outward. Ta
bl
e 1.\
-2
s
~1Il1m
a
ri
~es
th
ese
-
8/
(4*2)
ans
=
» 3*4A2 + 5
53
»(3
*
4)A2
+ 5
149
»2r(1/3)
~
32
A
(O. 2)
»2r
(
l/3)
+
32
A
O. 2
»2r1/3
+
32
A
O.
2
ee
de
d in the expression 8 +
(3
*
5)
, but they make cle
ar
our
intention
to
multipl y 3 by 5 before adding 8 to
th
e result.
Test
Your
Understanding
T1.1-1 Use MATLAB to
co
mpute
th
e fo
ll
ow
in
g ex pressions.
a.
6~
+
sm
or
replaceme
nt
operator. It
works differently than the equals sign you know from
mathematic
s. When you
type
x=3
, you tell MATLAB to assign the value 3 to the variable
x.
This usage
is no different
th
an in mathematics. However,
in
MATLAB we can al 0 type
s
om
ething like this: x = x +
2.
This
teU
s MATLAB to
add
2 to the current
value
of
x,
and to replace the current value
side. There-
fore
,
one
variable, and only
one
variable, must be on the left-hand side
of
the
= operator.
Thu
s in MATLAB you cannot type 6 = x.
Another
consequence
of
this restriction is that you
cannot
write in MATLAB expressions like the following:
»
x+
2=
20
The
corre
sponding equation x + 2 =
20
is acceptable in algebra, and has the
solution
x = 18, but MATLAB cannot solve such an equation without additional
commands
of
time.
or
for
changing
the value
of
a variable
by
using a prescribed procedure.
The
following
example
shows how this is done.
11
12
eeeHi.FIF
WORKSPACE
CHAPTER
1
An
Overview
of
MA
TL
AB
Volume
of a Circular
Cylind
er
diu
s of 8 m. We
wa
nt
to construct
particul
ar
cy
lindn
ca
l tank .IS 15 n
?O
'ce
nt
oreater
bu
t h
avi
ng
th
e same heigh
t.
another
cy
lin
drical tank w
nh
a vo
lum
e - pel 0
. Th
is
gi
ves
r
=[i;
The session is sh
ow
n bel
ow.
First
we
ass
ign
va
lu
es to
th
e
va
ri
a
bl
es r a
nd
h representing
th
e
radius
and
a
ll
y
we
so
l
ve
fo
r
th
e required radius. For
thi
s problem we can
use
th
e
MATLAB
built-in
co
nsta
nt
pi.
»r
= 8 ;
»h
=
15
;
»V
=
es of
th
e
va
ri
a
ble
s r a
nd
V are
repl
ac
ed
with
th
e
new
va
lu
e
s.
T
lu
s i acceptable as l
on
g as we
do
n
ot
wish to use
V =
pi
*
(r
A
2)
*h
;.
Variable Names
The te
rm
works
p
ac
e refers to
th
e names a
nd
va
lu
es
of
a
ny
variables in use in the
curre
nt
work session. Variable names
mu
st beg
umma
ri
zes some commands and special
sy
mbols for
managing
the
work e sion. A semicolon at the e
nd
of
a line suppresses printing the results
to
th
e
sc
ree
n.
If
a semicolon is not put at the e
nd
of
a line, MATLAB displays
the results
of
the line on the screen. Even if
yo
u suppress the display with the
emicolon, MATLAB still retains the variable's value.
You
can put several commands on the same line if you separate them with a
clc
clear
clear
varl
var2
exist
( '
name
' )
quit
who
whos
Description
Clears
th
e
Co
mm
a
nd
window.
Rem
ove
s a
ll
va
r
ia
bl
es
ex
ists h
av
in
g
th
e name 'name'.
Stops
MATL
AB.
Li
sts the
va
ri
abl
es
curre
ntl
y
in
memor
y.
Li
sts
th
e c
urr
e
nt
va
eg
ul
ar
ly spaced
e
l
e
lll
e
nt
~.
Co
mm
a;
separat
es
elements of an a
rr
ay.
Se
mi
colon; suppresses creen printin
g;
al
so
denot
es
a new r
ow
in
of
x
changed from 2 to IS .
Jfyou
need to type a long line, you can use an ellipsis, by typing three periods.
to delay execution.
Fo
r example,
»NumberOfApples
=
10
;
NumberOfOranges
=
25
;
»NumberOfPears
=
12
;
»Frui
t
Purchased
=
NumberOfApples
+
NumberOfOranges
+NumberOfPears
FruitPurchased
=
variable
'
sqr
'.
b
eca
use
yo
u misspelled
sqrt
.
In
stead
of
retyping the entire line, press the up-
arrow key
(t)
once
to display the previously typed line. Press the left-arrow key
(
~)
several tim
es
to move the
cursor
and add the mis ing l , then press Enter.
Rep
eate
d use
of
'
fy
For example after you have
or
var
ia
bl
e who
efi
rst
few
characters
yo
u
spec~l'a
n
d
press
in
a
tile
up
-arr
ow
key
en
te
red
th
e
s
th
e l
as
t-t
yped
lin
e t
~t
st
ar
. .
. 1
TI
' feat
ur
e IS case-
se
ns
iti
ve.
name b
eg
in
s with
vo
.
li
S ' I '
fea
of a f
un
c
ti
on,
va
ri
ab
le, or
fi
le if
MATLAB
au
to
.ma
ti
ca
ll
y
c~
mp
f
~
he:
name
'a
nd
press
th
e Tab
exa
mp
l
e,
in
the session listed ea
rli
er,
u
l1l
qu
e,
It
IS a
ut
o,
mdtl
ca
ll
y
co
I b
MATLAB
co
mp
let
es
th
e name a
nd
.'
h d
e
di
tin
a
to crea
te
a new e
xe
cutable
li
ne
that u
ses
th
e van.
ab
le
FrUl
tPurc
ase
d'
If
'"
the
re
is
mor
e than one
the Tab key agam
to
see a
li
st
of
the
po
ss
ibil
it
ie
s.
I ah
The
up
-
arrow
(t)
and
do
w
n-
arr
ow
(t)
k
e.ys.
mo
ve u p and
(~)
key
s m
ove
left a
nd
r
ig
ht t
hr
ough a
Im
e
o
~l
e
c
hara
cter at a t
ll
ne
.
To
move through one word
at.
a ti
me
,
pr
e
Home to
m
ove
to
th
e b
eg
inn
ing
of a
lin
e; pr
es
s E
nd
to
m
ove
to the end of a
lm
e.
Pr
ess Del
to
de
lete the character
at
the c
ur
sor; pre
delete
(k
ill) to the end of
th
e
lin
e. .
MA
T
LA
B reta
in
s the last
va
lu
e of a
va
ri
ab
le
until
yo
u
qUI
t
MA
TLAB or clear
i
ts
va
pr
efer
to
u
se
the
va
ri
a
bl
e x
in
a
numb
er of
di
ffe
re
nt
calcul ation
s.
If you
fo
r
ge
t to enter the
co
rr
ec
t
e
clear
f
un
c
ti
on to remove
th
e
va
lu
es
of
a
ll
va
ri
a
bl
es
from memory,
or
yo
u
ca
n u
se
th
e
fo
ffe
re
nt
;
it
cl
ears
th
e
Co
mmand
w
ind
ow
of everyt
hin
g
in
th
e wind
ow
di
s
pl
ay,
but
th
e
va
lu
If
th
e v
ari
a
bl
e d
oes
not h
ave
a
va
lu
e
(i.
e.,
if
it
d
oes
not
ex
ist),
you
see
an
error
message. You can
al
so
ists' a 0 indicates
that
it
do
es
not exi
t.
Th
e who
fun
c
tion
li
sts
th
e
nam
es
of
all
th
e
va
ri
ables
in
memor
y,
but
doe
ec
ifi
ed,
Th
e wildca
rd
ch
ar
ac
ter * can be us
ed
to
di
s
pl
ay
va
riabl
es
th
at ma
tch
a
patt
e
rn
. For
in
s
tan
nam
es
a
nd
th
e
ir
s
iz
es
, a
nd
indic
at
es
whe
th
er or not
th
ey
h
ave
non
zero imaginary
pa
rt
s.
1.1 MATLAB Interactive Sessions
Ta
bl
e
co
nt
a
inin
g
th
e
Ill
os
t r
ece
nt
an
swe
r.
eps
Speci
fi
es
th
e
acc
ur
acy
of
fl
oa
tin
g po
e
ri
ca
l r
es
ul
t.
p i
Th
e
numb
er
1T.
The
di
fference be
tw
een a function a
nd
a co
mm
and or a stateme
nt
is that f
un
c-
tions have their argu
me
nts enclos
ed
clc
a
nd
qui
t are stateme
nt
s,
You
can quit
MAT
LAB by typing
quit,
On
MS
Wind
ow
s s
ys
t
em
s
yo
u can
also
cl
ick on
th
e F
il
e me
th
e
m.
Th
e sy
mb
ol
Inf
tands for
00
, w
hi
ch
in
pr
ac
tice means a number so large
th
at MATLAB cannot represenl
it.
For
ex
ample, typing
5/0
generates
th
e
an
s
we
ll
est number w
hi
ch, when added to ]
by
th
e computer, cre
at
es a number g
re
ater
th
an I. We use it as an indicator
of
th
e
accuracy of computations.
The symbols i a
nd
j denote
th
e
im
ag
inary unit, where i = j = p , We
use
th
em
to
create and represent complex number
so,
Complex Number Operations
MATLAB ha
ndl
es co
mpl
ex
number algebra automatica
lly.
For
ex
ample, the
number
CI = ] - 2i is e
nt
ered as follows: c l = 1 -
2i.
Caution: Note
th
at an a te
ri
sk is not n
ee
ded
betw
e
en
i or j a
nd
a
ca
re
ful.
For
exa
mpl
e.
th
e
ex
pr
ess
ions y =
7/2
* i
and
x
7/2
i gi
ve
t
wo
diff
ere
nt
r
es
ult
s: y =
(7
3+7i
; w =
5-9i
;
8.0000
- 2 .
0000i
»w*s
ans
=
78
.
0000
+
8.
OOOOi
»w/s
ans
=
-0
.
8276
- 1 .
0690i
Camp/ex
co
njugates have the same
re
al part but ima
gi
mple,
»(-3
+
7i)*(-3
-
7i)
58
because
.)3
2
+ 7
2
=
S8.
More co
mpl
ex number functions are discussed in
Chapter
3.
es
Yo
Under
tanding
T1.1-2
Gi
ve
n x
=-S
+ 9i and y
=6-2i,
di
splay formats
Command
format
short
formac.
long
formal
short
e
format
long
e
format
bank
format
+
format
format
compact
format
~oose
Description
and
example
Four decimal
di
gi
t (the default); 13.6745.
16
Menus and the Toolbar
calculations, but we rarely need to
see
a
ll
of
them.
The
default MATLAB display
form at
is
th
e
short
format, w
hi
ch uses four decimal
di
gits. You
ca
n di splay
more by typing
format
long,
w
hi
ch gives 16 digit
s.
To return to
th
stands for the numb
er
6.3792 x
10
-
3
.
Note that
in
this context e
does not represent the numb
er
e,
w
hi
ch is
th
e base
of
th
e natural l
ogar
ithm. Here e
stands
for
"ex
ponent."
It
is a poor choice of notation, but MATLAB follows
co
default app
ea
rance
oftheDe
sk
top is shown
in
Figure 1.1- ] .
Beside
s the
Command
wi ndow, the default
De
sktop includes three other windows, the
Command
Hi
stor
y,
Current
Dir
ec
tor
y,
and Workspace windows, which we discus
se
d in the previous
section. Across the top
of
the Desktop are a row
of
se
the
plotting functions; an editor window, called the EditorlDebugger, appears for use
in
creating program files. Each window type has
it
s own menu bar, with
one
or
mor
e menu s, at the top. Thus the menu bar will change as you change win.dows.
To activate,
or
se
l
ec
t, a menu, click on it. Each menu has several item . Click
on an
item
to se
lect
it. Keep
in
mind that
l'I1
.enus are contex
t-
sensitive. Thus their
contents chang
e,
Note
that these
menu
s
change
depending on what window
is
active. Every item on a menu
can
be
se
lected
with
the menu open either by clicking on the item
or
by typing its
underlined letter.
Some
items can be selected without the menu
being
open by
using the shortcut key
li
sted to the right
of
the item.
Tho
se items followed by
three dots (
o
Jen
a dialoo box that allows
YOLl
to
create a new program
fi
Ie
, .call.ed
~n
New I . 0 . I' . lIed the Editor/De
bu
ooer, or a new Flg
Ul
e 01
M-file, uS
Ing
a text
ec
ltol
ca . ' 0 0
Model
file
(a
file
type used
by
SlInullnk).
.'
.
Opens a dialog
box
that en
ab
les you
to
set the MATLAB
sea
rch
path.
Preferences.
Opens a
di
alog box that en
ab
les you
to
set preferences
for
such
items as fonts, colors, t
ab
spacing, and so forth.
Print
Opens a dialog box that enables you
to
print a
ll
of
ece
ntly used.
Ex
it
MATLAB Closes MATLAB.
The E
dit
menu contains the
fo
ll
ow
in
g items.
The
E
dit
Menu
in MATLAB 7
Un
do
Reverses the previous editing operatio
n.
Redo
Re
ve
rses
th
e pr
ev
iou
nt
s
of
th
e clipboard into the workspace as
one or more vari
ab
les.
Select A
ll
Hi
g
hli
g
ht
s a
ll
t
ex
t
in
th
e Command
wi
ndow.
Delete
Clears
th
e varia
bl
th
e Command History
window.
Clear
Workspace
Re
mo
ves
the va
lu
es
of
all variables from the workspace.
You
can use the Copy and Paste e
le
ctions
to
copy a
nd
pas te
commands
appear-
Ing
on
{h
e Command window. Howeve
r,
an
easier way is to use the up-arrow
Use
th
e
Desktop
menu to co
nt.rol
th
e
co
nfi
guration
of
the
Desktop
and to
di
s
pl
ay
tool bars.
Th
e
Window
menu has one
or
more items, depending on
what
you have
done thus far in your sessio
n.
tool bar, which is below the menu bar, provides buttons as shortcuts to
s
ome
of
the features on
th
e menus. Clicking on the button is equi
va
lent to click-
ing on the menu, then clicking on the menu item; thus
th
e button eliminates
one
click
of
the mouse.
The
first seven buttons from the left
co
rrespond to the
New
M -File,
Open
File, C
ut
,
Copy,
Paste,
Undo,
and
ook
th
ese
ca
pabilities are discussed
in
more detail.
The
followin g chapters also provide numerous
se
lf
-help exercises and
examp
les
of
how
th
ese features can be used
to
solve engineering pro
bl
ems.
Arrays (Chapter
2)
MATLAB has hundreds
of
functions, which we will
di
scuss throughout the text.
For example, to
log
(x).
(Note the
spe
lling differen
ce
between mathematics text,
In
, and MATLAB syntax, l o
g.)
You
comp
ute the base 10 log
ar
ithm by typing
10g10
(x)
.
The
inverse sine.
or
arcs
in
e, is obtained by typing
asin
(x)
.
It
returns an an
swer
ers (a set
of
number
s arranged in a specific order).
An exam
pl
e
of
an array variable is
one
that contains the numb
er
0, I. 3. and
6,
in
that o
rd
e
r.
We can use s
quare
brackets to defi ne the varia
bl
e x to contain
this collection by typing x
=
[0
, 1 , 3 ,
6]
.
y to
produce
another array z by typing the
single line z
= x +
y.
To
co
mpute
z,
MATLAB a
dd
s a
ll
the
corresponding
19
20
ARRAY
INDEX
CH
APTER
1 An Overview of MATLAB
. e z
Th
e r
es
ultin
g array z contains
th
a~;
i~tt
~
i'~r
handling arrays, MATLAB
t1~an
one
command.
B
eca
~l
se
O~s\
I~
~
c::~e
eas
ier
to
creat
e,
read, a
nd
document.
pro
grams
can
be
very
sholt.
er,
w
ith
th
e sp
ac
lll
g
In
Lh
e
lnst
ea
d,
you
typ
e
the
fir
st
m;lb
el an
Ie
the
numb
ers 0,
0.1
, 0.2,
. ,
, the sess
ion
i
s:
To
comp
ut
e w = 5 S
in
u
for
u - , . ,
»u
= [0 :
0.1
:
1
0] ;
»w
=
5*sin
(u) ; .
.'
* . ( )
com
ut
ed
th
e
fo
h
value
1n
th
e
aJ~aYf
u
M'
~~r~
to
per
fo
rm
many
calculati
on
s with just
illustrate
so
me
of
the
pow
el 0
a
few
co
mm
a
nd
on
th
e creen. The
va
lu
e are s
tOi
ed
~n
the
variab
l
es
u
and
w if
yo
u
ne
ed
them.
You
can
se
e
all
the u
va
lu
es
~~
t1u
es
the
sa
me
way.
Th
e number 7
is
ca
ll
ed
an
array tndex,
becau
se
it
points
to
a particular element
in
the
array.
»u
(7)
ans
=
0
.6000
pr
ev
iou
s session
as
follows:
»m
=
length
(w)
101
Array
that
di
s
pl
ay
on
the
sc
r
ee
n
as
a s
in
gle
row
of numbers with more than
one
d
esc
ribe
a polynomial
in
MATLAB
with
an
array whose elements are
th
e
pol
yno
mi
al's coefficients. starting
lI
'
ich
th
e coefficie
nt
of
th
e
hi
ghest power
of
x.
For exampl
e,
f(x)
are
th
e values of x such that
!(x)
=
O.
Polynomial
roots
can
be
fo
und
with
th
e
roots
(a)
function, where
1.3
Computing
with MATLAB
a is the polynomial's coe
ffi
cie
nt
array. The result is a column arr
ay
th
at co
0000
- 5 .
000i
1 .
0000
The roots are x = I and x = 3 ± 5i. The
two
comma
nd
s co
uld
h
avc
been com-
bined into the s
in
gle comma
nd
roots
(
[l
,
-7
, 40 ,
-34]
).
Roots of f
un
ctions o
th
.
3-1
Use MATLAB
to
determine h
ow
ma
ny
elements
<u'e
in
the array
[cos(O)
: 0 . 02 :
log10(100)]
. Use MATLAB
to
determine the
25th eleme
nt.
(Answer: 51 elements and 1.48.)
T1.3-2 Use MATLAB
to
fi
nd
the roots of the polynomial 290 -
11
x +
6x
2
se
d functions.
Chapter 3 gives
ex
tensi
ve
coverage of
th
e built-in f
un
ct
ion
s.
Table
1.3-1
Some
commonly
u ed mathemati
ca
l
functions
Function
e'
.,jX
In
x
loglo x
cos X
sin x
tan
function
u~e
radian
21
22
MAT-FlLES
ASCII FILES
DATA
FILE
CHAPTER
1
An
Overview
of
MA
T
LA
B
MATLAB users can create
th
e
ir
own :
un
c
ti
ons
~or
their speci
s.
As
we w
Ill
see 10 . ec
tl
on . , .
ro!!r
am files are saved with the exten
SIO
n . m, a
nd
thus are
ca
ll
ed M-files.
p
b MAT-files have the
ex
tens
ion.
mat
a
nd
~re
L1
sed
to
save the names and values
of
ASCII files that
ar
e
wn
tten
in
the MATLAB lang
ua
ge.
Because they are ASCII files, M-files
~a
n
be created
using just about any word pro
cessor-ge
nerically called a
tex~
ed
lt
~r-because
the ASCII
file
fo
rmat is the
ba
s
ic
fo
rm
at that a
an~
Macmtosh
,
for example) is not easy. Howe
ve
r, MAT-files conta
1l1
a machJne
Sig
nature that
allows them
to
be transferred. They can also be manipulated by
program
s external
to
MATLAB. Binary
file
s provide more compact storage than
ASCII
files.
The third type
of
file
we w
ill
be using
is
a data file, specifically an
ASCII
Retrieving
Your
Workspace
Variables
If
you want
to
stop using MATLAB but continue the session
at
a later time, you
mu
st use the
save
a
nd
load
comma
nd
s.
Typing
save
causes MATLAB to save
the workspace
va
riable
s,
that i
s,
th
e variable names, their sizes, and their values,
re
sponses.
To
save the
workspace
vari-
ables in another
fil
e named
filename
.
mat,
type
save
filename
. To load
the work. pace variables, type
load
filename
;
thi
s loads all the
workspace
variables from
th
e
file
filename
.
mat
t
or no extension at all.
If
the
file
name does not have
an
extension
MATLAB
assumes that
it
is .
mat.
'
1.3
Computing with MATLAB
23
To save
ju
st some
of
your variables, say,
var1
and
var2,
in
the
fi
le
filename
double-
precision (16 digits) format, type
save
filename
-d
ouble
. ASCl1
fil
es
co
ntaining s
in
gle-
pr
ecision data are recognizable by their use
of
the E
fo
rmat
to represent numbers.
For
example, the
number
1.249 x 10
2
is repre
se
nted as
1 .
249E+002
Save
Data
from the
File
menu in the
Command
window. You
ca
n aL 0 save
variables from
th
e Workspace Browser.
Directories
and
Search
Path
It
is impoI1ant to know the location
of
the files
you u
se
with MATLAB.
Fi
le location frequently
ca
uses problems for b
eg
inners.
Suppo
to
find your file
s.
Files are stored in directories, ca
ll
ed
fold
ers on
so
me
comp
uter systems. Directories can have subdirecto
ri
es below
the
m.
Fo
r
examp
le, suppose MATLAB was
in
sta
ll
ed on drive
c:
in
th
e
dir
ecto
Math toolbo
x.
The
path to thi s file is
c : \
matlab
\
toolbox
\
symbolic
.
The
full
name
of
a file consists
of
its pa
th
and its name, for example, c : \
matlab
\
toolbox
\
symbolic
\
sol
ve
.
for
this
fil
e i
a : \
homework
. As MATLAB is normally installed, when you type
problem1
,
1.
MATLAB first checks to see
if
probl
em1 is a variable and
if
so, displays
its value.
2.
If
not, MATLAB then checks to see if
problem1
is
one
of
its own
co
mmands
, and executes
it
if
directory
a:
j not
in
the search path, MATLAB will not find
the file and will generate an error message, unless you tell it where to look. You
can
do
this by typing
cd
a :
\hom
ework
, which stands for
"change
directory
to
a:
\
homework
."
This
will change the current directory to a :
homework
and
24
CHAPTER
1
An
OveNiew
Add
s
th
e dir
ec
tory
dirname
to
th
e search pa
th
.
Ch
an
cres
th
e curre
nt
directory to
dirname.
Li
sts
~
II
fil
es
in
th
e curre
nt
s
pl
ays
th
e c
urr
e
nt
director
y.
Rem
oves
th
e dir
ec
tory
dirname
fr
om
th
e search pa
th
.
Li
sts
the
MATLAB-
sp
ec
if
dir
to
get a
li
st
of
a
ll
fil
es.
Li
sts the
MATLAB-
spec
ifi
c
fi
les
in
directory
dirname
.
force
MATLAB
to
l
ook
in
th
at
e directory.
The
main
directory
on
th
e
di
sk
is
a:,
so
if
yo
ur
fi
le is
in
the ma
in
directory, be
s
ur
e to inc
lud
e
th
e
co
l
th
e earch
path
.
How
ever,
th
ere
are
several pit
fa
ll
s with t
hi
s
approach: (1) if
yo
u chan
ge
th
e
file
durin
g
yo
ur
session,
yo
u might
fo
mi
g
ht
not
be
permitted
to
save your
fi
le
on
th
e ha
rd
driv
e);
(3)
the
file
mi
ght be deleted or overwritten ifMATLAB is
rein
s
tall
ed; a
nd
(4)
so
m
eo
file
s
in
th
e c
un
e
nt
director
y,
type
dir
.
To
see
th
e
file
s
in
the
directory
dirname
, type
di
r
di
r
name.
The
can
a
dd
a d
ir
ectory
to
the
se
arch
pa
th
by
us
in
g
the
ad
dp
a
th
command.
To
remove
a dir
ec
tor
y
fro
m
sta
rt
th
e
browser.
To
save
th
e path settin
crs
click on Save in the
tool.
To
re
s
tore
the
d
efa
ult
se
arch
path
, click
on
Default
in'
the browser.
The e commands
are
n
ct
I
ons
In
It
s
progr
am
s.
These functions en
ab
le
you
to
write programs
whose opera
ti
on
depend
on
the
r
es
ult
s of calculations made
by
th
e program.
MATLAB
1.3
Computing
with
MA
TL
AB
Section 1
.6
gi
ves
an introduction
to
these topics. Chapter 4
co
vcrs thcm
in
greater deta
il
.
Plotting
with MATLAB (C
hapter
5)
MATLAB contains
ma
ny powerful functions for easi ly creati ng plots of several
di
ffere
nt
types, such as recti
generate a large
IlLtmb
er
of
x
va
lu
es
in
order
Lo
produce a smooth curve. The function
plot
(x
,
y)
generaLes a plot with the
x va
lu
es
on
th
e horizontal axis (the abscissa) a
nd
the y
va
lu
es
on
th
en
in
a
gra
phi
cs
w
ind
ow,
named Figure
No.1,
as
GRAPH
ICS
sh
ow
n
in
Figure 1.
3-
1. The
xlabel
f
un
ction places
th
e t
ex
t
in
PLOT
CHAPTER
1
An
Overview
of
MATLAB
for
th
e
ve
rtical axis. When the
pl
ot co
mm
a
nd
is
s
u
ccess[u
ll
y~xecute~
,
a
grap
hi
cs
wi
nd
lo
sed
by
se
le
cting Close on
th
e FIle menu
111
t!le
gl
ap
hl
cs
window.
You
w
ill
then be returned
to
th
e prompt
in
th
e
Command
w
tn
~
l
aces
th
e text at the top of the
pl
o.
t,
the
gtext
function places
th
e text
at
the point on
th
e plot where the cur
or
IS
located when you click the left mouse button.
.,
You
can create multiple plot
s-ca
lled overlay plot
s-
by
II1cludll1
g an
o.
ther
set or sets
, y ,
x,
z)
,
xlabel
('x
' ) ,
gtext
('y
' ) ,
gtext
( ' z ' )
After the plot appears on the screen, the program waits for you to
po
sition the
cursor and click the mouse buttoll, once for each
gtext
function u
se
d.
A
lth
ough MATLAB displays different colors for each curve, if you
are
go
ing
to
print the plot
on
a black-and-white printer, you should label
is to
li
se the
legend
fu
nction,
wh
ich is discussed
in
Chapter 5.
The plotting functions
xlabel
,
ylabel,
title
, and
gtext
must
be
placed after the
plot
functi
on
and separated by commas.
You
can also distinguish curves from one ano
th
er by us
in
g different line t
be
used. These are discussed
in
Chapt
er
5.
In
the above example,
we
had many
va
lu
es
in
the
ar
rays to be plotted, and thus
the curve plotted
in
Figure 1
.3-
1
is
smooth. When plotting functions, you should
always use
mnys
that have several hundr
ed
points so they will
plot
plotted curve. The function
ginput
can be used
fo
r thi s purpose.
Place
it
at
the
end
of
all
the plot and
pl
ot for matting statements, so
th
at the plot will be
in
its
final form.
Th~coll1n~and
[x
,
y)
=
ginput
(n)
gets n points and r
et
urns
MATLAB
plotting commands
C
ommand
[x
,
y]
=
ginput
(n)
grid
gtext
( '
text
' )
plot
(x
,
y)
title(
'
text
' )
xlabel
( ,
text'
)
ylabel
( '
text
mou
se.
G
ene
rates a plot of
th
e array y versus the
array
x
on r
ect
ilinear axes.
Puts text
in
a title
at
th
e top
of
the plot.
Add
s a t
ex
t l
abe
l to the horizontal axis (the abscissa).
Adds a text label to the vertical axis (the ordinate).
In
cases
where
).
You can conn
ect
the
data
point
s
wit
h Jines
if
you
wis
h.
In
that case, you
must
plot
the
data
twice,
once
wit
h a
data
marker
, and on
ce
wit
hout
a
unit
s
of
vo
lt
s.
To
plot
the data with
plus
Si!l1
1S u
se
the
following
sessio
n: b
»x
=
[15
: 2 :
23);
»y
=
[20
,
50
,
60
,
are discussed in
Chapter
5.
.
~ab
l
e
1.
3-3 s
umm
a
ri
zes th
ese
plotting
co
mmand
s.
The
grid
command
puts
g
nd
llIles on the plot. We will di
sc
uss oilier plotting functions, and the Plot
Editor
,
In
the
interval
0
~
t
~
5.
Put
a title on the plot, and
properly
label the axes.
The
va
ri
a
bl
e s represents speed in feet
per
seco
nd; the variable t repre
se
nts
time
in
seco
nds.
T1.3-4
Use
MATLAB
to plot the functions y =
ter
s.
27
28
C
HAPTER
1
An
Ove
r
view
of
MATLAB
Linear Algebraic Equations (Chapter
6)
.
You
can u
se
the
left
di
vi
sio
n
ope
rator (\ )
in
MATLAB
to
so
l
ve
s
uch
sets
in
MATLAB
yo
u
mu
st create
two
~
rr
ays;
we will ca
ll
them A
a
nd
B The arr
ay
A h
as as
many
row
s as there are e
qu
a
st
row
of A must
be
6,
12
, 4; the
seco
J~d
row
mu
st
be
7,
-2,3
,
and
the
third
row
mu
st
be
2,
8,
-9.
The array B contall1s the
constants
on
the
r~w
of B IS 70, the
~ec~
n
d
is 5,
and
the
th
ird
is
64.
The solut
io
n is obta
in
ed
by
typ
lll
g A \ B. The sess
IOn
IS
»A",
[6
,
12
, 4 ; 7 ,
-2
, 3 ; 2 , 8
r
ks
fi
ne when
th
e e
qu
a
ti
on set h
as
a unique solution. To lea
rn
h
ow
to
deal w
ith
pro
bl
ems h
av
in
g a nonunique
so
lut
io
n
(o
r perhaps no solution
- 4y + 8z =
tl
2
-5x
- 3)' + 7z = 75
1
4x
+ 9 y -
5z
=
-6
7
(A
nswer: x =
2,
Y = - 5, z =
10
.)
Statistics (Chapter
7)
MATLA
B h
as
a
lIumb
erof
u
~e
ful
f
e
ave
J
.·a~e)
o.r
a set?l
va
lu
es
st
ored
in
th
e a
rr
ay
x by typing
mean
(x)
. The standa
rd
d
evIa
tI
on IS o
btall1
ed by typing s
td
(x)
. Cha
on
random number generati on a
nd
methods for interpolating data.
Numerical Calculus, Difl'erential Equations,
and
Simulink
(Chapters
8
and
9)
Given a set
of
x a
nd
y
va
lu
es, MATLAB ca n numericall y compute the derivative
d
yj
dx a
nd
th
e
in
tegral I y
dx.
In
addition, MATLAB can numerically sol
eq
ua
ti
ons.
Symbolic Pl'ocessing (Chap
ter
10)
Given a function
y(x),
MATLAB can be used
to
obta
in
th
e derivative
dy
j
dx
and the integral I y dx
in
symbolic form, that i
s,
as a form
ul
a
in
stead
of
as a
set
ri
pt Files
and
the
Ed
itorlDebugger
You can per
fo
rm operations in MATLAB
in
t
wo
ways:
1.
In
the interac
ti
ve
mode,
in
w
hi
ch a
ll
co
mm
a
nd
s are entered direc
tl
e
comman
ds-o
ne at a
tim
e-at
the Co
mm
a
nd
window promp
t.
Yo
u can
run
the
fi
le
by
typ
in
g i
ts
Il
ame at
th
e Co
mm
a
nd
nd
s,
a repeated
set
of
comma
nd
s,
or h
as
arrays with many cleme
nt
s,
th
e interac
ti
ve
mode is
in
conve
ni
en
t.
Fortunatel
y,
MATLAB a
ll
ows you to w
ri
te your ow n progra
MATLA B uses t
wo
types
of
M-
fil
es: script
fil
es and f unction
fil
es.
You
can
use
th
e Editor/De
bu
gger built into MATLAB to create M-files. A script file con-
ta
in
s a sequence
of
MAT
LAB co
mm
ands, and is usef
ul
when you need to use
many commands or a
rr
th
e exten
si
on . m.
29
30
GLOBAL
VARIABLE
COMMENT
CHAPTER
1
An
Overview
of
MATLAB
. . of
M-fi
le is a function
file,
which
is
usef
ul
when you
neec~
to
Anothel t
y.
pe.
f t of commands.
files
ma
y
fcon
t~1Il
a
Wh~n
you
tYIJe
the
name of a script
fi
le at
th
e
c1udlllg
user-wlltten
un
c
IOn
s.
.
Command
wi
nd
ow
prompt,
yo
u
u
type
the
name
of
the
script
fi
le,
~e
say
that
yo
u are.
ru~nlllg
the
file"
or
"exec
uting
the
file
." The
va
lu
es
of vanables prod.uced by lllnnll1g a
script
fi
le are
s a
comment,
which
is not exec
uted
by
MA~LA~
.
CO~l1-
me
nt
s a
re
not
that
usef
ul
for
int
e
ractive
sess
ion
s. and
are
u
se
d mainly
111
scn
ignor
es
eve
ry
thin
g
to
the
ri
g
ht
of
th
e % symbol.
For exampl
e,
co
ns
id
er
the
fo
ll
owing
sess
ion.
»%
This
is
a
, save, and run a script
file,
us
in
g
th
e Editor/Debugger
built
int
o
MATLAB.
However, you m
ay
use an-
other
text
editor to cr
ea
te
th
e
file.
The
sa
mple
file
is s
hown
be
low.
the
sine
of
% .
he
square
root
and
displays
the
result
.
x
=
sqrt
(
[5
: 2 :
13
) ) ;
y =
sin
(x)
To
create
this
ne
w
M-file
(
as
shown
in
Figure 1.4-1.
T
ype
111
the
file
as
hown
above.
You
can
u e
the
keyboard and the
Edit
menu
in
the
EditorlDebugger
as
you
would
in
mo
st
word
processors
u~
tIt
1
ed
)vllth
the
na
.
me
exampl
e 1,
and
click
on
Save. The Edjtor/Debugger
wIll
au
tomatica
ll
y
provide
the
extension . m and save the
file
in
the MATLAB
current directory.
which
for
now
0.'1758
0.1'111
-0.17'11
-0.'1'175
Steck'
"'(
Progralrl
e;-:ample)
. m
'"
Th13
pt:ogram
cOIrlpute~
the
31.ne
of
t}jE
square
root
sna
dle.pla?s
tbl!::
cesult.
'1
-
>:
=
sqrc
(
[5
examplel
to
execute the progr
am.
You
should see
th
e
feult
di
splayed
in
the Command window. The session looks like
th
e followin
g.
»example1
y =
0 .
7867
0 .
4758
0 .
1411
0 .
1741
-0
.
4475
Figure 1.4-1 shows a MATLAB MS Windows screen containing the
Ll
sef
ul.
For example,
to
change the number evaluated from f 3 : 2 :
::.::.;
to
[2 : 5 :
27
J , simply edit the corresponding line and save the
file
again
(a
com-
mon
oversight is
to
forget
to
resave the file after making changes
to
it).
31
8
32
LOCAL
VARIABLE
CHAPTER
1
conventIon
for
naI~I~1
g
1. The n
ame
of
a
SCrIpt
file
.
b'
'
th
a lelter
and
may include dIgIts
variables'
th
at
is
the
n
ame
must
egll1
WI,
,
, , ' I ' t
er
lu
e
0
ittC~~l~~I~~S
b~cause
'
MATL'\B
wi
ll
n~t
be
file
the
ame
n
ame
as
a.
val
l
ab
le . h P 0
lCe
unl
ess
you
clear the van
ab
le.
ab
SC
rIpt
ek
t e ,
'f
command
fu
nction or
file
name a
lr
eady
fUl:ction.
Y~u
can
c h
e~
to
~~~
lllm
:
nd
.
For ex;mpl
e,
to
see if a variable
eX
Ists by US
Ing
doe
s n
ot
exist,
and
a .1 d'
It
~oe
s
.
To
see I " ' f i
le
' )
exa
m
le
1.
ma
lr
eadyexistS,type
exlst
(
example
1.
m " "
be oreP
creati
ng
the
(
'
e
~
amp
l
el
'
,
'
~uiltin
' )
before creat
in
?
~he
fi
l
e;
th
Is
will
return a 0 if
the
built
-in
func
tI
on
does
whic
h
mean
s that their
va
lu
es
are
a~a
Il
ab
l
e
III
the baSIC
workspace.
You
can
type
w
ho
to
see
wh
at
van
ab
I
es
are
un
ct
ion.
All
the vanables
III
a
sc
ript
file
are gl
oba
l.
Thu
s,
if
yo
u
do
not
n
ee
~
to
h
av~
access
to
~
11
va
ri
a
bl
e names, a
nd
wIl.1
re?uce
me
mor
y requirements. Creation of user-defined function files IS
dI
scussed
in
Chapter
3.
6.
You
can
u
se
th
e
type
command
to
view
an M-file without opening
it
with
the
function
mean . m is supplied
but
is not a built-in function. The
co
mmand
exist
( '
mean.
m
',
'
file
' )
wiJI
return a
2,
but
th
e command
exist
( ' mean
',
'
builtin
' )
will
return a
O.
Effective
Use
of'
the Command and EditorlDebugger Windows
Here a
re
ome
tip
on
us
ing
the
Command
and
Editor/Debugger windows
effectively.
1.
You
can
u
se
the
mouse
to
re
s
ize
and
move
windows so they can be viewed
ck
on
it.
2.
If
th
e Editor/Debugger
is
no
t docked, u
se
the Alt-Tab
key
co
mbi
nation to
switch back a
nd
forth
qui
ck
ly between the
Ed
itor/De
bu
gger
wi
nd
ow
a
file.
This technique a
ll
ows
you
to
check a
nd
correct yo
ur
prog
ram
quickly. After making changes
in
th
e scri pt
file,
be
sure
to
save
it
before
switching
to
the Com ma
nd
window.
3.
You
g
hli
g
ht
th
e r
es
ults shown
in
th
e Comma
nd
wi
nd
ow,
then copy and paste
th
em
to
the Edi
to
r/Debugger
wi
nd
ow
above or below your script file (use
Copy a
nd
Paste on the E
dit
a
nd
import
it
into
th
e word
processor
of
yo
ur
c
hoi
ce (change the
file
name or
it
s
ex
tension if
yo
u intend
to
u e the script file again!).
Debugging
Script
Files
Debuggin.g a program is the proce
ss
offinding and removing the "bugs," or e
to
an incorrect mathematical procedure, called runtime error
s.
They do not necessa
Jil
y occur every
tim
e the program
is
executed: their
occurre
nc
e often depends
on
the particular input data. A common example
is division
by
zero.
MATLAB error messages usua
lly
aJlow you
to
find syntax errors. However, run-
tim
e errors are more difficult
to
locat
e.
To
locate such
that
it
require
rel
atively simple programs
to
accomplish many types
of
tasks. Thus you
probably will not need
to
u
se
the Debugger for many
of
the problems
encountered
in
thi
s text.
33
34
CHAPTER
1
An
Overview
of
MATLAB
Programming Style
Comments
command,
di
sc
ussed
later
in
this
chapter. Therefore, if you intend
to
use
the
cript
file
in
the
future
,
co
nsider putting
key
words that describe the
script
file
in
this
first
lin
e
(ca
ll
in
the first line.
b.
The date created,
and
the
creators' names
in
the second line.
c.
The definitions of
the
variable
name
s for every input a
nd
output
va
riabl
e.
Divide
this
sec
tion
into
at
least
two
s
ub
rem
e
ntfor
all input
and
aLI
ou.tput variables!
d.
The
nam
e of
every
user-defined
function
ca
ll
ed
by
the program.
2. Input section
In
this
sect
ion
put
the
input data and/or the input functions
that enable
data
to
deliver the
out
put
in
wh
atever
for
m
required.
For exampl
e,
this
section
mi
ght conta
in
function s
for
displaying
th
e output on
the
sc
reen.
In
clude comments where
app
ro
pri
ate
not
necess
ary
her
e because
the
tex
t discu
ssi
on
associated with the
program provides
the
required
do
c
um
e
nt
atio
n, a
nd
because
we
all know w
ho
wrote
th
ese
programs
ic
fai
lure
of
an
en
aineerin a
sys
tem
ha
be~n
traced
to
th
e
mi
s
und
ersta
ndin
g of
the
units used for
~he
inpL~
a
nd
output
va
nabl
the
~.S.
Cust?mary.
Sy
ste
m a
nd
th
e British En
gi
neering Syste
m.
SI
(Systeme Internatlonale) IS
th
e
Int
e
rn
a
tion
al metric
sys
tem.
Us
ing Script Files to Store Data
You
mi
g
ht
le
1.4-1 SI and FPS unils
U
ni
t name and abb.·eviation
Quantity
S[ unit
FPS unit
Time
sec
ond
(s)
seco
nd (sec)
Length
meter (m)
fOOL
(f
l)
Force
newton (N)
pound (
Ib
)
Ma
ss
kilogram (kg)
s
lu
g
(' F),
kelvin (K)
degrees Rankine
(OR)
a set of daily temperature measurements at a pa
rti
c
ul
ar locat
ion
, which are needed
from
tim
e
to
time for calc
ul
ation
s.
As
a short exa
mpl
e,
consider the following
script
fi
le, whose na
me
is
mydata
Fahrenheit
.
temp_F
=
[72
,
68
,
75
,
77
, 83 ,
79]
A session to access this data from
th
e Comma
nd
window, a
nd
convert
th
e tem-
peratures
to
degrees Celsius, is
»mydata
temp
_ F =
72
68
Thus
68
° Fahrenheit correspo
nd
s
to
20° Celsius.
Te
derst
nding
T1.4-1 Create, save, a
nd
run
a
sc
ript
file
that solves the foJlowing set of equations
fo
r given values
of
a,
b,
and c. Check your
file
for the case a =
112
,
b = 7S, a
nd