Professional Documents
Culture Documents
The diagram in Fig. 1 . 1 shows the main features and capabilities of MATLAB.
MATLAB's built-in functions provide excellent tools for linear algebra computa
tions, data analysis, signal processing, opt i mization , numerical solution of o r din ary
differential equations ( ODEs ) , quadrature, and many other types of scientific com
putations . Most of these functions use state-of-the-art algorithms. There are nu
mcrom; functions for 2-D and 3-D graphics , as well as for animation. Als o , for Lhosc
w ho cannot do w it ho u t their Fortran or C codes, MATLAB even provides an ex
ternal interface to run those p ro gr ams from within MATLAB. T he user, however ,
is not limited to the built-in functions; he can write his own functions in the MAT
LAB language. Once written, these functions behave j ust like the built-in functions.
MATLAB 's language is very easy to learn and to use.
There are also several optional "t oolboxe s " available from the developers of
MATLAB. These toolboxes are collections of functions written for special appli
cations such as symbolic computation, image processing, statistics, control system
d es ign, and neural networks. The list of toolboxes keeps growiug with time. There
are now more than 50 such toolboxes. We do not attempt introduction to any
toolbox here, with the exception of the Symbolic Math Toolbox ( Chapter 8 ) .
The basic building block o f MATLAB i s the matrix. The fundamental data type
is the array. Vectors, scalars, real matrices, and complex matrices are all automat
ically handled as special cases of the basic data type. Wh at is more, you almost
never have to declare the dimensions of a matrix. MATLAI3 simply loves matrices
2 Introduction
0
MATLAB
E E
X X
Graphics T Computations T
External Interface
R Linear Algebra R
A
• 2-D Graphics A
•
(Mex-files)
• 3-D Graphics $
• Data Analysis
$
F
Interface with C, Java,
F Signal Processing •
Color and Lig hting •
u u
•
Quadrature
Audio and Video c C:
•
•
T • Solution of ODEs T,
I I
0 0.
N; N
and matrix operations. The LuilL-in functions are optimize d for vector operations.
C onse qu ently, vcctorized1 commands or codes run much faster in MATLAB.
The most likely answer is "yes," because MATLAB supports almost every compu
tational platform. In addit io n to Windows , MATLAB is available for UNIX, Sun
Solaris, Linux, and Mac OS X op er atin g systems. Older versions of MATLAB are
available for addit io nal platforms such as Mac OS and Open VMS. To find out
more about product availability for your particular computer, see the MathWorks
website listed in Section 1.4.
1 Vectorization referB to a manner of computation in which an operation is performed simulta
mJuusly on a list of numbers (a vcector) r11.th�r than AtXjUCntially on each member of �hi! li�L Fur
example, let (} be a list of 100 numbers. Then y =sin( B) i� "· vRctorized st at ement as opposed to
Yl = sin(lh ) ,y2 = sin(B2 ) , etc.
2Symbolic a.lgcbra meanG that computation is done in terms of symbols ur variaules ralhPr than
numbers. For example, if you type (x+y)-2 on your curnpuLPr and Lite cuml-'uler responds by
sayi n g that the expression is equal to x2 + 2xy + y2, Ll1en your computer does symbolic algebra.
Software package� that du tiymbulic algebra are also known as computer algebra systems.
4 lntrod uctiun
---- --
• Typographical styles:
- All actual MATLAB commands or instructions are shown in t yped
face. Menu commands, files names, etc. , are shown in sa ns serif font.
- Place holders for variables or names in a command are shown in italics.
So, a command shown as he lp topic implies that you have to type the
actual name of a topic in place of topic in the command.
- Italic text has also been used to emphasize a point and, sometimes, to
introduce a new term.
• Actual examples: Actual examples carried out in MATLAB are shown in
gray, shaded boxes. Explanatory notes have been added within small white
rectangles in the gray boxes, as shown in Fig. 1.2. These gray, boxed figures
are intended to provide a parallel track for the impatient reader. If you would
rather try out MATLAB right away, you are encouraged to go through these
boxed examples. Most of the examples are designed :oo that you can ( more or
less ) follow them without reading the entire text. All examples are system
independent . After trying out the examples, you should read the appropriate
sections.
• On-line help: We encourage the use of on-line help. For almost all major
topics, we i nd ic ate the on-line help information in a ::;mall box in the margin,
as shown here on the left .
1.6 Basics of MATLAB 5
Figure 1.2: Actual examples carried out in MATLAB are shown in gray boxes
throughout this book. The text in the white boxes inside these gray boxes are
explanatory notes.
Typing help topic in MATLAB with the appropriate topic name provides
a list of functions and commands for that topic. Detailed help can then be
ohtained for any of those command s and functions.
We discourage a passive reading of this book. The best way to learn any com
puter software is to try it out . We believe this, practice it, and encourage you to
practice it too. So, if you are impatient , quickly read Sections 1 . 6 . 1 - 1 .6.3, jump to
the tutorials on page 15, and get going.
(File) Details pane: Just below the C urrent D i rectory pane is the Detai ls
pane that shows the details of a file you select in the current directory
pane. These details are normally limited to listing of variables from a
2. Figure window: The output of all graphics commanrls typed in the com
mand window are flushed to the graphics or figure window, a separate gray
window with (default) white background c o l o r . The u s er can create as many
figure windows as the system memory will allow.
3. E d itor window: This is where you wr it e , edit , c reat e , and save your own
programs in files called M-jiles. You can use any text editor to carry out these
tasks. On mo st systems , MATLAB provides its own built-in editor. However,
you can use your own editor by typing the standard file-editing command that
you normally use on your system. From within MATLAB , the command is
typed at the MATLAB prompt following the exc l am at ion character ( ! ) . The
exclamation character prompts MATLAD to return the control temporarily
to the local operating system, which executes the command following the
character. After the editing is completed, the control is returned to MATLAB.
For example, on UNIX systems, typi n g ! vi myprogram . m at the MATLAB
prompt ( and hitting the return key at the end ) invokes the vi editor on the
file myprogra m . m . Typ i ng ! emac s myprogram . m invokes Lhe emacs editor.
1 .6.3 Input-output
MATLAB supports i nteract ive c omp utation ( s ee C hapt er 3) , taking the input from
the screen, and flushing the output to the screen. In addition, it can read input
files and write output files ( see Section 4.3.7) . The following features hold for all
forms of input-output :
• Data type: The fundamental data type in MATLAB is an array. It encom
passes several disLlnct data obj ects-integers , doubles ( re al numbers ) , ma
trices, char act e r strings, s t ru ctur e s , and cells. 3 In most cases, however, you
never have to worry about the data typ e or the data object declar at ions . For
example, there ia no need to declare variables as nml or comp lex . Wh P.n a real
numl.Jer is euLered as the value of a variable, MATLAB automatically sets the
variable to be real (double) .
21
3Structures an d cells as d ata objects were introduced in MATLAB 5. See Section 4.4 on page 1
fur their dcBcription. MATLAB al so allow� n�Pr� t o create their OWn data objects and MSOciatcd
operations. We do not discuss this facility in this book.
8 Int roduction
MATLAB Desktop
!
Current Directory
Ed itor Window _/
Figure 1 .3: The MATLAB environment consists of the MATLAB desktop, a figure
window, and an editor window. The figure and the editor windows appear only
when invoked with the appropriate commands. For example, you can open the
editor window by selecting F i l e ___. N ew ___. B la n k M - F i le, and open a blank figure
window by selecting F i l e ___. N ew ___. Figu re.
1 . 6 Basics of MATLAB 9
commands from even previous sessions of MATLAB are recorded and listed )
to execute it in the command window. On most UNIX systems, MATLAB's
command-line editor also understands the standard emacs keybindings.
• Creating a directory and saving files: Where should you save your files so
that MATLAB can easily acc e ss them? MATLAB create� a default folder
called M a t l a b in�ide D o c u m e n t s ( on Macs) , or My Docu ments ( on PCs)
where it saves your files if y o u do not specify any other location. I f you are
the only user of MATLAB on t he computer you are working on, this is fine.
You can save all your work in this folder and access all your files easily (default
setup) . If not, you have to create a separate folder for saving your wor k .
Theoretically, you can create a directory /folder anywhere, save your files,
and direct MATLAB to find those files. The most convenient pla<..:e , however,
to save all user-written files is in the default directory M ATLAB c r eate d by
the application in your Doc u ments or My Docu ments folder. T hi s way all
user-written files are automatically accessible to MATLAB . If you need to
store the files somewhere else , you might have to specify the path to the files
using the path command, or change the working directory of MATLAD to
the desired directory with a few navigational clicks in the C u rren t D i rectory
pane. We re commend the latter.
• Printing:
On PC s : To print the contents of the current active window (command,
figure, or edit window) , select P ri nt . . . from the F i le menu and click
P ri n t in the dialog box. You can also print the contents of the figure
window by typing print at the MATLAB prompt .
On UNIX machines: To p rint a file from inside MATLAB , type the appro
priate UNIX command preceded by the exclamation character ( ! ) . For
example, to print the file sta rt u p . m , type ! lpr startup . m on the MAT
LAB prompt . To print a graph that is currently in the figure window
simply type print on the MATLAB prompt.
12 Introduction
General information
comput er tells you the computer type you are using
clock gives you wall clock time and date as a vector
dat e tells you the date as a string
more controls the paged output according to the screen size
ver gives the license and the MATLAB version information
benc h benchmarks your computer on running MATLAB
compared to other computers
Termination
�c ( Control-c ) local abort , kills the current command execution
quit quits MATLAB
exit same as quit
1 .7 Visit This Again 13
the most. Although many of these things would prohably not make sense to you
right now, they are here, and you can come back to them whenever they seem
relevant.
In the past , file navigation in MATLAB has caused considerable problems for
users, especially the beginners. We have had numerous complaints from students
about not being able to make MATLAB find their file, get MATLAB to work from
their directory, get MATLAB to find and exec.ute the currently edited file, etc.
Fortunately, from MATLAB 6 onward, MathWorks has incorporated several new
features that mitigate this problem immensely. The current directory is shown just
above the command window with the option of changing it with just a click of the
mouse. There is also a current directory subwindow to the left of the command
window that lists files in the current directory and gives you options of opening,
loading ( Mat-file ) , executing ( M-file ) , editing, etc . , with the click of the right button
on the mouse. You can also change the directory there or add a particular directory
to the MATLAB path so that MATLAB has access to all the files in that directory
automatically.
If you do not save all your MATLAB files in the default Work directory or folder,
you need to be aware of the following issues.
1. Not b eing in the right directory: Yo u may writ e and save many MATLAB
programs ( M-files ) but MATLAB does not seem to find them. If your files
are not in the current working directory, MATLAB cannot access them. Find
which directory you are currently in by looking at the small current directory
window in the toolbar or by querying MATLAB with the command pwd. If
you are not in the ri ght place, guide MATLAB to get to the directory where
your files are. See Lesson 10 in the tutorials ( Chapter 2 ) .
2. Not saving files i n the correct directory: When you edit a file i n the
MATLAB editor / debugger window and save it , it does not automatically
mean that the MATLAB command window has access to the directory you
saved your file in. So, after saving the file, when you try to execute it and
MAT LAB does not find your file, follow item 1 above and set things right.
3 . No t overwriting an existing file while editing: You run your program by
executing your M-file, do not like the result, edit the file, and run it again;
but MATLAB gives the same answer! The previou;;ly parsed ( compiled ) file
is executing; M AT LA B does not know about your changes. This can happen
due to various reasons. The simple cure is, clear the workspace with clear
all and execute your file.
There are various other little things that cause trouble from time to time. We
point them out throughout the book wherever they raise issues.
�"',
c;,\�e \�TPBY �t sfmpl�
Ul§l �
CC<<\Vl l�tU@ IYB5
St\'Mft
Tutorial
• Less ons
The following lessons are designed to get you started quickly in MATLA B . Each
lesson should take about 1 0-15 minute s . The lessons are intended to make you
familiar with the basic facilities of MATLAB . We also urge you to do the exercises
given at the end of each lesson. This will take more time, but it will make you
familiar with MATLA B . If you get stuck in the exercises, simply turn the page;
answers are on the back. Most answers consist of correct commands to do the
exercises. However, there arc several mrrect ways to do the problems. So, your
commands may 'look different than t hos e given.
Before Yo u Start
You neeJ some information abouL the computer you are going to wo rk on . In
particular, find out the fo llowing:
• How to switch on the computer and get it started.
• How to lo g on and log off.
• Where MATLAB is installed on the computer.
• How to access MATLAB .
• Where you can write and save files-hard drive or a floppy disk.
• If there is a printer attached to the computer.
If you are working on your own computer, you will most likely know the answer
to these question�. If you are working on a computer in a public facility, the system
manager can he lp you. If you are in a class that requires working on MATLAB ,
your pr ofe s so r or TA can provide answers. In public facilities, sometimes the best
t hing to do is to spot a friendly person who works there and ask these questions
p olit ely. People are usually nice!
If you have not read the introduction ( Chapter 1 ) , we recommend that you at
least read Sections 1 . 6 . 1- 1 . 6 . 3 and glance through the rest of Section 1. 6 before
trying the tutorials.
16 Tutorial Lessons
T h e Ba sics
Here are the lessons in a nutshell:
Time Estimates
Lesson: 1 0 minutes
Exercises: 30 minutes
In addition, if you do the exercises, you will learn more about arithmetic oper
ations, exponentiation and logarithms , trigonometric functions, and complex num
bers .
Method: Log on and launch MATLAB . Once the MATLAB command window
is on the
screen, you are re ady to carry out the first lesson. Some commands and
their output are shown in Fig. 2. 1 . Go ahead and reproduce the results.
18 Tutorial Lessons
» 2 + 2
Enter 2 + 2 and hit the return/enter
key. Note that the result of an un
ans
assigned expression i s saved in the
default variable ans .
4
y =
3 . 1337
» t he t a = aces (-1)
MATLAB knows trigonometry.
Here is arccosine of - 1 .
t he t a =
3 . 14 1 6
3 . 1416e+ 0 0 0
t he t a =
3 . 1415 92653 5 8 9 7 93
Quit MATLAB. You can also quit by
selecting Quit from the file menu on
» qu i t
Macs and PCs.
EX E R C I S ES
• e "VI63.
• S olve 3x 17 for x and check the result. ( The solution is x
= = 1f,/37 . You
can verify the result by direct substitution. )
A nswers to Exercises
1. Command Result
2-5/ (2-5-1) 1 .0323
3* ( sqrt ( 5 ) - 1 ) / ( sqrt ( 5 ) + 1 ) - 2 - 1 -0.6459
area=p i * (pi - ( 1 /3) - 1 ) - 2 0.6781
2. Command Result
exp ( 3 ) 20.0855
log ( exp ( 3 ) ) 3
log1 0 ( exp ( 3 ) ) 1 . 3029
log10 ( 1 o - s ) 5
exp (pi*sqrt ( 1 63) ) 2 . 6254e+ 17
x=log ( 17 ) /log ( 3 ) 2.5789
3. Command Result
s in (pi/6) 0 .5000
cos (pi) -1
t an (pi/2) 1 . 6331e+16
( s in (pi/6) ) - 2+ ( c o s (pi/6) ) - 2 1
x=32*pi ; y= ( c o s h ( x ) ) - 2- ( s inh (x) ) - 2 0
4. Command Result
( 1+3i) / ( 1 -3 i ) -0.8000 + 0 .6000i
exp ( i *pi/4) 0 . 7071 + 0.7071i
exp (pi/2 * i ) 0.0000 + l . OOOOi
exp (pi/2 i ) 0.0000 l . OOOOi
-
Note that
exp (pi/2 * i ) = e � i = cos ( � ) + i sin G ) = i
exp (pi/2 i ) e Yi = e - � i = cos ( � ) - i sin G ) = -i
=
2.2 Lesson 2: Creating and Working with Arrays of Numbers 21
Time Estimates
Lesson: 15 minutes
Exercises: 45 minutes
Method: You already know huw to launch MATLAB . Co ahead and try the
commands shown in Fig. 2.2. Once again, you are going to reproduce the results
shown.
22 Tutorial Lessons
1 2 3
»y [2 i 1 ,· 5]
y is a column vector with three
elements.
y
2
1
5
3 3 3
» b 2*a
But mu ltiplying a vector with a
>> z
functions s q r t , exp, l og, etc . ,
s qrt (x} . *y
operate o n vectors term b y term.
EX E R C I S E S
x = 0, 1 .5 , 3, 4, 5, 7, 9, and 10.
1r, and 57rl4. Take r 2 an d compute the column vectors x and y. Now
=
check t hat x and y indeed satisfy the equation of a c ircl e , by computing the
rad i u s r = J(x2 + y2 ) . [To calculate r you will need the array operator . -
for squaring x and y. Of course, you could compute x2 by x . *X also. ]
4. The geometric series: This is funky! You know how to compute xn element
by element for a vector x and a scalar exponent n. How about computing
x
n , and what does it mean? The result , again, is a vector wit h e lement s
n , , n 2 , n 3 , etc. The sum of a geometric s e r i es 1 + r + r2 + r 3 +
x x x
+ rn
· · ·
[r0 r1 r2 r n ] with the x=r . -n command. Now take the sum of this
vector with the command s=sum ( x ) ( s is the sum of the actual series) . Cal
culate the limit l �r and compare the computed sum s. Re p eat the procedure
t aki ng n from 0 t o 50 and then from 0 to 1 00.
5 . Matrices and vectors: Go to Fig. 3 . 1 on page 67 and reproduce the results.
Now create a vector an d a matrix with the following commands: v=O : 0 . 2 : 1 2 ;
and M= [sin (v) ; c o s (v) ] ; (see Section 3 . 1 . 4 on page 72 for use of " : " in
creating vectors) . Find the sizes uf ·u and M using the s i z e command. ExlmcL
thP. A r.q f: 1 0 Alementf; of each r ow of the matrix and display them as w lumn
vedvrs .
24 Tutorial Lessons
A nswers to Exercises
Commands to solve each problem are given here.
1. x= [0 1 . 5 3 4 5 7 9 1 0] ;
y=0 . 5*x-2
[Ans. y - 2 . 0000
= - 1 .2500 -0.5000 0 0 . 5000 1 .5000 2 . 5000 3 .0000]
2. t=1 : 10 ;
x=t . * sin ( t )
y= (t - 1 ) . / (t + i )
z=s in (t . - 2 ) . / (t . - 2 )
4. n=O : 1 0 ;
r=0 . 5 ;
x=r . - n ;
s 1 =sum (x)
n=0 : 50 ;
x=r . -n ;
s2=sum (x)
n=0 : 1 00 ;
x=r . - n ;
s3=sum (x)
[Ans. s 1 = 1 . 9990, s2 = 2.0000, and s3 = 2]
5 . v=0 : 0 . 2 : 1 2 ;
M= [ s in (v) ; cos (v) ] ;
s ize (v)
s ize (M)
M ( : , 1 : 1 0) '
[Ans. v is 1 x 61 and M is 2 x 6 1 . T he M ( : 1 : 1 0 ) ' command picks out the
,
Method: You are going to draw a circle of unit radius. To do this, first gene rat e
the data ( x- and y-coordinatcs of, s ay, 100 p oint s on t he circle ) , then plot the data,
and finally print the graph. For generating data, use the parametric equation of a
unit circle:
X = cos B, y = sin B , 0 ::::; e ::::; 27r.
In the sample session shown in Fig. 2.3, only the commands are listed. You
should see the output on your screen.
26 Tutorial Lessons
» theta. ""· l inspa.C.e .(0. ,. 2 *pi f :l.O O) . ; Create a linearly spaced 1 00-
elements-long vector S .
» x cos ( the ta ) ;
>> y • s i n ( the t a } ;
» plot ( x , y)
Commen ts:
• After you enter the command plot (x , y ) , you should see an ellipse in the
figure window. MATLAB draws an ellipse rather than a circle because of its
default rectangular axes. The command ax i s ( ' equal ' ) dir e ct s MATLAB to
use the same scale on both axes, so that a circle appears as a circle. You can
also use axi s ( ' square ' ) to override the default rectangular axes.
• The arguments of the axi s , xlabel , ylabel , and t itle commands are text
strings. Text strings are entered within single right-quote ( ' ) characters. For
more information on text strings, see Section 3.3 on page 77.
• The print command sends the current plot to the printer connected to your
computer.
2.3 Lesson 3: C r e ati n g and P rint ing Simple Plots '2 7
EX E R C I S E S
1. A simple sine plot : Plot y = sin x, 0 :::; x :::; 21r, taking 100 linearly
spaced points in the given interval. Label the axes and put "Plot created by
yourname" in the title.
2. Line styles: Make the same plot as in Exercise 1, but r at her than displaying
the graph as a curvf!, show the unconnected data points. To display the
Jata points with small circles, u�c plot (x , y , ' o ' ) . [Hint: You may look into
Section 6 . 1 on page 1 75 if yon wish.] Now combine the two plots with the
command plot ( x , y , x , y , ' o ' ) to show the line through the data points as
well as the distinct data points.
3. An exponentially decaying sine plot : Plot y = e-0.4x sin x , 0 :::; x :::; 471",
taking 10, 50, and 100 points in the interval. [Be careful about computing
y. You need array multiplication between exp ( -0 . 4*x) and s in (x) . See
Section 3 . 2 . 1 on page 73 for more discussion on array operations. ]
4. Space curve: Use the command plot3 (x , y , z ) to plot the circular helix
x (t) sin t, y(t) = cos t , z ( t ) = t, 0 ::=;; t ::=;; 20.
=
5. O n- line help : Type help p l o t o n the MATLAB prompt and hit return. If
too much text flashes by the screen, type more on, hit return, and then type
help plot again. This should give you paged screen output . Read through
the on-line help. To move to the next page of the screen output , simply press
the spacebar.
6 . Log-scale plots: The plot commands s emi logx, s emilogy, and loglog plot
the x-values, the y-values , and both x- and y-values on a log 1 0 scale, respec
tively. Create a vector x=O : 1 0 : 1000. Plot x vs. x 3 using the three log-scale
plot commands. [Hint: First , compute y=x . � 3 and then use semilogx (x , y) ,
etc. ]
7. Overlay plot s : Plot y cos x and z
= 1 - x22 + �: for 0 ::=;; x ::=;; 1r on the same
=
plot . You might like to read Section 6 . 1 . 5 on pagf! 1 79 to learn how t o plot
multivle curves on the same graph. [Hint : You can use plot (x , y , x , z , ' - - ' )
or you can plot the first curve, use the hold on command, and then plot the
second curve on top of the first one. ]
8. Fancy plots: Go to Section 6 . 1 . 6 and look at the examples of specialized 2-D
plots given there . Reproducf! any of the plots you like .
9 . A very difficult plob Use yonr knowledge of splines and interpolation to
dmw a lizard (iust kiddin.o;) .
28 Tutorial Lessons
4. t=l inspace ( 0 , 2 0 , 1 0 0 ) ;
plot 3 ( s in (t ) , c o s ( t ) , t )
6. x=O : 1 0 : 1000 ;
y=x . - 3 ;
semilogx ( x , y )
s emilogy ( x , y )
loglog ( x , y )
7. x=linspace ( O , p i , 1 0 0 ) ;
y=cos ( x ) ; z = 1 - x . - 2 / 2+x . - 4/24 ;
plot ( x , y , x , z )
plot (x , y , x , z , ' - - ' )
legend ( ' c o s ( x ) ' , ' z ' ) % try thi s l egend c ommand
[For fun: If the last command legend does produce a legend on your plot , click and
hold your mouse on the legend and see if you can move it to a location of your liking.
See page 177 for more information on legend.]
2.4 Le:J:Jon 4: Creating, Saving, and Executing a S cript File 29
-- - -----
S cript File
Goa/: To learn how to c:reate script files and execute LhHrn in MATLAB .
A script file is
a user-created file with a sequence of MATLAB commands in it . The
file must be saved with a . m exten s ion to its name, thereby, m aking it an M-jile. A script
file is executed by typing its name (without the . m extens ion ) at the command prompt .
For more i nfo rm at i on , see Section 4.1 on page 99.
Time Estimates
Lesson: 20 minutes
Exercises: 30 minutes
emacs) , or that you ' re using the built-in MATLAB editor on a Mac or a PC.
• You know how to open, edit , and save a file.
Method: WriLe a script file to draw the unit circle of Lesson 3. You are essentially
going to write the command� shown in Fig. 2.3 in a file, save it , name it , and execute
it in MATLAB . Follow the directions below.
1 . Create a new file:
• O n PCs and Macs : Select File-+New-+ B ia n k M - F i l e from the File
4. Now get back to MATLAB and type the commands shown in Fig. 2.4 in the
command window to execute the script file.
» circle
Execute the file. You should see
the circle plot in the figure window.
5 . If you have the script file open in the MATLAB editor window, you can also
execute the file by pressing the R u n file icon (the little green arrowhead over
a white page in the edit window nemu bar) or the F5 function key (see Debug
menu) .
2 .1. Lesson 4: Creating, Saving, and Executing a Script File 31
EX E R C I S ES
1 . Show the center of the circle: Modify the script file ci rcle . m to show the
center of the circle on the plot, too. Show the center point with a "+" . ( Hint:
See Exercises 2 and 7 of Lesson 3.)
3. Variables in the workspace: All variables created by a script file are left in
the global workspace. You can get information about them and access them,
too:
• Type who to see the variables present in your workspace. You should see
the variables r , thet a , x, and y in the list .
• Type whos to get more information about the variables and the workspace.
• Type [thet a ' x ' y ' ] to see the values of (), x , and y listed as three
columns. All three variables are row vectors. Typing a single right quote
( ' ) after their names transposes them and makes them column vectors.
4. Contents of the file: You can see the contents of an M-file without opening
the file with an editor. The contents are displayed by the t yp e command. To
see the contents of c i rcle . m , type t yp e circle . m.
A n swe rs to Exercises
6. Here is a script file that you may not fully understand yet . Do not worry, j ust
copy it if you l i ke it . See the on-line help on the commands used, e.g. , di sp ,
dat e , f ix , c l o ck, and int2str.
% Scr ipt f i l e t o begin your day . Save it a s Hi _there . m
% To execut e , j ust type Hi_there
% File wr itten by Rudr a Prat ap on 6 / 1 5 / 9 5
% Last modif ied 6/28/98
% -------------------------------
di sp ( ' H e l l o R . P . , H o w i s l i f e ? ' )
disp ( ' ' ) % display a blank l ine
d i sp ( ' Today is . . . ' )
disp ( dat e ) % d i spl ay dat e
t ime=f ix ( clock) ; % get t ime as int egers
hourstr=int 2 s t r (t ime ( 4 ) ) ; % get the hour
minstr=int2str ( t ime ( 5 ) ) ; % g e t the minut e
if t i m e ( 5 ) < 1 0 % if minut e i s , s ay 5 , then
minstr= [ ' O ' , minstr] ; % - wri t e it as 05
end
t imex= [hour str ' : ' minstr] ; % creat e the t ime str ing
d i sp ( ' ' )
disp ( ' And the t ime i s . . ' )
disp ( t imex) % display the t ime
2 . 5 Lesson 5: Creat ing and Executin g a Function File 33
---- ---
Goal: To l e arn how to write o.nd execute a function file and to Jearn the difference
between a script file and a function file .
A function file is also an M-file, just like a script file, except it has a function definition
line on thA top that defines the inp ut and output explicitly. For more informatio n , see
Section 4.2.
Time Estimates
Lesson: 15 minutes
Exercises: 60 minutes
Method: Write a function file to draw a circle of a specified r adius , with the
radius as the input to the function. You can either write the function file from
scratch or modify the script file of Lesson 4. We advise you to select the latter
option.
1. Open the script file c i rcle. m :
• O n PCs: Select F i l e----> O p e n . . . from the F i l e menu. Navigate and select
the file c i rcle. m from the O p e n dialog box. Double-click to open the file.
The contents of the file should appear in an edit window.
• On UNIX workstations: Type ! vi c ir c l e . m or ! emacs circle . m
on the MATLAB prompt to open the file in a vi or emacs window.
2 . Edit the file c i rcle . m from Lesson 4 to look like the following:
funct i on [x , y] = circlefn ( r ) ;
% CIRCLEFN - Funct i on to draw a c i r c l e of radius r .
% F i l e wr itten by Rudra Prat ap on 9 / 17/94 . Last modif i e d 7/ 1 /98
% Call synt ax : [x , y] = c ir c l efn ( r ) ; or j ust : c i r c l efn ( r ) ;
% Input : r = spe c i f i e d radius
% Output : [x , y] = th e x- and y-co ordinat e s of dat a po int s
thet a=l inspace ( D , 2*pi , 1 0 0 ) ; % creat e vector theta
x = r * C O S (theta) ; % generat e x-co ordinat e s
y = r * s in (theta) ; % generat e y- c o ordinat e s
plot ( x , y) ; % plot the c i r c l e
axi s ( ' equal ' ) ; % set equal s cale on axe s
t it l e ( [ ' C ircle of radius r = ' , nurn2str ( r ) ] )
% put a t it l e with the value of r
Alternatively, you could select F i l e----> N ew----> Fu n ction M - F i l e and type all the
lines in the new file.
34 Tutorial Lessons
3. Now write and save the file under the name ci rclefn . m as follows:
• O n PCs: Select Save As . . . from t he F i l e menu. A dialog box should
appear . Type c ir c l e f n . m as the name of the document (usually, MAT
LAB automatically writes the name of the function in the document
n ame ) . Make sure the file is saved in the folder you want ( t he current
working fol der/ direct ory of MATLAB) . Click Save to save the file.
• On UNIX workstations: You are on your own to write and save the
file using the editor of your choice. After writing the file, quit the editor
to get back to MATLAB.
Comments:
• Note that a function file ( see previous page ) must begin with a function defini
tion line. To learn more about function files, refer to Section 4.2 on page 102.
• The argument of the t itle command in this function file is slightly compli
cated. It consists of two character strings. The first one is a s i m p le character
string, ' C i r c l e of radius r The secoml oue , num2str ( r ) , is a func
= ' .
tion that converts the numeric value of r to a string ( and hence the name
of the function ) . The square brackets create an array of the two strings by
concat enat ing them. You will learn more about this in Section 3 . 3 on page 77.
2.5 Lesson 5: Creating and Executing a Function File 35
EX E RC I S ES
1. O n- line help : Type� help f unct i on to get on-line help on funct i on . Read
through the help file.
2. Convert t e m p e r at ur e : Write a function that outputs a conversion table
for Celsius and Fahrenheit temperatures. The i nput of the function should
be two numbers: Ti and Tf , specifying the lower and upper range of the
table in Celsius. The output should be a two-column matrix: the first column
showing the temperature in Celsius from Ti to T1 in the increments of 1 o c
and the second column showing the corresponding temperatures in Fahrenheit.
To do this, (i) create a column vector C from Ti to T1 with the command
C= [Ti : Tf] ' , (ii) calculate the corresponding numbers in Fahrenheit using the
formula [F = t C + 32] , and (iii) make the final matrix with the command
temp= [C F] ; . Note that your output variable will be named temp.
3. Calculate factorials: Write a function f actorial to compute the factorial
n! for any integer n. The input should be the number n and the output should
be n ! . You might have to use a for loop or a while loop to do the calculation.
See Section 4.3.4 on page 1 1 4 for a quick description of these loops. (You
can use the built-in function prod to calculate factorials. For example, n! is
prod ( 1 : n) . In this exercise, however, do not use this function.)
4. Compute the cross product : Write a funct ion file cro s sprod t o com
pute the cross product of two vectors u and v, given u ( u 1 , u2 , u3 ) , v
= =
the function must be r and n and the output must be the sum of the series.
[See Exercise 4 of Lesson 2.]
6. Calculate the interest on your money: The interest you get at the end
of n years, at a fiat annual rate of r%, depends on how the interest is com
pounded. If the interest is added to your account k times a year, and the
principal amount you invested is X0 , then at the end of n years you would
have X = Xo ( 1 + );: ) k n amount of money in your account . Write a function
to compute the iuLeres L (X - Xo) on your account for t1 given X, n, r, and k .
Use the fnnction to fin<i t h P. clifference between the interest paid on $1000 at
the rate of 6% a year at the end uf five years if the interest is compounded
(i) quarterly (k 4) and (ii) daily (k = 365 ) . For screen output , use format
=
A n swers to Exercises
Some of the commands in the following functions might be too advanced for you
at this point . If so, look them up or ignore them for now.
Note: Once the function file is written and saved, you could run it to get a
temperature table showing conversion from, say 0 to 100 degrees Celsius. You
can either use ctof ( 0 , 100) or t able = ctof ( 0 , 100) to get the table. Now,
here is a note of caution. What happens if you type ctof ( [0 , 100] ) instead
of ctof ( 0 , 100) ? You will get an error message. The two commands are very
different although they differ just by a pair of square brackets. The function,
as written, expects two numbers in the input list , tinitial and tfinal. Therefore,
when you type ctof ( 0 , 100) , the function automatically sets t inial = 0 and
tf inal = 100. The computation proceeds accordingly. However, when you
type ctof ( [0 , 1 00] ) , then the input is a single vector [0 , 100] that has two
elements: 0 and 1 00. The function, however, is not written to accept a single
vector as its input and, therefore, the function gets confused and produces an
error message. The moral of the story is, there is a difference between a list of
numbers and a vector or an array as a single object . This is something that
you will have to master as you work in MATLAB .
Can you modify this function to check for negative input and noninteger input
before it computes the factorial?
2.5 Lesson 5: Creating and Executing a Function File 37
4 . f unct i on w = cro s sp r o d ( u , v) ;
% CROSSPROD : funct ion to c omput e w u x v f or vectors u & v
% call synt ax :
% w = cros sprod (u , v) ;
% - - - - - - - -----
if l ength (u) >3 I l ength (v) >3 % che ck if u OR v has > 3 e lement s
error ( ' Ask Eul er . Thi s cross product is beyond me . ' )
end
w = [u ( 2 ) *v ( 3 ) -u ( 3 ) *v ( 2 ) ; % f irst e lement of w
u ( 3 ) *v ( l ) -u ( l ) *v ( 3 ) ; % s e c o nd e lement of w
u ( l ) *v ( 2 ) -u ( 2 ) *v ( 1 ) ] ; % third e lement of w
Can you modify this function to check for 2-D vectors and set the third com
ponent automatically to zero?
5. function s = gseriessum (r , n) ;
% GSERIES SUM : funct i on to cal culat e the sum of a geome t r i c s e r i e s
% The s e r i e s i s 1 +r+r - 2+r - 3+ . . . . r - n (up t o n t h power ) .
% call synt ax :
% s = gser i e s sum ( r , n) ;
% ------------
nve c t o r = O :n; % create a vector from 0 t o n
s e r i e s = r . -nvector ; % creat e a vector of t e rms in the s e r i e s
s = s um ( s e r i e s ) ; % sum a l l e lement s of t h e vector ' s e r i e s ' .
D i rectional Explorations
Here are the next set o f lessons. These lessons are a little longer than the previous
ones and rely upon the basic skills you have already developed with the previous
lessons.
\·\
We strongly recommend that whenever t!1RIK MftN iPut'Ay1,'
c:::,_,·_�-"'-:' ""'· � -· - -4···.·-' ·:
Time Estimates
Lesson: 20 rninute<J
Exercises: 30 minutes
Method: We will take a simp le 3 x 3 matrix and use its row and columns indices
to manip ul at e the matrix, extract a vector, compute inner and outer product of
vectors, multiply the matrix with a vector, exponentiate the matrix, and exponen
tiat i ng each element of the matrix using an arra y operation.
Commen ts: Arrays are the backbone of MATLAB computation. The more
familiar you are with arrays, their manipulation and usage (Figs. 2.6 and 2 . 7) , the
better off you are in the world of MATLAB . You should look out for understanding
the following two concepts and acquiring associated computational skil ls.
• A 2-D array is a list o f numbers arranged in rows and columns. If you form
an array by wr it ing numbers in rows, all rows must have the same number
of entries. Same is true for columns. An array with m rows and n columns
is called an m x n array and it has a total of m n entries. An element of
·
the array is recognized by its location-its row number and column number.
These row and column identifiers are called indices of t he maLrix. Thus A( i, j)
refers to a specific element of matrix A located in the ith row and jth column .
These locations are unique. In MATLAB , you can also use a list of numbers
for the row and column indices to access more than one element of the matrix
at a time. This concept of using indices carries over to higher dimensional
arrays (discussed in Section 4.4) as well.
• You can use arrays for carrying out element-by-element operations (also called
army operations, see Section 3 . 2 for details ) as well ao; matrix operations . If A
is ::� squarP. arrily, then B = [A] * [A] or B = A2 it> very diiTerent from B =ra7j J .
The first one i s the ::>quare o f 1natr.ix A or thP. product of the matrix A witl1
itself, whereas the second one is an array made of squares of corresponding
elements of array A .
40 Tutorial Lessons
spaces or commas.
1 2 3
4 5 6
7 8 8
» A (2 , 3) Element A ij of matrix A is
accessed as A ( i , j ).
ans
» A (3 , 3) 9
Correcting any entry is easy
through indexing.
A =
1 2 3
4 5 6
7 8 9
4 5 6
7 8 9
» B = A (2 : 3 , : )
The colon by itself as a row or
column i ndex specifies all rows or
B =
columns of the matrix.
4 5 6
7 8 9
» B ( : , 2) = []
A row or a column of a matrix is
deleted by setting it to a null
B
vector [] .
=
4 6
7 9
>> A (1 2 3 ;
>> X A(1, : ) I
Matrices are transposed using the
single right-quote chara<.:tcr ('). Here
X "'
x is the transpose of the tirst row of A .
1
2
3
>> X I *X
Matrix o r vector products are well
1 2 3
2 4 6
3 6 9
>> A*x
Look how easy it is to multiply a
ans
vector w ith a matrix, compared with
=
14 Fortran or Pascal.
32
50
» A" 2
You can even e xp onenti ate a matrix
ans if it is a square matrix. A "2 is simply
A *A .
30 36 42
66 81 96
102 126 150
>> A . "2
When a dot precedes the arithmetic
ans operators *, " , and I, MATLAB
perform s array operation (element-by
1 4 9
element operati on ). So, A . " 2 produces
16 25 36
a matrix with elements ( a,j)2 .
49 64 81
E X E R C I S ES
A= [ � � ] ,
2 . Check some linear algebra rules:
• Is matrix addition commutative? Compute A+B and then B+A. Are
the results the same?
• Is matrix addition associative? Compute (A+B ) +C and then A+ (B+C)
in the order prescribed. Are the results the same?
• Is multiplication with a scalar distributive? Compute a (A+B ) and
aA+aB, taking a = 5, and show that the results are the same.
• Is multiplication with a matrix distributive? Compute A* (B+C)
[� � �]
See the on-line help o n these functions, i f required (e.g. , help eye) .
D =
[ 00 0
0
0
0
] '
E =
0 0 5
4. Create a big matrix with submatrices: The following matrix G is created
by putting matrices A, B, and C , given previously, on its diagonal. In how
many ways can you create this matrix using submatrices A, B, and C ( that
is , you are not allowed to enter the nonzero numbers explicitly) ?
2 6 0 0 0 0
3 9 0 0 0 0
0 0 1 2 0 0
G=
0 0 3 4 0 0
0 0 0 0 -5 5
0 0 0 0 5 3
5 . Manipulate a matrix: Do the following operations on matrix G created in
Exercise 4 _
• What do you get if you type G ( 1 3 ) and hit return? Can you explain how
MATLAB got that answer?
• What happens if you type G ( 12 , 1 ) = 1 and hit return?
2 . 7 Lesson 7: Working with Anonymous Functions 43
(x - 22)x + 100, and you need to evaluate this function at different values of x, plot
it over certain range of x, or find the zeros of f (x) . For such computations, you can
define f (x) as an anonymous function and evaluate it at any value ( s ) of x or use
this function as an input to other functions that need such input .
Time Estimates
Lesson: 25 minutes
Exercises: 40 minutes
Method:
The key to anonymous functions is the syntax of its creation:
fn_name = © ( list of input variables) function_expression
Here, the key clement is the symbol © that assigns a function handle to the defined
function. A function handle is a name given to a function by which you can call
it wherever you need it . In the anonymous function definition line, fn_name is
the name of the function or the handle of the function. The syntax © ( list of input
variables) is what tells MATLAB that you are defining an anonymous function here.
Comments:
• Anonymous functions are defined on the command line. They live in the
MATLAB workspace and are alive as long as the MATLAB session lasts.
• You can define a n anonymous fum:Llon with any number o f input varinblca.
• You must usc a vectorized expression ( using array operators ) for the function
if you intend to use an array as an input variable.
• You can use anonymous functions as input to other functions where appro
priate.
44 Tutorial Lessons
ans =
100
ans =
- Inf
Mat r i x mu s t be square .
>> f @ ( x) x . A 3 - 3 *x . A2 +x . * l og ( x - 1 ) + 1 0 0 ;
f (x) Redefine / by vectorizing the
expression (use array operators) . Now
ans = use it with an array argument.
Warn i ng : imagihary
argument s i gnored
Figure 2 . 8 : Lesson 7: Creating and evaluating anonymous func t ions in one variable.
2 . 7 Lesson 7: Working with Anonymous Funct ions 45
» f_many = [ f ( - 5 , x) f ( O , x) f (5 , x ) f { '* $ , x) J ;
·· >>
» g�id
» x l abe l ( 'x' )
>>
» 9 ® ( a , x ) a ( 4 ) *xA 3 + a ( 3 ) *xA 2 + a
ans =
- 14
>> g ® ( a , x) a ( 4 ) *x . A 3 + a ( 3 ) *x . A 2 + a ( 2 ) *x + a (1 ) ;
>> a Be carefu1 about passing functions of
two variables as input variable to
» fp lot (g ( a ) , [ - 2 2 ] )
functions that expect a function of a
single variable as input.
EX E R C I S ES
(b) Learn about the built-in function fzero that finds the zero of any given
function by typing help fzero. Now use fzero to find the zeros of f
accurately, making approximate initial guesses based on the plot you
made above.
(c) Use function quad to integrate f (x) from x 0 to x 1 and verify the
= =
X = Xo
(1 + r ) "
lOO
where x = accumulated amount , x0 = initial investment , r rate of annual
=
• How to manipulaLe expressions using symbolic math functions expand, s impl ify,
The command sym is the formal command for constructing objects of symbol
class. You can define one symbolic variable at a time using this command. You can
use additional qualifiers in the definition for the symb o lic object (e . g . , for restricting
a variable to be only real or positive) . The command syms is a shortcut to declare
several variables of the same class in one shot . We will use syms in this lesson. For
learning more about these commands and symbolic comp ut at ion, see C h apt er fl .
There are three basic skills to learn in symbolic computations: ( i ) How to define
expressions and do simple algebra with them ( multiply, divide, expand, factorize,
sirnpli�y, etc . ) . (ii) How to do simple c:alculus (differentiate, integrate, etc. ) . (iii)
How Lo solve equations-algebraic and differential cquatioul:l. Once yo u kuvw these
skills ( Figs . 2 . 10 and 2 . 1 1 ) , you c an meet most of your symbolic math calculation
requirements. The rest of it is about honing these skills , learning clever shortcuts
and substitutions , and establishing a personal rapport with the Symbolic Math
Toolbox for having fun with these calculations.
48 Tutorial Lessons
f =
f = (x + y)3 .
(x + y ) A3
>> expand ( z )
an s =
cos ( x ) * s in ( y ) + cos ( y ) * s in ( x)
ans I . e .,
. f'Illd Bz .
=
ax
cos ( x + y)
>> Z XX Find the second derivative of z
i d 82z
with respect t o x , I. . e . , ftn
Z XX =
ax 2 ·
- sin ( x + y)
VT 7! = XX + yf} .
>> ·
>> inner
be real and evaluate the inner
inner_produc t product . Since x and y are real,
T
XA2 + yA 2 v v = x2 + y2 .
>> syms a b
Solve two simultaneous algebraic
>> exp l 1 a*x + b *y -3 I ; equations for x and y :
-5 I ; ax + by - 3 0
>> exp2 I -x + 2 * a *y
-x + 2ay - 5 0
>> [x , y] = solve ( expl , exp2 )
X =
( 6 *a - 5 *b ) / ( 2 * aA2 + b )
y =
( 5 *a + 3 ) / ( 2 *aA2 + b)
( b* ( S * a + 3 ) ) / ( 2*aA2 + b) + ( a* ( 6 *a - 5 *b ) ) / ( 2 * a A 2 + b) -3
2 a a 6 a 5 b
more readable form.
(5 + 3) -
------------- - --------- - 5
2 a + b 2 ·a
EX E R C I S ES
X + 3y - Z 2
x-y+z 3
3x - 5 y 4.
4. Solving simultaneous linear equations: Solve the following nonlinear
algebraic equations simultaneously.
3x 3 + x 2 - 1 0
x4 - 10x 2 + 2 0.
5. Integrals: Find the following integrals:
(i) 100 e-x dx , (ii) 100 e-x2 dx , and (iii) lxo e-x2 sin(x)dx .
( b ) � + w 2 y = 0 , y (O ) = Yo and � (0) Vo . =
[First, use on-line help on dsol ve to see how to enter the differential equation
and the initial conditions as input to the function. Please note that this
function requires the differential operator ft to be denoted by D. Therefore,
the first differential equation will be written as D x + x - 2 0] . =
2 . 9 Lesson 9: Importing and Exporting Data 51
Method: We are going to work with three different kinds of files for reading data
into MATLAB 's workspace:
• Mat-file: This is MATLAB 's native binary format fi l e for saving data. Two
commands , s ave and l o ad make it particularly easy to save data into and
load data from these files. In this lesson, we will create such a file and save
some data into it in named variables. We will then use this file to load desired
data back into the MATLAB workspace (Fig. 2.12) .
• M - fi l e : If you have a text file containing data, or you want to write a text file
containing dat a that you would eventually like to read in MATLAB , m aki ng
it an M-file may be an excellent option. We will use the following M-file (a
script file ) i n this lesson. So, you should first create this file and save it as
Te m pData . m before you try the session shown in Fig. 2. 13.
% TempDat a : S cript f i l e c ontaining dat a o n monthly maximum t emperature
Sl_No = [ 1 : 12] ' ;
Month = char ( ' January ' , ' February ' , ' March ' , ' April ' , ' May ' , ' June ' , . . .
' July ' , ' August ' , ' Sept ember ' , ' O ctober ' , ' November ' , ' De c ember ' ) ;
Ave_Tmax = [22 25 30 34 36 30 29 27 24 23 2 1 20] ' ;
• Microsoft Excel file: You can import data from a Microsoft Excel spread
sheet into MATLAB. You can use MATLAB 's import wizard, invoked by
typing ui imp ort on the co mm and p ro mpt , or by c li ckin g on F i l e -r I m port
Data . MATLAB also provides a s p eci al function x l s r e ad for reading Excel's
spreadsheets as .xis files. In this ] p,q qon , W fl will usP x l s r e ad (see un-liue help
before using ) to read mixed data from an Excel file Tem p Data .xls. This file
contains column titles in the fir st row, numeric data in the first and third col
umn, and text data in the second column. You should first create this Excel
file before trying out the commands shown i n Fi g . 2 . 1 3 .
52 Tutorial Lessons
Name S i ze Byt e s Cl a s s At t r i bu t e s
f 1x2 7 54 char
r 1x2 0 1 1608 doub l e
theta 1x2 0 1 1608 double
X lx2 0 1 1608 doub le
y lx2 0 1 1608 double
Clear all variables, query to see no
>> c l e ar a ll
variables are present, load the
>> who s
datafile, and query the workspace
>> load xydat a
again to see the loaded variables.
>> who s
Name Size Byt es Class At t r ibut e s
f lx2 7 54 char
X lx2 0 1 1608 doub l e
>> plot ( x , y ) , axi s ( ' square ' ) ; The newly loaded variables aref, x
>> f and y. Use these variables to verify
the data they contain.
f =
>> c l ear al l
You can also load only selected
>> load xydat a X y
va.tiables from the Mat-file.
> > whos
>> c l e ar a l l
Delete a l l variables. Select xyda t a
» %Act i on in t;h£: :[ il e bJ,:"OIIJsgr
i n the cunent directory pane and
>> s i ze (x)
double-click x in the data browser to
load x in the worksp ac e .
ans
1 201
Figure 2 . 1 2 : Lesson 9: Saving and loading data with MATLAB's native binary data
format i s the easiest and most reliable. Examples of how to save data in a Mat-file
and how to load all or some variables from a Mat-file are shown here.
2 . 9 Lesson 9 : Importing and Export ing D at a 53
>> Month
> > months = char ( raw { 2 : 1 3 , 2 } ) ; U s e char to convert text data in the
second column of raw into a text array.
>> T = c e l l 2mat ( raw ( 2 : 1 3 , 3 ) ) ; .
Similarly, get the numeric data in the
third column into array T.
>> bar ( sn , T )
Now you can use the numeric arrays
sn and T as normal data. Here we
use them to create a b ar graph
(output shown on the left) .
Figure 2 . 13: Lesson 9: Loading data typed as text in a script file is eas y and re l iable .
Yo u can also import data from other MATLAB readable file formats using File -t
EX E R C I S ES
1 . Working with binary Mat-files: Create a matrix S with its columns cre
ated from the terms in the sine series:
x3 x5 x1
sin x = x - - + - - - +
3! 5! 7!
· · ·
First create a column vector x between 0 and 211' with the command
x l i n s p a c e ( 0 , 2*pi , 1 0 1 ) ' . Now compute
A [x -x . - 3/6 x . - 5 / 1 20 -x . - 7/f actorial (7 ) ] ;
• Save matrix A and vector x in a Mat-file.
• Select the Mat-file in the C u rrent D i rectory pane and then double-click
on the variable x visible in the file contents pane below the directory
pane to load x in the workspace. This action is equivalent to typing
load Mat-file x .
• Double-click o n the variable x visible in the workspace pane t o open the
Va ri a b l e Ed itor and inspect the entries of x. You can edit any value if
you wish.
• Plot sin(x) with the command plot (x , s in (x) ) , grid , hold on.
• Now import the image data in an array S from the file s i n eseries p l ot .j peg
you created earlier. Check the size of S to verify that it is a 3-D matrix
(corresponding to three colors-red, green, and blue) .
• Reconstrnct thP image with the command image ( S ) .
• Try reading some other JPEG file that you may have (a picture perhapR) ,
store the data in some variable, and reconstruct the picture with the
image command. You have to play with setting the axes correctly to get
the image right .
2 . 1 0 Lesson 1 0 : Working with Files and Directories 55
Time Estimates
Lesson: 15 minutes
Exercises: 20 minutes
Method: MATLAB includes several menu-driven features that make file navi
gation much easier ( compared with the earlier versions ) . You will explore some
of these features in the exercises. In the lesson, you will learn commands that
pretty much do the same thing from the command line. The commands that you
will use are pwd . dir , l s , cd , what , makedir, etc . Please go ahead and try the
commands shown in Fig. 2. 14.
Commen ts:
• It is important to know which directory you are currently in because any files
you write or save will, by default , be saved into the current directory.
• You may have your M-files-scripts or functions-stored in a different direc
tory than the current directory. In that case, MATLAB will not be able to
access your files by itself. You will have to either change the current directory
to the directory where your files are or include your directory in the M AT L AB
path. The path is a MATLAB variable that contains the full path names of
all directories that MATLAB can access during a work session. It is created
during MATLAB installation. You can, however, modify it . See on-line help
on path.
• You can create new directories from within the MATLAB command winrlow.
You can also copy or move files from one directory to another with MATLAB
commands ( c opyf i l e , movef ile) . See on-liml h Alp on pwd , cd , mkd i r ,
rmdir , c opyf i l e , movef ile , what , and whi c h .
56 Tutorial Lessons
ans ·=c·
C : \mat l ab\work
c i rcle . m c i r c l e fn . m
mkd i r
Make a new directory named
» lessonl Odi r
lesso n 1 Odir. List the contents of
» ls
the directory again.
c i rc l e . m c irclefn . m l e s s on l O d i r
xyda t a f i l e . ma t
x:ydatafile
C: \matlab\work
EX E R C I S ES
1 . Working with directories: Infor mat i on about the current directory's name
and its contents are available in the MATLAB desktop. Look at the command
win dow toolbar. There is a small window that shows the name of the current
directory, along wit h its p at h . For example, Fig. 2 . 1 5 shows that the current
directory is /Users/rud ra prajDocu ments/MATLAB (this is on a Mac; on a
PC it may be C : \ D o c u me n t s a n d Setti ngs \ . . . \ M y Dcu ments\ MATLAB ) .
A s the path indic�J,t es, i t is inside the M ATLAB directory.
The current directory is also displayed in a separate subwindow to the
left of the command window. If it is not visible, click on the C u rrent D i rectory
tab. This subwindow also lists the contents of the current directory.
Current Directory
Subwindow
File
Details of the
Selected File » ..
h;>lot.pd&: ltJ.l1oi§JidW.j,e>a ,u,� .�._...
lUI� dAU4dNP:lot:, j:p.g
lUJIOli!t-o lfirAntiNPl«.�ift
» 'olbB:ti
In this exercise, the idea is to use the CUI (graphical user interface ) buttons in
the MATLAB desktop to change directories, see their contents, create direc
tories , etc . These are the tasks that you did using commands in the tutorial
lesson (Fi!'!;. 2 . 14) .
• Go to the current directory subwindow and ch an ge the din�r. t ory using the
Now you know your way around t he directories using mouse clicks.
58 Tutorial Lessons
Time Estimates
Lesson: 20 minut es
Exercises: 30 minutes
4. Voila! You should see a nice , colorful HTML file l ike the one shown in Fig. 2.16.
A Splral Plot
90
I SO
240 •
'-�------------��------------------------�-L�
\r�-.,---------------....d.J;LI..-�-�����----��....-.,.-q.-·;-':
="i
Figure 2 .16 : An HTML file created by the MATLAB publisher from the script file
s p i ra l p lot . m shown on the previous page.
5. Now see the on-line help on publi sh and use this command to publish a Word
document. (if you are on a PC) .
60 Tutorial Lessons
EX E RC I S ES
1 . Using the publisher from the editor window: Open the file s p i ra l pl ot . m
that you created while working with Lesson 1 1 . You can open the file by
following F i l e ---> O p en from the menu or from the command window with
either edit spiralplot . m or open spiralpl ot . m. Once the file is open in
the editor, select P u b l ish from the F i l e menu (see Fig. 2 . 1 7) of the editor
window, or click on the publish icon (next to the printer icon in the menu
bar) . The script open in the editor will be published to an HTML file and
MATLAB will automatically open the HTML file for your perusal.
5n Pa_tfl_,
flra.ft;t..IKU-
••gtSttu;>,.. Cell e1.ecut1011 buttons
Prim
l?/,�,: s:��ti.Yi.
••.
1 [UUU/.J\IlJSf){fitlp1ot.m
2 /l.lst1S/.-IMA.Tt.A!:Ibe.i#.un
l i-U�(fs$/.,4gr-A¢'1iaJW.o,Jn �· 22
4 rtiuuj•...mfi!e5}dtdt.m 23
£xltMATI.AB XQ i 24
25
i 26
27
Figure 2. 17: The MATLAB publisher can be invoked from the F i l e menu when the
script is open in the editor window.
2. What are those cells? A cell, in a script file, is a set of commands enclosed
between two cell separators (lines that start with %%) . You can execute a cell
independent of other cells. You can also execute one cell and then the next
by simply clicking on the cell execution option buttons (see Fig. 2 . 1 7) in the
toolbar of the editor. Move your mouse on these buttons to see what each
one does.
Now , open the s p i ra l pl ot . m file again (if you have closed it) in the editor
and add the fo l lowi ng two cells at the end of the file. You can just type %%
t o start a new cell or click on the I nsert C e l l D ivider button in the toolbar to
in:>crt it.
%% P o l ar t o Cart e s i an c o ordinat e s
x = r . * c o s ( theta) ;
2 . 1 1 LeRRon 1 1 : Publishing Reports 61
y = r . * s in (theta) ;
plot (x , y ) , axi s ( ' equal ' )
%% Polar t o Cart e s i an with pol2cart
[xx , yy] = p o l 2 cart (theta , r ) ;
plot ( xx , yy ) , axi s ( ' equal ' )
Now experiment with executing one cell at a time by clicking on the appropri
ate cell execution button in the toolbar. If you are happy, publish the script
again. The newly published document should have three plots, one polar and
two Cartesian, showing the same spiral.
3. Just a bit of fun with formatting the script : It is possible to format your
report to make it look better. In particular, you can introduce bold text,
monospaced text, bulleted list , and nicely formatted mathematical equations.
Out of these, formatting equations is something that definitely improves the
readability of your report. However, it also requires learning a little bit of
:fb.TEX . 1 See Section 4. 5 on page 129 for more discussion.
Let us introduce a bit of formatting in the script file so that it shows
equations for the spiral and polar to Cartesian conversion formulas as math
ematical equations. Edit spi ra l p l ot . m so that it now looks like the following
( note, there are basically two changes for the mathematical equations ) .
%% Pub l i shing Report s - A S impl e Exampl e
%% A Spiral Plot
% Let us plot a spiral given by
%%
% $$r ( \theta) = e - {-\frac{\theta} { l O} } , \quad 0 \ l e \theta\le 10\pi$$
%% Create vectors theta and r
Now save the file and publish it again. Look at the output. It should have
nice formatted equations that look like
and
X = T COS 8, y = T sin 8.
4 . Invoke helpdesk, do a search for publish, and read ( and watch videos ) as
much as you would like to learn about the publisher.
1 If you have not heard of lffiTEX , it's time to Google. For a minimal list of lffi-'IEX commands ,
see Table 4.1 on page 131 .