Tải bản đầy đủ (.pdf) (348 trang)

Introduction to matlab 7 for engineers

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (41.98 MB, 348 trang )

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


a circular cylinder
1.6-1
Analysis
of
temperature data
1.6-2
Plotting with a
for
loop
1.6-3
SeIies calculation with a
for
loop
1.6-4
Series calculation with a
while
loop
1.6-5
Growth
of
a bank account
1.7-1 Piston motion
Chapter
Two
2.3-1 Vectors and relative velocity
2.3-2
2.3-3
2.3-4
2.3-5
2.3-6

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

Data sorting
4.5-2
Flight
of
an
instrumented rocket
4.5-3
Time
to
reach a specified height
4.6-1
Using the
swi
tch
structure for
calendar calculations
4.8-1
A college enrollment model: Part I
4.8-2
A college enrollment model: Part II
Chapter
Five
5.2-1
5.3-1
5.3-2
5.5-1
5.5-2
5.5-3
5.6-1
5.6-2

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

unknowns
6.2-2 An electrical-resistan
ce
network
6.2-3 Ethanol production
6.2-4 Calculation
of
cable ten ion
6.2-5
The
matrix inverse method
6.4- 1 A
set
having a unique solution
6.4-2 An und
er
determined set
6.4- 3 A statically indeterminate problem
6.4-4 A singular , et
6.
4-5
Production planning
6.4-6 Traffic engineering
6.5- 1
The
least squares method
6.5-2 An overdetermined set
Chapter
Seven
7.1- 1 Breaking strength

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

g s
in
e voltage applied to an
RCcircuit
8.5-3 Liquid height
in
a spherical tank
8.6-1 A nonlinear pendulum model
8.6-2 Trapezoidal profile for a dc motor
Chapter
Nine
9.2-1
9.
2-2
9.
2-3
9.
3-1
9.
4-1
Simulink solution
of
5'
= 10 s
in
1
Exporting to the MATLAB
work~pace
SiJl1ulink model [or y =
-lOy

+
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

Monster
·
EST
(Best
Engineering
Series
and
McGraw-Hili
Continues
to
Brmg
You
the
B
Engineering
Education
Tool
s)
Approach
to
Introductory
;!'~1~~1:/95
ror Scientists and Engineers,
2/e
ISB 0072922389
Donaldson
The Engineering Student Survival Guide.
3/e
ISB 0073019259
EidelJenisonINorthup

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

MATLAB 7 for Engineers
ISBN 0072922427
Pritchard .
Mathcad: A Tool for Engineering Problem SolvlOg
ISBN 0070121893
Schinzinger/Martin
Introduction
to
Engineerin g Et
hi
cs
[SBN 0072339594
Smith
Teamwork and Project Manageme
nt
,
2/e
ISBN 0072922303
TanID' Orazio
C Programming for Engineering and Computer
Science
ISBN 0079
J 36788
Additional
Titles
of
Interest
Andersen
Just Enough Unix.
4/

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.

Palm III
Un
iversity
of
Rhode Island
ffI
Higher
Education
B
oston
Burr Ri
dge
,
IL
Dubuque,
IA
Madison
,
WI
New
Yor
k
San
Francisco
S
t.
Louis
Ba
ngkok
Bogot

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

ec
hanical Engineering a
nd
Applied
Mecha
nic
s
at
the
University of Rhode Isl
and.
In
1966
he
rece
iv
ed a B.S. from
Loyola
CoJIe
ge
in
Baltimore,
and
in
197
I a
Ph
.D.
in
Mechanical

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

19
courses.
On
e
of
the
se is a
fre
hman
MATLAB
course, which
he
helped develop. He
ha
s authored
eight
te
xtbooks d
eaJ
in
g
with
modeling
and
simulation, system dynamic
s,
control
sys
tem
s,

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

and
L.
G.
Kraige
(Wi
ley,
2002).
Professor
Palm
's
research
and
indu
trial
experience are
in
control systems,
robotic
s,
vibrations,
and
sys
tem
modelin
g.
He
was
the Director
of
the Robotics

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

sys
tems
, including underwater vehicles and
tracking systems;
and
design of control systems for underwater-vehicle engine-
test facilitie
s.
CONTENTS
Preface
ix
CHAPTER
1
An Overview
of
MATLAB
1.1
MATLAB Interactive Sessions
1.2 Menus a
nd
the Toolbar
17
1.3 Computing with MATLAB J 9
1.4 Script Files a
nd
the Editor/Debugger 29
1.5 The MATLAB Help System 38
1.6 Programming
in
MATLAB 43

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

141
3.2 User-Defined Functions
148
3.3 Advanced Function Programming
163
3.4 Working with Data Files
172
3.5 Summary 177
Problems J 78
CHAPTER4
Programming
with MATLAB 183
4.1
Program
De
sign and Development
184
4.2
Relational Operators and Logical
Variables
191
4.3
Logical Operators and Functions
194
4.4
Conditional Statements
201
4.5
Loops
210

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

271
5.3
Special Plot
Type!>
282
5.4
Interactive Plotting
in
MATLAB
5.5
Function Discovery
298
5.6
Regression
312
5.7 The Basic Fitting Interface
331
5.8 Three-Dimensional Plots 334
5.9 Summary 339
Problems 340
CHAPTER
6
Linear
Algebraic
Equations
359
6.1
Elementary Solution Method
361
292

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

9.5 Transfer-Func
ti
on Models 557
9.6 Nonlinear State-Variable Models
56
1
9.7 Subsystems 563
9.8 Dead Time
in
Models 568
9.9 Simulation
of
a Vehicle Suspension 571
9.10 Summary 575
Problems 576
71
Sta
ti
tics,
Hi
s
to
grams, and Probability 418 C
HAP
T E R
10
8
7:2 The Normal
Di
stribution 427 Symbolic Processing with MATLAB 5 5

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

Extension
to
Higher-Order Equations
8.7
ODE Solvers in the Control System
Toolbox
518
8.8 Advanced Solver Syntax 527
8.9 Summary
531
Problems 532
CHAPTER9
Simulink
541
9.1 Simulation Diagrams 542
9.2 Introduction
to
Simulink 543
9.3 Linear
State-Variable Models 548
508
10.4
Differential Equations
615
10.5 Laplace Transforms 622
10.6 Symbolic Linear Algebra
631
10.7 Summary 635
Problems 636
APPENDIXA

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

rl
y used mainly by specialists
in
signal processing and numerical
analysis, MA
TL
AB*
in
recent ye
ar
s has achieved widespread and enthus
i-
as
ti
c acceptance throughout the
en
gineering community. Many engineer-
ing schools now re
quir
e a
cour
se based entil'ely
or
in part on MATLAB early
in
th
e curriculum. MA
TLAB
is programmable and
ha

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

sign.
Tbe
popularity
of
MATLAB is partly due to its long history, and thus it
is
well developed and well tested.
People
trust its answers. Its popularity is also
due
to its us
er
interface, wbich provides an
ea
sy-to-use interactive
environment
that includes extensive numerical computation and visualization capabilities. Its
compactness is a big advantage.
For
example
, you can solve a
set
of
many linear
algebraic equations with
ju
st three lines
of
code, a feat that
is

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

is
intended as a stand-alone introduction to MATLAB. It can be used in
an introductory course, as a self-study text,
or
as a supplementary text.
The
text's
material
is
based on the author's experience in teaching a required two-credit
semester
course
devoted to MATLAB for engineering freshmen. In addition,
the text can serve a a reference for later use.
The
text's
many
tables, and its
referencing system in an appendix and
at
the
end
of
each chapter. bave been
designed witb this purpose in mind.
A secondary objective
is
to introduce and reinforce the use
of
problem-solving

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

ledge
of
calc
ul
us is not req uired for the
fir
s
~
s
ev
~
n c h
aprer
s
.
_
~om
e
.
~n
o.w
l
e
d
ge
of
high school che
mi
stry and physics, primanly simple el
e.

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

to
prov.iding new
mate
ri
al based on MATLAB 7,
th
e text
in
corporates
th
e many suggestIons made
by reviewer a
nd
o
th
er users.
'.
.
The t
ex
t consists of 10 chapters. The
fi
rst chapter gIves an. ovel
V
I
~W
of
MATLAB features, including
it
windows a

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

es
~
ow
to use numeric arrays, cell arrays, a
nd
structure
mTa
Ys
fo
r basIc mathema
tI
cal
operations. .
Chapter 3 discusses the use
of
functions a
nd
fil
es.
MAT~AB
has an
e.x
tens
lV
e
number
of
built-
in
math

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.

Chapter 5 treats two- and
th
ree-dimensional
pl
ott
in
g. It
fi
rst estab
li
shes sta
n-
dards for profession
al
-l
ook
in
g,
usef
ul
pl
ots. In
th
e author's experien
ce
begin n
in
g
students are not aware
of

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

di
scover
a ma
th
ema
ti
cal descri
pti
on
of
th
e data, is a common app
li
cation
of
pl
ot
ting, and
a separate section is devoted
to
thi
s topi
c.
The chapter also treats polyno
mi
al and
multiple linear regre sion
as
part
of

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

iew has proved he
lp
f
ul
to many stude
nt
s
in
th
e auth
or
's
classes. T
hi
s
coverage also esta
bli
shes
th
e terminology a
nd
some important con
ce
pts that are
required to use
th
e compu ter me
th
ods prope
rl

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

iews b
as
ic sta
ti
s
ti
cs a
nd
probability a
nd
shows how to use
MA
TL
AB to generate
hi
stograms, perfo
rm
ca
lc
ul
ations with
th
e norm al distribu-
ti
on, and create ra
nd
om number
si
mula
ti

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

.
Pr
eface
and cubic-spline int
er
polation.
Thi
s chapter
ca
n
be
skipped if necessary. None
of
the fo
Jl
owing chapters depend on it.
Chapt
er
8
cove
rs numeri
ca
l methods for calculus and di fferential equa
ti
ons.
Analytical me
th
ods are reviewed to provide a fo undation
for
understanding and

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

ca
l inter
face
for
building
simulations
of
dynamic
systems. The coverage
of
Simulink has b
ee
n expanded
to a separate chapter in light
of
its growing populari ty, as eviden
ce
d by
rece
nt
workshops held by various professional organizations such as the
ASEE.
Th
is
chapter need n
ot
be covered to r
ea
d Cha
pt

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

ti
on, optimization, Taylor se
ri
es,
se
ries
eva
luation, and limits.
La
pl
ace
transform methods for solv
in
g differential equations are also introdu
ce
d.
This cha
pt
er
requires the u
se
of
th
e Symbolic Ma
th
toolbox or the Student Edition
of
MAT
LA
B.

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

creating fo
rm
atted outpu
t.
A
pp
endix D
is
a
li
st of r
efe
rences.
App
endix E, which
is ava
il
able on the text's w
eb
s
it
e, conta
in
s some suggestions for
cour
se projects
and is b
ase
d on the author's experience in t
ea

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

or
exa
mpl
e,
Fi
gure 3.
4-2
is the s
econd
fi
gure in
Chapter 3, S
ec
tion 4. This system is designed to help the reader locate these items.
Th
e end-of-cha
pter
problems
ar
e the exception to this numbering system.
They
are
numb
ered 1, 2, 3, and so on to avoid confusion with the in-
ch
a
pter
exercises.
The
fi

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

plotting and model building, linear algebraic e
qu
ations, proba-
bility and statistics, calculus and differential equations,
Simulink
, and symbolic
pro
cess
ing
, respecti
ve
ly.
' Simulink is a registered trademark of The MathWo
rk
s
.ln
c.
xi
xii
Prefac
e
SPECIAL REFERENCE FEATURES
The
te
xt
ha
s
the
following s
pecial

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

s tables summari
ze
the
comm~nds
a
nd
functions a
they
are
introduced.
• At
the
end
of
each
chapter is a guide
to
tables
in
that chapter. These m
as
ter
tab
l
es
will
help
the
reader
find

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

are
introduced.

At
the
end
of each chapter is a
li
st of
the
key
terms introduced
in
tbe
chapte
r,
w
ith
the
page
number referenced.

Key
terms
have
been
placed
in
the
m

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

st of Simulink blocks,
an
d
an
alphabetical
li
st of topics.
PEDAGOGICAL AIDS
The following pedagogical aids
have
be
en included:
• Each chapter
begins
with
an
overview.
• Test Your Understanding
exe
rci
se
appear throughout the chapters near
the
relev
a
nt
te
x
t.
The

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

these exercises
as
they
are
encountered.
• Each chapter ends
with
numerous problem
s,
grouped according
to
the
relevant sect
ion.

Each
chapter contains numerous practical examples. The major examples
are
numbered.

Each
chapter
has
a
ummary
section that reviews the chapter's objectives.
• Answer
to
many
end-oF-chapter problems appear at the end of the text.

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

ru:
e
drav:n
from
a variety of engineering
fields
and
show realistic
~pphcatlOns
01
MATLAB.
A guide
to
these example appears
on
the inside
tront
cover.
Preface
• The fac
in
g page
of
each chapter
co
ntains a photograph of a recent
engineering
ac
hi
eveme

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

s,
and a
di
sc
u
ss
ion
of
how
MATLAB can
be
ap
pli
ed
in
those
di
sc
iplines accompanies each photo.
An
In
structor's Manual is ava
il
a
bl
e
on
lin
e for
in

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

t, PowerPoint slid
es
keyed
to
the text, and suggestions
for
project .
ACKNOWLEDGMENTS
Many individuals are due credit for this text. Working with faculty at the Uni-
versity of Rhode Island
in
developing a
nd
teaching a freshman co
ur
se based
on
MATLAB has grea
tl
y influenced
thj
s text. Email from many
Ll
sers contained use-
ful
suggestions. The following people,
as
we
ll
as several

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

College
The MathWork
s,
Inc. has always been very supportive
of
educational pub-
lishing. I especially want
to
thank Naomi Fernandes
of
The MathWorks, Inc. for
her help. Carli e Paulson, Michaela Graham, Michelle Flomenhoft, and Peggy
Lucas of McGraw-Hill efficiently handled the manuscript
review!>
and guided the
text through production.
My sister
s,
Linda and Chri
s,
and
my
mother Lillian,
ha
ve
alway,- been there,
cheering
my
efforts.
My

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


Remote Exploration
I
t will be many years before humans
ca~1
tra:el
to
o~her
planets. In the mean-
time, unmanned probes have been rapidly
ll1crea
s
ll1
g our knowledge
of
the
universe. Their use
wi
ll
increa
se
in the future as our technology develops to
make them more reliable a
nd
more versatile. Better sensors are expected for imag-
ing and
ot
her data collection. Improved robotic devices will make these probes
more autonomous,
an

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

ages
of
the la
nd
er for damage assessme
nt.
Then
in
ea
rl
y 2004, two im-
pro
ve
d rovers, Spirit and Oppo
rl
uni
ty,
la
nd
ed on opposite s
id
es
of
th
e planet. In
one
of
the ma
jor
di

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

obtain power from solar arrays that generate 140 watts during a four-hour
Wll1dow
each
day.
The so
ph
isticated temperature control system must not
only
protect against nighttime te
mp
eratures
of
-96
°C, but
mu
st also prevent the rover
from overheating.
The robotic arm
ha
s
th~ee
joints ( houlder, elbow, and wrist), driven by five
motor
s,
and
It
ha
s a reach of 90 centimeters. The a
rm
calTies four tools and instru-

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

ss
ing, Image Processing,
PDE
, and
vanous control
s~s
tem.toolboxe
s
a
re
well suited
to
assist designers
of
probes and
autonomous vehIcles
lIke the Mars rovers . •
An
OvervielN
of
MATLAB®*
OUTLINE
1.1 MATLAB Interactive Sessions
1.2
Menu
s and the Toolbar
1.3
Computing
with MATLAB
1.4

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

problems.
Section
1.1 provides a "quick-start" introduction to
MATLAB
as an
interactive calculator. Section 1.2 covers the
main
menus and tool bar. Section 1.3
gives an overview
of
MATLAB, and directs the reader to the appropriate
chapter
where
more detailed information
is
available. Section 1.4 discusses how to create
edit, and save MATLAB programs.
Section
1.5
introduces the extensive
MATLAS
Help
Sy
stem.
Section
1.6 treats the use
of
conditional statements
and
loops.

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

ap
ter
orga
nization is
fl
exib
le enough to accommodate a
va
r!ety of
u
se
r
s.
However,
it
is
imp
Oitant
to
cove
r
at
l
eas~
the.
fir~
t
fo
ur
c

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

apter 3
cove
rs
fil
e usage,
f
un
c
t
io
n
~
butl~
lIl
to
MAT
LAB,
a:~
u
se
l
-
d
~fi
n
~
d
f
un
c

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.
.

Use
S
ec
ti
on 1
.3
to dete
rmin
e
th
ose
MA
TLAB
fea
tur
es
fo
r
w
hl
~ h
yo
u
wa
nt
more deta
il
ed
in
f

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

ind
epe
nd
e
nt
cha
pt
ers
:h
at can be covered
In
an
y or-
der, or
ca
n be o
mitt
ed.
Th
ey
co
nt
a
in
in-d
e
pth
di
sc
u

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

nd
thr
ee
-dim
ens
ion
al plots
in
more
deta
il
, a
nd
shows
ho
w
to
use
pl
ots
to
bUlld
math
ema
tical
mod
els f
rom
dat
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

calcu
lu
s
and
ordinary differential equations. Chapter 9 covers
Simulink®
,*
which
is a graphical user intelface
for
solving differential equation
model
s.
Chapter 10 covers symbolic proce
ss
ing
in
MATLAB
, with app
li
cations
to
al
gebr
a,
ca
lculu
s,
differential equations,
lin

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

terms are
introduced.
• Throughout
eac
h chapter short Test
Your
Understanding exercises appear.
Where
app
ropriate, answers immediately
fo
ll
ow
the exercise
so
you can
measure
yo
ur
mastery of
the
material.
• Homework
exe
rcises
co
nclud
e each cha
pt
er.

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

u
ced
in
that
chapter.

At
the
end
of
each
chapter i
s:
• A
ummary
g
uid
e
to
th
e
co
mmand
s covered
in
th
at
chapter,
• A s
umm

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

up
ed
by category,
W
Ith
th
e a
ppr
oprIa
te
page
refe
rence
s.
· Simulink i, a r
eg
istered
trad
ema
rk
of The MathWorks.
[nc
o
CHAPTER
1 An
Overview
of MATLAB
• Two
in
dexes are

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

th
an book publishe
rs
can
release n
ew
edition
s.
This t
ex
t doc
um
e
nt
s
th
e pre-release vers
ion
of
MATLAB 7
as
of
th
e spring of 200
4.
Th
ere
will
be additional updates, numbered
7.1

, 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

nd
to lea
rn
how
to
use the ext
en
s
ive
MATLAB Help
S
ys
tem, w
hi
ch is covered
in
Section 1.5.
MATLAB
and
Related Software
MATLAB is both a computer programming
lan
guage and a oftware environment
for using that l
an
g
ua
ge effectively. It is maintained and so
ld
by

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-

ve
lop and manage files
for
use with MATLAB. The language was originally
developed
in
the 1970s for applications involving matrice , linear algebra, and
numerical analysis (the name MATLAB stands for
"Matrix Laboratory'·
).
Thus
the language's nLllnerical routines have been well-tested and improved through
many years
of
use, and i
ts
capabiJities have been grea
tl
y expanded.
MATLAB h
as
a number of add-on sof
tw
are modules, called toolboxes, that
perform more specia
li
zed computa
ti
ons. They can
be

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

to
olbo
x.
in
Chapter 8,
and the Symbolic Math toolbox,
in
Chapter 10), and from SimuJink (in Chapter 9).
All of the examples and problems
in
the first seven chapters can be done with the
core MATLAB program.
On
MS Windows systems MATLAB 7 requires Windows XP or Windows NT
to
run. The Student Edition
of
MATLAB contains the core MATLAB program.
some co
mm
ands from two toolboxes (the Signal Processing toolb
ox
and the
Symbolic Math
to
olbox), a
nd
the Simulink program. The Simulink program
is
based

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.

DESKTOP
CHAPTER
1
An
Ove
rview of M
ATLAB
1.1 MATLAB Interactive Sessions
We
now
show h
ow
to
st
ar
t
MATLAB
, h
ow
to
make
some basic calculations, and
h
ow
to
exit
MATLAB
.
Conventions
In

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

pp
eal o
n.
the screen. for
exa
mpl
e,
y = 6 *x. Variable
in
normal mathema
tI
cs
t~xt
a
p~
ea
I
in
ita
l
ics;
for
exa
mpl
e,
y =
6,1.
We u e
b
o

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

ee
n
menu
or
an
it
em that appears
in
uch a me
nu
(fo
r example, File
).
It
is assumed that
yo
u
pre
ss
th
e Enter
key
after
yo
u
typ
e a co
mm
and. We do not
s

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

ee
th
e
MATLAB
D
esklO
p.
The Desktop manages the Command
w
ind
ow
a
nd
a He
lp
Browser,
as
we
ll
as
other tools. The default appearance
of
th
e De ktop i s
hown
in
Figure l.J -
1.
Three windows a
pp

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

Je
ytern
Jh
elp
J
ja
File
Type
Folder
Folder
Folder
Folder
Folder
'"r.
Dorectory
WOI~spece
x •
(O:0.02:
6
J;
V •
St'!Hn(x);
» x -
(0:
0 .
02
: 8J ;
!
» y .
S'einlxl;

»
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

ll
ed
the too/bar.
To
thc right
of
the tool bar is a box showing
th
e directory
where MATLAB looks for and saves files.
We
will describe the me
nu
s,
too
lb
ar,
and directories later
in
thi
s chapter.
You
usc the Command window
to
communicate with
th
e MATLAB rro-
gram,
by
typing

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

ll
th
e
in
structions
by
th
e generic name
comll1ands. MATLAB
di
splays
th
e prompt (» )
to
indicate that
it
is ready to
re
- C
OMMAND
ceive
in
s
tru
ctions. Before giving MATLAB
in
struction
s,
make ure
th

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

th
e normal prompt
symbol »
to
illustrate co
mm
a
nd
s
in
thi
s text.
Three other windows appear
in
th
e default
De
sktop. The Curren t Direl:tory
window
is
Illuch
li
ke
a
fil
e manager
wi
nd
ow; you can use
it

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

in
Section J.4.
U
nd
ernea
th
th
e Curre
nt
Directory wi
nd
ow
i
~
th
e Workspace w
ind
ow.
To
acti
va
te
it
, c
li
ck on its tab at the bottom o
f"
th
e Curre
nt

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

kLop
is
th
e Command
Hi
story window .
T
hi
s
wi
nd
ow shows a
ll
the previous keystrokes you e
nt
ered
in
the Command
wi
nd
ow.
Jt
i use
ful
for keeping track
of
what you typed.
You
can click on a
keystroke a

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

ow.
just c
li
ck on
it
s Close-window button
(x)
in
it
s upper
ri
g
ht
-
hand co
rn
er.
To
undock, or separate the window from the Desktop, click on
th
e
button containing an arrow.
You
can manipulate other
window~
in the
'>arne
way.
To
restore

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

) to scro
ll
back
through
th
e co
mm
a
nd
s.
Press
th
e
key
once
to
see
th
e previous e
nt
ry,
twice to
see
th
e entry before that , a
nd
so on. Usc the down-arrow key ( ) to croll forward
through the command . When you
find
th

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

ut
e the command. This technique enables
Delete
key.
Press the Enter
ey
t~
ex
yo
u
to
correct typing
mi
takes
~ul
~k
l
'y'
keystrokes displayed
in
the
Comma
nd
ote that you can see
YO
Ul
~~
e~~~~l
this window
to

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

ow.
. ' .
"'Make s
ur
e the c
ur
sor is at the prompt
in
the Comma
nd
w
md
ow. To dIvide
8 b
10
type
8/10
a
nd
press Enter (
th
e symbol / is the MATLAB
s~
mbol
for
di
vfs
iOI;
).
Your entry a

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

splays its results using four decimal
pl
aces. T
hi
s is called
t
h ~
s
/
~ort.
format.
This default can be changed by using the
forma
t command, whlch IS
dl
s
c:ls~ed
later
in
this section . MATLAB uses the notation e
to
represent
expone
ntl
a~lOn
to
a power
of
10
; for example, MATLAB displays

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

si
ng
the MATLAB
sy
mbol for multiplication
(*):
» 5*
ans
ans
=
Note that the
va
ri
ab
le
ans
now h
as
th
e
va
lu
e
4.
You
can use
va
ria
bl
es

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

s:
»
r=8/10
0 .
8000
Spaces
in
the line improve
it
s readability; for example, you can put a space before
and after the
= sign if you want. MATLAB ignores these spaces when
making
its calculations.
If
you now type r at
th
e prompt, you will see
0 .
8000
1.1
MATLAB Interactive Sessions
thus verifying that the variable r has the va
lu
e 0
.8
. You can u
se
thj s variable
in

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.
A pair
of
parentheses is u
se
d
af
t
er
th
e function's n
ame
to
enclose the valu
e-ca
ll
ed
the func
ti
on's
argument-
th at is operated on by the ARGUMENT
function.
For
example,
to
comp
ute the square root
of
9, you type

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,


multiplication, division, and exponentiation (power)
of
sca
lar
s.
The
se are
li
sted in
Table
1
.1-
].
For
example, typing x = 8 + 3 * 5 returns the
answer
x =
23.
Typing 2 A 3
-1
0 returns the
answer
ans
= -
2.
The
fan-liard slash
(!)
repre-

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

remember
the
difference between the right and left division operators is to note that the slash
slants toward the denominator.
For
example, 7
/2
= 2 \ 7 = 3.5.
The
ma
thematical operations represented by the symbols + - * / \, and
A follow a set
of
rules called
pr
ecedence. Mathematical expressions are evaluated PRECEDENCE
starting from the left, with the exponentiation operation having the
highe
st
order
of
precedence, followed by multiplication and division with equal precedence,
followed by addition and subtraction with equal precedence. Parenthes
es
can be
Table
1.1-1 S
ca
lar
ar

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

e
1.1
2
Ord
er of
pr
ecedence
Precedence
Fir
t
Sec
ond
Th
ird
Fo
u
rt
h
Operation
Parentheses,
eva
lu
ated sta
rt
ing w
ith
th
e inne
rm
ost pa

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

ecedence,
eva
l
ua
t
ed
from left
to
ri
g
ht.
Addit
i
on
and
subtrac
ti
on
with
equal
pr
ecedenc
e,
evaluated
fro
m le
ft
to
ri
gh

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

rul
es. For example, note
th
e effect
of
precedence on the foll
ow
1l1
g session.
» 8 + 3 *5
ans
=
23
» 8
+
(3*5)
23
»(8
+
3)
*5
55
»4A2-12-
8/4
*2
ans
=
»4A2
-
12

-
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

11
To avoid mistakes. you should
feel
free
to
insert parentheses wherever you are
unsure
of
the effect precedence will have on the calculation. Use
of
parentheses
1.1
MATLAS inter
ac
tive Sessions
also improves the readab
il
ity
of
your MAT
LA
B ex
pr
essions. For example, paren-
th
eses
ar
e n
ot
n

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

+
5(
9
2
)
b.
6(35
1
/
4
)
+ 14
03 5
(A
nswer
s:a.
410
.
12
97 b.
17
.1123.)
The Assignment
Operator
Th
e = sign in MATLAB is the called
th
e assig
nm
ent

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

of
x with this new value.
If
x originally
had the value 3, its new value would be 5. This usage
of
the = operator is different
from its use in
mathematic
s.
For
example, the mathematics equation x = x + 2 is
invalid because it implies that
0 = 2 (subtract x from both sides
of
the equation
to see this).
It is important to understand this difference between the
MATLAB
opera-
tor
= and the equals sign
of
mathematics.
The
variable on the lefi-hand
side
of
the = operator is replaced by the value generated by the right-
hand

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

(these
commands
are available in the
Symbolic
Math toolbox, which
is
described in
Chapter
10).
Another
restriction is that the right-hand side
of
the = operator must have a
computable
value.
For
example,
if
the variable y has not been a signed a value.
then the following will generate an
error
message in MATLAB.
» x = 5 + Y
In addition to assigning known values to variables. the
assignment
operator
is
very useful
[or
assigning values that are not known ahead

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

.'
. d . f h
eio
ht
h and ra
diu
s r is gi
ven
by V
nr
2
h . A
The
vo
lum
e at a
.c
lr
c
ul
ar
cy
lin
ell
~a
ll
a1~d
h
as
a ra

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

H
ow
large mu t
it
s
rad
iu
s
be?

Solution
. .
First sol
ve
th
e
cy
lind
er e
qu
a
ti
on
fo
r
th
e ra
diu
s
/'

. 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

heig
ht.
Th
en
we
co
mpute
th
e volume of
t
l
~
e
o
ri
g
in
al cylind
e.r,
a
nd
In
crease
th
e
vo
lum
e by 20 perce
nt.
Fin

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
=

pi*r
A
2*h
;
»V
= V + O.
2*V
;
=
sqrt
(VI
(pi*h))
ans
=
r = 8 .
7636
Thus
th
e
new
cylinder
mu
st
have
a ra
diu
s of 8
.76
36 m. Note that the original va
lu

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

th
e orig
in
al va
lu
es ag
ain
.
No
te h
ow
pr
ecedence app
li
es
to th
e line V
pi
*r
A2
*h
;.
It
is e
qu
i
va
le
nt
to

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

in
with a letter and must contain less
than 32 characters; the rest
of
th
e name can co
nt
a
in
letters, digits, and underscore
characters. MATLAB is case-sensiti
ve
. Thus
th
e following names repre
se
nt five
different variables:
speed
.
Speed
. SPEED,
Speed
_ I , and
Speed
_ 2 .
Managing the Work Session
Table
1.1
-3

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

comm
a-if
you wa
nt
to
see the results
of
the previous
command-or
semicolon
1.1
MATLAB
I
nt
eractive Sessions
Table
1.1
-3
Commands
fo
r man
ag
in
g
th
e
wo
rk
ses ion
Command

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

fro
m memor
y.
Rem
oves
th
e
va
ri
a
bl
es
varl
a
nd
var2
fr
om memor
y.
Determ
in
es
if a
fil
e or
va
ri
a
bl
e

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

ri
a
bl
es
a
nd
sizes, a
nd
i
ndi
cates
if'
th
ey
have
im
ag
in
ary
pa
rt
s.
Co
lon;
ge
nerates an an
'ay
h
avi
ng r

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

an
arr
ay.
Ellipsi
s;
continues a l
in
e.
if
you want to suppress the
di
spJay.
For
example,
»x=2
;
y=6+x
,
x=y+7
y
15
Note
that the first value
of
x was not
di
splayed. Note also that the
va
lu
c

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
=

47
Use
th
e arrow, tab, and control keys to reca
ll
, edit, and r
euse
functions and
va
ri
abl
es
you typed
ear
lier.
For
example, suppo
se
you mi st
ake
nly
enter
the line
»volume
= 1 +
sqr(5)
MATLAB responds with the error message
Undefined
function
or

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

the up-arrow key recalls lines typed
ea
rlier.
13
14
C H
AP
TER
1
An
Overview
of
MATLAB
. . II
fea
tur
e
to
r
eca
ll
a
pr
eviously typed function
You
ca
n u e
th
e S/1'lW r !
eca

'
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

lin
e tart
in
g
wi
th
vO
.
lum
h
e
.t
y
pl~
sg
: ith
t
~
e
f
un
ct
ion
"'or
va
riable whose
(t)
on
ce reca
ll

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

tu
re
to re
du
ce
th
e amo
un
t of typin
g.
You
ca
n u
se
th
e r
ab
com
l~
~
1I
0
!
~
h
e
~
a
m
e

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

key
.
If
th
e
n
a
m
~
is
yo
u
t
y
p
~
t
~
l
e
fil
t
f
~~
le
lt
els
~l
leted
For

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

di
splays
if
y
o~
type
FrUl
t a
npd
pr
es
Es t
a
~o
di
s
pl
ay
th
e
va
lue of
th
e varia
bl
e, or continue
Frultpurchased
. r
ess
n er

.'
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

name
that sta
rt
s wi
th th
e
l
e
tt
~
r s
y
ou
t
y p ~
,
MATLAB
di
spl
ay
s
not
hin
g.
In
this
cas
e
pr
ess

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

~~
w
n
tlrou
",
the p
re
v
io
usly
typ
ed lines
one
l
in
e
at
a time.
SIITIl
I
~rly
,
the left-allow (
~).
a
nd
rig
ht
ar
row

(~)
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

ss
Ctrl and
~
S
ll1
lult
a.
neously
to
mo
ve
to
the rig
hr
;
pres
s Ctrl and
~
s
imu
lt
an
eo
usly
to
move to the left.
P
r
~s
s

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

ss
Backspace
to
delete the
char
ac
ter before t
he
c
ur
s
or.
Pr
e
ss
Esc
to
clear
th
e entire
lin
e; press C
trl
and k
imul
ta
n
eo
usly
to

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

lu
e. O
ver
l
ook
in
g t
hi
s
fact
co
mm
o
nl
y
ca
us
es
e
rr
ors
in
MATLAR. For exam-
pl
e,
yo
u
mi
g
ht

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

val
ue
for
x,
MA
TLAB us
es
th
e l
as
t
va
lu
e, a
nd
yo
u
ge
t an
in
co
rr
ect r
es
ult.
You
ca
n u
se
th

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

rm
clear
varl
var2
to
cl
ear
th
e
var
ia
bl
es
named
varl
a
nd
var2
.
Th
e effect of
th
e
clc
co
mm
a
nd
is
di

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

es
of
th
e
va
ri
a
bl
es rema
in
.
You can
ty
pe
th
e name of a
varia
bl
e a
nd
pr
ess
Enter
to
see
it
s current
va
lu
e.

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

use
th
e
exist
function . Type
exist
('x')
to see if
th
e
va
ri
a
bl
e x is
in
u
se
.
If
a I is re
turn
ed,
th
e va
ri
a
bl
e
ex

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

not
gi
ve
th
e
ir
va
lu
es.
Th
e fo
rm
who
varl
var2
restricts
the
di
s
pl
ay
to
th
e
va
ri
a
bl
es
sp

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

ce,
who A *
find
s a
ll
variabl es
in
th
e c
urr
e
nt
w
ork
space
th
at sta
rt
w
ith
A
Th
e
whos
fun
ction
li
sts
th
e variable

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 1.1
-4
Specia
l
va
r
ia
bl
es
a
nd
co
nsta
nt
s
C
ommand
De
scr
ip
ti
on
Te
mp
or
ary
va
r
ia
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

in
t
pr
ec
i ion.
i
,j
The i
lll
agi
nary
unit
R.
I
nf
In
fi
nit
y.
Na
N Indi
ca
t
es
an
und
e
fin
ed
num

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

in
parentheses. Co
mm
a
nd
s, such as
clear
,
need not h
av
e argume
nt
s,
but if they do, th
ey
are not enclosed
in
parenthese
s;
fo
r
exam
pl
e,
clear
x. Stateme
nt
s cannot have arguments;
fo
r example,

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

nu
, a
nd
th
en
cl
ick on Ex
it
MA
TL
AB.
Predefined Constants
MATLAB h
as
several prede
fin
ed special constants, such as
th
e built-in consta
nt
pi
we used in Exa
mpl
e 1,1- ] , Ta
bl
e
Ll
-4
li
sts

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

r
Inf.
Th
e symbol NaN sta
nd
s for
"not a numbe
r.
" It indicat
es
an unde
fin
ed
num
e
ri
cal re
ul
t s
uch
as
th
at obtained
by typing
0/0
, The symbol
eps
is
th
e sma

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

s,
such a x = 5 +
8i
.
Try not to use
th
e names
of
s
pe
cial constants
as
va
ri
able names. Although
MATLAB allows you
to
assign a differe
nt
va
lu
e
to
these constants,
it
is not good
pr
ac
ti
ce to do

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

numb
er.
alth
ough
it
is required w
ith
a v
ariabl
e,
s
uch
as
c2 = 5 - i *
cl.
Thi
s
convention
c
an
ca
us
e
e
rr
ors if
yo
u
ar
e not

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

/
2)
i = 3.
5i
a
nd
x = 7/ (2i) =
-3
.5i.
15
16
CHAPTER
1
An
Overview
of
MA
TL
AB
Addition, subtraction, multiplication, and divi sion
of
complex numbers are
eas
il
y don
e.
For example,
»w+s
ans
=

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

nary parts
of
opposite sign;
for example,
-3
+ 7i a
nd
-3
- 7i are complex
co.
nJu
g~
t
es
.
The
product
of
two
conju gates is the sum
of
the squares
of
th
e real and
IIn
aglI1ary part
s;
for
exa

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,

use MATLAB to show that
x + y = I + 7
i,
xy =
-12
+ 64i, and x / y =
-1.2
+ 1.1i.
-

-

Formatting
Commands
The
format
command controls
how
numbers appear on the screen. Table 1.1-S
gives the
va
riants
of
thi
s command. MATLAB uses many significant figures in
it
s
Table
1.1-5
Numeric

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

digits:
17
.27484029463547.
Five digits (four decimals)
pillS exponent; 6.3
792e+03.
16
digits (15 decimals) plu exponent;
6.37924378478 I
294e-04.
Two
decimal digits; 126.73.
Po itive. nega
li
ve
. or zero:
+.
R
at
ional approximation;
4317.
Suppresses some line
fe
eds.
Resets
to
less compact
di
splay mode.
1.2

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

e default
mode, type
format
short
.
You
can force the output to be in scientifi c notation by typing
format
short
e,
or
forma
t
long
e,
where e stands for the
number
10. Thus
the
output
6 .
3792e+03
stands for the number 6.3792 x
10
3
.
The
output
6 .
3792e-03

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

n-
ventional
co
mput
er programming standards
th
at were estab
li
shed many years ago.
Use
format
bank
only for moneta
ry
calc
ul
ation ; it does not recognize
imaginary part
s.
1.2 Menus
and
the Toolbar
The
De
sktop manages the
Comm
and window and oth
er
MATLAB tools.
The

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

menu names, and a row
of
icons
ca
lled
th
e too
/b
ar
. To the right
of
th
e tool
bar
is a box howing
th
e current director
y,
CURRENT
where
MATLAB
look
s for files. We now describe the menus and the toolbar. DIRECTORY
Other
windows app
ear
in
a MATLAB ses ion, depending on what you do.
For
example, a graphics window containing a plot appears when you u

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,

depending on which features you are curren
tl
y using.
The
Desktop
Menus
Most
of
your
interaction will be in the
Comm
and window. When the
Command
window is active,
th
e default MATLAB 7
De
sktop (shown in
Figure
1.1-1) has
ix
menu
;
File,
Edit,
Debug,
Desktop,
Window,
and
Help.

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 (


) open a submenu
or
another window containing a dialog box.
The
three most useful menus are the
File,
Edit,
and
Help
menus.
The
Help
menu
is described in Section I.S.
The
File
menu in MATLAB 7 contains the
following items, which perform the indicated action when you select them.
17
18
CHAPTER
1
An
Overview
of
MATLAB
The
File
Menu
in MATLAB 7

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).
.'
.

Open

Opens a dialog box that allo
ws
you
to
s
ele~t
a
fil
e tor ed
ItIn
g.
Close
Command
Window Closes the Command
WIndow
. .
Import
Data
Starts the lmport Wizard w
hi
ch enables you to Import data
easily.
Save Workspace As

Opens a dialog box that enables you save a file.
Set
Path.


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

the Corrunand
wi
nd
ow.
Print
Selection
Opens a dialog
bo
x that enables you to print selected
pOltions
of
the Command window.
File
List
Co
nt
ai
ns a
li
st
of
previously used
file
s,
in
o
rd
er
of
most r

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

s Undo operation.
Cut
Removes
th
e
se
lected text a
nd
stores
it
for pasting later.
Copy
Copies
th
e selected text
fo
r pasting later, without removing it.
Paste
lnserts a
ny
text on the clipboard at
th
e current location
of
the cursor.
Paste
Special
In erts the co
nt
e

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

e
hi
g
hli
g
ht
ed
in
the Workspace Browser.
Find
Finds a
nd
replace ' phrases.
Find
F
iles
Finds
file
.
Clear
Command
Window Removes a
ll
te
xt from the
Command
window.
Clear
Command
History Removes all text from

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

1.3
Computing with MATLAB
key to s
cr
o
ll
through the previous
commands
, and press
Enter
when you see
th
e
c
omm
and you want
to
retrieve.
U
se
th
e
Debug
menu to access the Debu
gger
, which is discussed
in
Chapt
er
4.

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.

Click on
th
e name
of
a window that appears on
th
e menu to open it.
For
example,
if
you have cr
eate
d a plot and not closed its
window, the plot window wi
ll
appear on this menu as
Figu
re
1.
Ho
wever, there
are
otber
ways
to
move between windows (such as pressing the Alt and
Tab
keys
simultaneously).
The

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

Redo.
The
eighth button acti-
vates
Simulink
.
The
ninth button activates the
GUIDE
Quick
Start, wh ich is used
to create and edit graphical user interfaces (GUIs).
The
tenth button (the
one
with
the question mark) accesses the Help System.
1.3
Computing
with MATLAB
This
se
ction provides an overview
of
the computational capabilities
of
MATLAB,
and points out
where
in the b

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

co
mpute s
in
x,
where x has a value
in
radians, you type s i n
(x)
.
To compute cos
x,
type
cos
(x)
.
The
exponential function
eX
is
computed
from
e
xp
(x
).
The
natural logarithm,
In
x,
is computed by typing

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

in
radians, not
degrees.
One
of
th
e stren
gt
hs
of
MATLAB is its ability to handle collections
of
num-
bers.
ca
ll
ed
arrays, as if they were a single variable. A nume
ri
cal array
i~
an
orde
red
co
ll
ec
tion
of
numb

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]
.

Th
e elements
of
the
ar
ray must
be sepa
rat
ed
by
commas
or
s
pac
es. Note that the variable '.I defined as
'.I
=
[ 6 , 3 ,
1,
0]
is not the
sa
me
as x because the
order
is different.
We
ca
n add the two arrays x a
nd

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

e.
numbers
numb
ers
in
x a
nd
y to
pLOduc
'.
I
aoes
thi
s operati
on
reqUir
es more
6
4, 4.
6.
In
mo
st
oLher
pr
og
ral
.
ll1~:ln
g

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.

Th
lbe
;'
s
in
th
e array if
th
ey
are reg
ul
arl'y
s
l
~aced.
You
need
not ty
pe
a
ll
th
e
nun.
d
th
e
la
st
numb

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,

. ,

10
can be
middl
e,
se
parated
by
co
l
ons.
or
~:::p
='
[0 : 0 .1 :
10]
.
assigned
to th
e vanable u.
by
typ
0_
0
0
1
0.
2,

,
10

, 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

rmul
a w = 5 s
in
u
101
tllnes,
The s
lll
gie
11Il
e,
w
~
5
Sl.~
u,
.
Pduce
an
ar
r
ay
z that h
as
101
va
lu
es. This
once for
eac

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

s.
I"
. I b e session
Becau
se
you
typed
a
se
micolon
at
the
e
nd
of each
lIle
111
t le a
ov
.'.
'
MATLAB
doe
s
not
display
the
resu
lt
s

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

b~
t~plll
g
u
after
th
e prompt
or
for
example,
yo
u
ca
n see
the
seve
nth
va
lu
e
by
tYpll1
0
~
(7)
.
You
can see
the
w

~~
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

»w(7)
ans
=
2 . 8232
You
can
u
se
th
e
length
function
to determine
how
many
va
lu
es are
in
an
a
rr
ay.
For
exa
mpl
e,
co
ntinue
the

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

co
lumn
are
called
row
arrays. You
can
create co
lu
mn
arrays, which have
more
than
o
ne
row,
by
u
si
ng a
se
mi
co
l
on
to
separate the rows.
Polynomial Roots
We
can

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,

the
p
oly
no
mi
aI4x
'-
8x
2
+ 7x - 5
would
be
re
pr
e e
nt
ed
by
the array
[4 ,
- 8 , 7 , - 5) .
The
/"Oats
of
th
e
pol
y
nomi
al

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

nt
a
in
s
th
e polynomial's roots. For exa
mpl
e,
to
find
th
e roots of x
3
- 7x
2
+4
0x - 34 = 0,
the sess ion
is
» a = [1 ,
-7
, 40 ,
-34];
»
roots(a)
3 .
0000
+ 5 .
000i
3 .

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

er
th
an polynomials can be obtained with
th
e f
zero
function, covered
in
Chapter
3.
Usef
ul
app
li
cations of a
rr
ays are
di
sc
ussed
in
more detail
in
Chapter
2.
1i
st
Your
Understanding
T1

.
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

+x
3
.
(A
nswer: x = -
10
,2
± 5i.)
Built-in and User-Defined Functions (Chapter 3)
We
have seen several
of
the functions built
in
to
MATLAB. such
a~
the
sqrt
and the
sin
functions. Table 1
.3-
1
li
sts some of
th
e
co
mmonly u

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

x
COS- I x
si
n I x
tan- I x
MATLAB
syntax 1
exp(x)
sqrt
(x)
log
(x)
10g10
(x)
cos
(x)
sin
(x)
lan(x)
acos
(X)
asin
(x)
alan
(x)
IThe
MATLAB
trig.onom
c
lrk

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

al
needs. Cre-
ation
of
user-d
efi
ned functions
is
covered
111
Chaptel 3.
Working
with
Files
, . I t es
of
fil
es that ena
bl
e you to save programs, data,
MATLAB uses se\ ela yp . . S .
14
MATLAB fun
ct
ion files and
a
nd
session
re
sult

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

variables created during a MATLAB
seSS
IOn.
.
ASC
II
fi
les are
file
s written
in
a specific form.at .deslgned
to
make
t~~m
usable
to
a wide variety
of
software. The ASCII
ab
breviation stands for
Amell
~a
n
S.tan-
dard Code for Information Interc
han
ge. M-files a
re

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

ll
word process1l1g
pIO
gram~
ca
n
recoa
ni
ze and creat
e.
M-files are machine independent. MAT-fi les
are
hl.nary
fil
es~
nol
ASCII
files.
Binary files are generally readable only by the
sof
tware that
created them, so you cannot read a MAT-file with a word processor. In
g~nera
l
,
transferring binary
file
s between machine types
(M~
Window~

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

da
ta
file, that i
s,
one created according
to
the ASCII fOima
t.
You
may
need
to
u
se
MATLAB
to
analyze data stored
in
such a file created by a spreads
he
et pro
gra
m ,
a word processor, or a laboratory data acquisition system or
in
a file you share
with omeone els
e.
Saving
and

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,

in a binary
file
ca
ll
ed
matlab
.
mat
. which MATLAB can read. To retrieve
your
workspace
va
riables, type
load
.
You
can then continue your session as before.
Of
course,
if
you
ex
ited MATLAB after using the
save
command
, you
cannot
recover your
key
trokes or the MATLAB

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

.
If
the saved MAT-file
filename
con-
tains the variables A. E, a
nd
C,
then loading the file f i 1
ename
places the
se
variable back into the workspace. If the variables already exist
in
the
work
s
pace
,
they are overwrillen with the values
of
the variables from the file
filename.
To
load
th
e workspace variables, the filename
mu
st have the extension .
ma

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

.
mat
, type
save
filename
var1
var2
. You n
ee
d not type
the variable names to retrieve them;
ju
st type
load
filename.
You can save the variables
in
ASCII s
in
gle-precision (eight
di
gits) format
by typing
save
filename
-ASCII.
To save the varia
bl
es in
ASCn

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

.
ASC
II
fi
les
co
ntain
in
g
double
-pr
ec
ision data use
th
e D format;
for
exa
mpLe
, 1 .
249D+002
. As an alternative
to th
e
save
fun c
ti
on, you can
sel
ec
t

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

se
you use MATLAB on your
home
comp
ut
er
and save a
fil
e to a removable
disk, as discussed later
in
this section.
If
you bring that di
sk
to use with MATLAB
on
another
comp
ut
er
, say,
in
a sch
ool's
computer
lab, you must make sure
th
at
MATLAB knows how

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

ry
c : \
matlab.
Then the
toolbox
directory is a subdirectory under the directory
c :
\m
atlab,
and
symbolic
is a subdirectory under the
toolbox
directory.
The
path
tells us and MATLAB how to find a palticular file.
For
example, the PATH
file
sol
ve
. m is a
fu
nc
ti
on
in
the
Symbolic

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
.

m.
Working
with
Removable
Disks
In Section
LA
you will l
ear
n how to create
a
nd
save M-files. Suppose you have saved
th
e file
problem1
. m
in
the directory
\
homework
on a disk, which you insert
in
drive
a:
.
The
p
at
h

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

it is.
3.
If
not, MATLAB then looks in the current directory
for
a file named
probleml
. m and executes
problem1
if
it finds it.
4.
If
not, MATLAB then sea
rche
the directories in its search path, in order.
for
probleml
. m and then executes it
if
found.
You can display the MATLAB search path by typing
path
.
If
probleml
i
on
the disk only and
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

of
MATLAB
Table 1.3-2 Sy tem. dir
ec
tory. a
nd
fil
e
co
mm
a
nd
s
Command
addpath
dirname
cd
dirname
dir
dir
dirname
path
pathtool
pwd
rmpath
dirname
what
what
dirname
Description

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

director
y.
Li
sts a
ll
th
e
fil
es
in
th
e directory
dirname.
Di
s
pl
ays
th
e
MATLAB
search pa
th.
Starts
th
e Set Pa
th
t
oo
i.
Di

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

ic
file
s fo
und
in
th
e curre
nt
wo
rkin
g dir
ec
tor
y.
M
os
t data
fil
es a
nd
other non-MATLAB
fil
es
ar
e
not
li
s
ted
. U e

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

dire
c
tor
y
to
find
yo
ur
file
. The general sy
nt
ax
of
thi
s
co
mm
a
nd
is
cd
dirname,
where
dirname
is
th
e f
ull
path
to th

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

on
, and
type
cd
a : .
An
alte
rn
at
i
ve
to
thi
s
proc
ed
ur
e is to
copy
your
fi
le
to
a directory on the
h
ard
dri
ve
that i
in

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

rget
to
copy
the
r
ev
i
sed
fi
le b
ack
to
your
di
sk;
(2)
th
e ha
rd
drive becomes cluttered (th
is
is a
probl
em
in
public computer lab
s,
a
nd
you

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

ne el
se
can
access your
work!
You
ca
n determine
the
current directory (
th
e one whe
re
MATLAB looks
fo
r
yo
ur
file
)
by
typi
ng
pWd
.
To
see a list of a
ll
th
e

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

what
command
di
s
play
s a
li
st of
th
e MATLAB-specific files
in
the
c
urr
e
nt
directory.
The
what
di
rname
comma
nd
does the same for
th
e directory
di
rname
.
You

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

the
se
arch
path
, u
se
th
e
rmpath
command. The
Set
Path
tool
is a g
raphical
intetfa
ce
for
worki
ng w
ith
files
a
nd
directorie
s.
Type
path
tool
to

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

s
umm
a
ri
ze
d
in
Table
1
.3-
2.
Decision-Making Programs in MATLAB (Chapter 4)
The .u
se
fulne. s
Of.
~ATLA
B
greatly
in
creases w
ith
it
s ability
to
use decision-
m
ak
JDg
fu

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

a.l
so
can
u
se
.
Ioop
s to perfo
rm
calculations repeatedly, a specified
number of tllnes.
or
untIl
Some
condition
is
satisfied. This allows us
to
solve
problems of great
co
mpl
ex
it
y or
problem
s requiring
num
erous calculation
s.

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

lin
ear, logari
thmi
c,
surface, a
nd
co
nt
o
ur
plots. As a
simple exa
mp
le, let us plot the f
un
ction y = sin
2x
for 0
.::::
x
.::::
10
.
We
choose
to use an increme
nt
of
0.01
to

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

e vertical axis
(
th
e ordinate). The se
ss
ion
i
s:
»x
= [0 : 0 . 02 : 8] ;
»y
=
5*sin(x)
;
»plot
(x
,
y)
,
xlabel
( ' x ' ) ,
ylabel
( ' y ' )
The
plot
ap
pears
on
the sc
re

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

s
in
gle quotes
as
WINDOW
a label on
th
e horizon
ta
l
ax
i
s.
The
ylabel
f
un
ction performs a similar
fu
nction
Figure
1.3-1 A grap
hi
cs window sh
ow
in
g a plot.
25
26
OVERLAY

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

ow automatica
ll
y a
pp
ea
r
s.
If
a hard copy
of
the plot IS
des
ll
~d,
tl~e
pl
ot
can be printed by select
in
g
Print
from
th
e File me
nu
~
n
the graphics
w~nd~w.
The window can be c

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

ow
.
Other u
ef
ul
plotting functions are
title
and
gtext
.
~hese
functions
pl
a.ce
text on
th
e plot. Both accept text within .parentheses and s
in
gle
quote
~,
as
W
lti~
the
xlabel
function. The
title
function
pl

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

of
values
in
the
plot
function. For example, to plot the
functions
y = 2.JX and z = 4
in
3x for 0
~
x
~
5
on
th
e same plot, the session is
»x
= [0 : 0 . 01 :5] ;
»y
=
2*sqrt
(x)
;
»z
=
4*sin(3*x)
;
»plot
(x

, 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

each
curve
so
that you know which curve represents
y and which curve repre
se
nts Z.
One
way
of
doing this i
to
use the
gtext
functi
on
to
pl
ace the labels y and z
next
to
the appropriate
cu
rves,
as
shown
in
the above session. Anoth
er
way

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

ypes
for each cur
ve.
For exa
mpl
e, to plot the z cur
ve
using a dashed line, r
ep
l
ace
the
plot
(x
, y , x ,
z)
fu
nction
in
the above session with
plot
(x,
y , x , z , '

')
.
Other
li
ne
types can

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

as
co
ntinuous
curves. This should be done because functions are de
fin
ed at an infinite
numb
er
of
points.
You
should never plot a function us
in
o
data markers
or
a sma
ll
numb
er
of
point.
b
Sometimes it is usef
ul
or necessary to obtain the coordinates
of
a
point
on a

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

til
e
x a
nd
y coordlllates
1Il
the vectors x and y, which have a lenoth n. Position
the
cursor
uSlI1g
a mouse, a
nd
press the mou e button. The returned
coordinates
have
the same scale as
th
e coordinates
on
th
e
pl
ot.
1
.3
Computing with
MATLAB
Table
1.3-3
Some

MATLAB
plotting commands
C
ommand
[x
,
y]
=
ginput
(n)
grid
gtext
( '
text
' )
plot
(x
,
y)
title(
'
text
' )
xlabel
( ,
text'
)
ylabel
( '
text

' )
Descl"iption
Enables the mou
se
to
ge
t n
point
s from a plot, a
nd
returns
th
e x and y
coordina
t
es
in
the vectors x and
y,
w
hi
ch have a length
n.
Puts grid lin
es
on
th
e plot.
Enable
s placement of tex t with the

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
are
plotting
data, as
opposed
to functions,
you
should u
se
data markers to plot each data
point
(unless there are very
many
data
points). To DATA
MARKER
mark
each
point
with a plus sign +, the required
syntax
for
th
e
plot
function is
plot
(x
, y ,
'+'

).
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

marker
.
Forexamp
le, s
uppose
the data for the
independe
n
tvariab
Je is x =
[15
: 2 :
23)
with units
of
seco
nds, and the
dependent
variable values are y =
[20
,
50
,
60
,
90
,
70)
wit
h

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
,

90
,
70)
;
»plot(x
, y , ' +
',
x ,
y)
,
xlabel(
' x
(seconds)
' ) ,
ylabel(
' y
(volts)
' )
Never
forget to label your
plots
with the units
of
measur
eme
nt! Other data mar-
kers
are
avai lable.
These

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

Chapter
5.
The c
hapt
er
also discusses h
ow
to u
se
plots to
develop
mailiematical
models
from
data.
This
proc
ess
is called junction discovery
and
regression.
Test
Your
Understanding
T1.3-3
Use
MATLAB
to plot the function s = 2 in(3! + 2) +
.JSr+T
over

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 =

4)6x
+ 1 and::: = Seo
.)x
- 2x
over
the interval 0
~
x
~
1.5.
Prop
e
rl
y label the plot
and
each
curve.
The
variables y and
:::
represent force
in
newtons; the
variable
x repre
se
nts
di stance
in
me

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

sol
ve
sets
of
lIn
ear
algebraic e
qu
a
tion
s.
For exam
pl
e,
co
ns
id
er
the
set
6x + 12y + 4z =
70
7x
- 2y + 3z = 5
2x
+
8y
- 9z =
64
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

tIon
s,
an?
as
many columns
as
the'
re
are variabl
es.
The
row
s of A
mu
st contain
th
e coefficients
of
x, y, a
nd
z
in
th
at order. In
thi
s exa
mple
,
the
fir

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

rig
h
t-
hand side of t
he
eq
uation;
it
ha
one column a
nd
a ma
ny
r
ow
s
as
there
are
eq
u
atio
n
s.
In
this examp
le
, the
fir
st

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

,-
9)
;
»B",
[70
; 5 ;
64)
;
»Solution
'"
A
\B
Solution
3
- 2
The
so
lu
ti
on
is x =
3,
Y = 5, and z =
-2.
Th
is
me
th
od
wo

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

at a
ll
!)
, s
ee
Ch
ap
ter
6.
s
T1.3-5
Use
MATLA
B
to
so
l
ve
the
fo
ll
ow
in
g set of e
qu
a
ti
on
s.
6x

- 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

uncti
ons for perfor
min
g sta
ti
stical calcula
ti
ons
and o
th
er types or
~
ata
ma
nipul
a
ti
on.
Fo
r
exa
mpl
e,
yo
u
ca
n compute
th
e mean (
th

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

pt
er 7 covers
th
ese topics,
as
we
ll
1.4
Sc
ript Fil
es
and the Edi tor/Debug ger
as
methods for obt
ai
nin
g several types
of
spec
ia
lized
hi
s
to
gram plots used in
statistical analysi
s.
The chapter also describes methods fordeveloping simu lations
ba
sed

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

ve
differential
eq
ua
ti
ons, which are equation involving der
iv
a
tiv
es; for example,
r}2
+5y
2 =
3sin8x
dx
where
th
e desired solution is y(x). Chapter 8 deals with these methods.
Chapter 9 treats Simulink, wh
ich
is a grap
hi
cal user interface,
bu
il
t on top
of
MATLAB, for solv
in
g differential

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

of
numerical
va
lues. Th
is
can
be
done with the Symbo
li
c Math too lbox. In
addition, t
hi
s toolbox can be used
to
symbo
li
ca
ll
y sol
ve
many types
of
algebrai
c,
transcendental, and differential equations. Chapter
10
covers these me
th
ods.
1.4 Sc

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

y
in
the
Co
mm
and window, or
2. By runn ing a MATL
AB
pr
og
ram stored in script
fi
l
e.
T
hi
s type of
fi
le
con
ta
in
s MATLAB commands, so running it is e
qu
iva
lent to
ty
ping a
ll
th

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

w
in
dow prompt.
Us
in
g
th
e in
te
rac
ti
ve
mode is simil ar to us
in
g a calculator, but is con
ve
ni
ent o
nl
y
fo
r simpler pro
bl
em
s.
When the pro
bl
em requires many co
mm
a

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

ms
to
avo
id
this difficulty.
You
write a
nd
save
MA
TL
AB
programs
in
M-
til
es, wh
ic
h
have
th
e
ex
tensio
n.
m; for exa
mpl
e,
program1
. m.

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

ays with many eleme
nt
s.
Because
th
ey conta
in
commands,
script
fil
es are sometimes ca
ll
ed commu
nd
fil
es. YO
ll
execute a sc
ri
pt
ti
le at
th
e
Comma
nd
window prompt by typing
it
s name witho
ut

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.

You
can
create your own function
repeat
the
opel
atlOn
0 a
se
fil
We
di
sc
u
ss
them
in Cha
pter
3.
. .
es.
. '
t'
ny
va
lid
MATLAB
commands or functions,
111-
~cnpt

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

get
the
sa
me
result
~s
If
you
~ad
typed at the
Command
window
prompt
all
the
comma
nd
s stored
111
the scnpt
fi
l
e,
,?ne
~t
a
time.
Wh
en
yo

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

ava
il
able
in
th
e workspace;
thus
,
we
say
the vanables created by a
script
file
are
globa
l
variab
l
es
.
Creating and
Us
ing a Script File
The
sy
mbol
% d
es
igna
te

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

pt
file
s
fo
r
th
e
purpo
se
of
docum
e
ntin
g
th
e
file.
Th
e comme
nt
sy
mbol may be put
an
yw
here
in
th
e l
ine.
MATLAB

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

comment
.
2+3
% So
is
this
.
Note that
the
portion of
the
lin
e before
the
% s
ign
is executed
to
compute x.
Here is a s
impl
e
examp
le
that
illustrates
how
to
crea
te

, 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.

It computes the
s
ine
of
the
s
qu
a
re
foot of
seve
ral
numb
ers
a
nd
displays
th
e
re
sults
on
the screen.
Program
example1
. m
%
This
program
computes

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
(

in
the
MS
Window
s environment),
in
the Command
window
se
lect
New
from
the
File
menu
,
then
se
lect M-file.
You
will then see a
n
ew
e?
it
window.
This
is
the
Editor/Debugger window

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

to
create and edit
th
e
file

When
finished,
se
l
ec
t Save
from
the
File
menu
in
the EditoriDebugger.
I~
th~
di
a
log
b~x
that
appears,
replac
e
th
e default name provided (usually named

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

we
will
ass
um
e
to
be
on
the hard drive.
1.4
SCript Files and the Edito
r/D
ebugger
File
Edit Debug Desktop Window
Help
,
r1
~
Currer
rt
Directory: I c:lrnetlab7
Shortcuts
1tJ
Ho
w to Add
»
example
1
0.7867

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

: 2 :
13
J ) ;
5-
y=sin(x)
F
igur
e
1.4-1
The MATLAB
Com
ma
lld
wi
nd
ow with the Editor/Debugger
ope
n.
Once the
file
h
as
been saved,
in
the MATLAB Command window type
th
e
script
file
's name

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

re
. ulting
Command window
di
splay and the Editor/Debugger opened
to
di
splay
th
e scri pt
file.
Effective Use of Script Files
Create script
file
s
to
avoid the need
to
retype commonly used procedures. The
above file,
example1,
implemen
ts
a very simple procedure, for which
we
ordinarily would not create a script
file.
However, it illustrates how a script
file
is

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

An
Overv
i
ew
of
MA
T
LAB
. k
in
mind
when
using script
file
s:
Here
are
some
o
th
er
thlI1gs
to
eep
'
. .
must
follow
the
MATLAB

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

up
to
31 characters.
and
the
under
score
c
laI
aC
, t
the
Command window prompt causes
2.
Reca
ll
that
typing a
variab
le's
n
a~1~
a '·able Thus
do
not aive a script
MATLAB
to
display
the
v~.

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

le
to
execu
te
th
at
SCrIpt
file
more
t,
an
I
'd
.
.
fil
h
sa
me
name
as
a
MATLAB
comman 0 1
3.
Do
not
gi
ve
a

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

th
e
ex~st
.
st
( '
examplel
' ) ; this
wi
ll
return
examplel
al
ready
eX
I
sts,
typ
e
eXl
. " .
'f
an
M-fi le
a
0 if
th
e
variab
le

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

file;
thi
s
will
return
a 0 if
the
file
does not
eX
Ist,
~d
a 2
'/t
doe
s Finally to
see
if a built-in f
un
c
ti
on
examplel
already
eX
Ists,.
~y~e
e
xi
st

(
'
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

not
eXIst,
and a 5 Jf
It
does.
4.
As
in
interactive
mode
, a
ll
variab
l
es
c
reat
ed
by
~
sc
rip
.t
file
are
~loba
l
variab
l
es,

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

p.re
sen
t.
.
5.
Variable
s cr
eated
by
a
function
file
are local
to
that
fu
nctIon, whl:h m
ea.
ns
that their
va
lu
es
are
not
ava
ilabl
e outside
the
f

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

t1:
e
var
iabl
es
in
a
sc
ript
file,
consider us
in
g a functIon
fil
e
Ill
stead

ThIS
WIll
avoid
"clutte
rin
g"
th
e
works
p
ace
with

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

a text
ed
it
o
r.
For
example, to vi
ew
th
e
file
exa
m
plel,
the command is
type
exa
m
plel.
Note that not
all
functions s
uppli
ed
with
MATLAB
are "built-in" functions.
For
exa
mple.

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.

You
m
ay
think
of
built-
in
functions
as
primitives
that
form
the
ba
sis for other MATLAB function
s.
You
callnot vi
ew
th
e e
ntire
file
of a
built-in
function
in
a
te
xt editor, only the comments.

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

simultaneous
ly.
Or
you
can
dock
the
EditorlDebugger window
in
side the
1
.4
Sc
ript Fil
es
and
th
e Editor/Debugger
Desktop
by
selecting Dock
from
the view menu of the Editor/De
bu
gge
r.
To
activate a window,
cl
i

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

nd
the Comma
nd
w
ind
ow.
In
the Command window, use
th
e
up
-a
rrow
key
to
ret
ri
eve
th
e previously typed
sc
ript-file name, a
nd
press E
nter
to
exec
ut
e
the scrip t

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

can use the EditorfDebugger
as
a basic word processor
to
write a short
report that includes
yo
ur script
fi
l
e,
resu l
ts,
a
nd
di
scussion, perhaps
to
present your solution
to
one
of
the chapter problems.
Fi
rst u
se
th
e mouse
to
hi

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

me
nu
).
Then,
to
save space, delete any
ex
tr
a
blank
lin
es, and perhaps the prompt sy
mb
o
l.
Type your name and any other
required information, add any
di
s
cu
ss
ion
yo
u wish, and print the report
from the EditorlDebugger
wi
nd
ow,
or save
it

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

rror,
in
a program. Such errors usually fall into one
of
the following categories.
1.
Syntax errors such
as
omitting a pare
nth
esis or comma, or spelling a
co
mm
a
nd
name incorrec
tl
y.
MATLAB us
uall
y detects the more obvious
errors a
nd
di
s
pl
ays a message describing
th
e error and its location.
2. Errors due

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

an
eITor
, try the following:
1.
Always test your program with a simple vers
ion
of
the problem, whose
an.
wers can
be
checked
by
hand calculations.
2.
Di
splay any intermediate calculations
by
removing semicolons at the end
of
statements.
3.
Use
th
e debugging features of the EditorlDebugger, which are covered
in
Chapter
4.
However, one advantage of MATLAB
is

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

may
be
put
anywhere
in
the
script
file.
How
ever,.
it
is
in~portant
to
note
that
the
first
comment
lin
e
before
any
executable statement
IS
the
IlI1
e searched by
the
lookfor

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

ed
the
HI line). .
A sugge
ted
structure
for
a
sC
lipt
file
is
the
followll1g.
1.
Commellts sectioll
In
this
section put comment statements
to
give:
The
name
of
the
program
and
any
key
words

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

sections, one
fo
r input
data, a
nd
one
for
output
data
. A
third
, optional section may include
definitions of
variab
l
es
u
se
d
in
the
ca
lculation
s.
Be sure to
include
the
units
of
measu

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

be
entered. Include comments where appropriate for
do
cumentation.
3. Calcltlation section
Put
the
calculations
in
thi
s section . Include
com
ments
where
appropriate
for
documentation.
4. Ou/put sec
ti
on
In
t
hi
s sec
tion
put
the
fu
nctions necessary
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

for
documentation.
The
programs
in
thi
text
usua
ll
y
omit
th
e
co
mm
e
nt
s
in
order
to
save spac
e.
These
co
mm
e
nt
s
are

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

I
Documenting Units of Measurement
'!V
e
e
mph
a i
ze
aga
in
that
yo
u
mu
st document
the
units of measurement for
all
the
Input a
nd
all
the
output
variables.
More
than
one
dr
amat

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

es
o~
the
progr
am u
se
d to d
es
ign the
sys
tem
. Table
1.4
- 1
li
sts
~ommon
units a
nd
theIr
a
bbreviation
s.
The
foot-pound-second system (FPS) is
also
~a
ll
e
d

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

ha
ve
applications
hi
I .
freq
uently If
so
yo
w C 1
~eqUlre
you
to
access the sa
me
set
of
data
.
. u
can
storethedatall1 an array within ascript
file.
An example
is
1.4
Script Files and
the
Editor/Debugger
Tab

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

Ene
r
gy
joul
e (1)
fOOL-pound
(fl-
Ib
),
BlU
(=
778
ft-Ib)
P
owe
r
watl(W)
fl-Ib/sec,
Te
mp
eralure
hor
se
power (hp)
degr
ees
Celsius (oq ,
degree
s
Fahrenheil

(' 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

. m. The arr
ay
temp_F
contains temperatures
in
d
eg
rees Fa
hr
enhe
it.
File
mydata
. m:
Stores
temperature
data
.
%
Stores
the
array
temp
_ F,
%
which
contains
temperatures
in
degrees

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

75
77
83
79
»tem
p_C
=
5*(temp
_ F -
32)/9
temp
_C =
22
.
2222
20
.
0000
23
.
8889
25
.
0000
28
.
3333
26
.
1111

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

c =
-67.
The answers forthis case are x = 2
,)'
=
-S,
z =
10
.
6x - 4y +
8<;
= a
-Sx
- 3)' + 7z = b
14
x+9y-
Sz = c

35

×