| eig | eigenvalues and eigenvectors |
| chol | cholesky factorization |
| svd | singular value decomposition |
| inv | inverse |
| lu | LU factorization |
| qr | QR factorization |
| hess | hessenberg form |
| schur | schur decomposition |
| rref | reduced row echelon form |
| expm | matrix exponential |
| sqrtm | matrix square root |
| poly | characteristic polynomial |
| det | determinant |
| size | size |
| norm | 1-norm, 2-norm, F-norm, <infinity>-norm* |
| cond | condition number in the 2-norm |
| rank | rank |
MATLAB functions may have single or multiple output arguments. For example,
y = eig(A), or simply eig(A)
[U,D] = eig(A)
10. Command line editing and recall
The command line in MATLAB can be easily edited. The cursor can be
positioned with the left/right arrows and the Backspace (or Delete)
key used to delete the character to the left of the cursor. Other
editing features are also available. On a PC try the Home, End, and
Delete keys; on other systems see help cedit or type cedit.
A convenient feature is use of the up/down arrows to scroll through the stack of previous commands. One can, therefore, recall a previous command line, edit it, and execute the revised command line. For small routines, this is much more convenient that using an M-file which requires moving between MATLAB and the editor (see sections 12 and 14). For example, flopcounts (see section 15) for computing the inverse of matrices of various sizes could be compared by repeatedly recalling, editing, and executing
a = rand(8); flops(0), inv(a); flopsm=2; n=3; x=0:.01:2*pi; y=sin(m*x); z=cos(n*x); plot(x,y,x,z)
The expression 1:5 (met earlier in for statements) is actually
the row vector [1 2 3 4 5]. The numbers need not be integers nor the
increment one. For example,
0.2:0.2:1.2[0.2, 0.4, 0.6, 0.8, 1.0, 1.2], and
5:-1:1[5 4 3 2 1].
The following statements
will, for example, generate a table of sines. Try it.
sin operates entry-wise, it produces a vector
y from the vector x.
The colon notation can be used to access submatrices of a matrix. For example,
A(1:4,3)- A(:,3)
A(1:4,:) is the first four rows.
Arbitrary integral vectors can be used as subscripts:
A(:,[2 4])A(:,[2 4 5]) = B(:,1:3)Columns 2 and 4 of A can be multiplied on the right by the 2-by-2 matrix [1 2;3 4]:
A(:,[2,4]) = A(:,[2,4])*[1 2;3 4]
If x is an n-vector, what is the effect of the statement
x = x(n:-1:1)? Try it.
To appreciate the usefulness of these features, compare these MATLAB
statements with a Pascal, FORTRAN, or C routine to effect the same.
12. M-files
MATLAB can execute a sequence of statements stored on diskfiles. Such files are called "M-files" because they must have the file type of ".m" as the last part of their filename. Much of your work with MATLAB will be in creating and refining M-files.
There are two types of M-files: script files and function files.
Script files. A script file consists of a sequence of normal
MATLAB statements. If the file has the filename, say, rotate.m,
then the MATLAB command rotate will cause the statements in the file to be executed. Variables in a script file are global and will
change the value of variables of the same name in the environment of
the current MATLAB session.
Script files are often used to enter data into a large matrix; in
such a file, entry errors can be easily edited out. If, for example,
one enters in a diskfile data.m
data will cause the assignment given in data.m to be carried out.
An M-file can reference other M-files, including referencing itself recursively.
Function files. Function files provide extensibility to MATLAB. You can create new functions specific to your problem which will then have the same status as other MATLAB functions. Variables in a function file are by default local. However, version 4.0 permits a variable to be declared global.
We first illustrate with a simple example of a function file.
A more general version of this function is the following:
This should be placed in a diskfile with filename
randint.m
(corresponding to the function name). The first line declares the function name, input arguments, and output arguments; without this line the file would be a script file. Then a MATLAB statement
z = randint(4,5),
Note that use of nargin ("number of input arguments") permits one to set a default value of an omitted input variable---such as a and b in the example.
A function may also have multiple output arguments. For example:
Once this is placed in a diskfile
stat.m, a MATLAB command
[xm, xd] = stat(x), for example, will assign the mean and
standard deviation of the entries in the vector x to xm and xd, respectively. Single assignments can also be made with a function having multiple output arguments. For example, xm = stat(x)
(no brackets needed around xm) will assign the mean of x to xm.
The % symbol indicates that the rest of the line is a comment; MATLAB will ignore the rest of the line. However, the first few comment lines, which document the M-file, are available to the on-line help facility and will be displayed if, for example, help stat is entered. Such documentation should always be included in a function file.
This function illustrates some of the MATLAB features that can be used
to produce efficient code. Note, for example, that x.^2 is the matrix of squares of the entries of x, that sum is a vector function (section 8), that sqrt is a scalar function (section 7), and that
the division in sum(x)/m is a matrix-scalar operation.
The following function, which gives the greatest common divisor of two
integers via the Euclidean algorithm, illustrates the use of an error
message (see the next section).
Some more advanced features are illustrated by the following function.
As noted earlier, some of the input arguments of a function---such as
tol in the example, may be made optional through use of nargin
("number of input arguments"). The variable nargout can be similarly used. Note that the fact that a relation is a number (1 when true; 0 when false) is
used and that, when while or if evaluates a relation,
"nonzero" means "true" and 0 means "false". Finally, the MATLAB function feval permits one to have as an input variable a
string naming another function.
Some of MATLAB's functions are built-in while others are distributed
as M-files. The actual listing of any M-file---MATLAB's or your
own---can be viewed with the MATLAB command . Try entering , , and
.
13. Text strings, error messages, input
Text strings are entered into MATLAB surrounded by single quotes. For
example,
assigns the given text string to the variable s.
Text strings can be displayed with the function disp. For example:
Error messages are best displayed with the function error
since when placed in an M-File, it causes execution to exit the M-file.
In an M-file the user can be prompted to interactively enter input data with
the function input. When, for example, the statement
is encountered, the prompt message is displayed and execution pauses while the
user keys in the input data. Upon pressing the return key, the data is
assigned to the variable iter and execution resumes.
14. Managing M-files
While using MATLAB one frequently wishes to create or edit an M-file and then return to MATLAB. One wishes to keep MATLAB active while editing a file since otherwise all variables would be lost upon exiting.
This can be easily done using the !-feature. If, while in MATLAB, you precede it with an !, any system command---such as those for editing, printing, or copying a file---can be executed without exiting MATLAB. If, for example, the system command ed accesses your editor, the MATLAB command
will let you edit the file named rotate.m using your local editor. Upon leaving the editor, you will be returned to MATLAB just where you left it.
As noted in section 1, on systems permitting multiple processes, such as one running Unix, it may be preferable to keep both MATLAB and your local editor active, keeping one process suspended while working in the other. If these processes can be run in multiple windows, as on a workstation, you will want to keep MATLAB active in one window and your editor active in another.
You may consult your instructor or your local computing center for details of the local installation.
Version 4.0 has many debbugging tools. See help dbtype and
references given there.
When in MATLAB, the command dir will list the contents of the current
directory while the command what will list only the M-files in the
directory. The MATLAB commands delete and type can be used to
delete a diskfile and print a file to the screen, respectively, and chdir
can be used to change the working directory. While these commands may
duplicate system commands, they avoid the use of an !.
M-files must be accessible to MATLAB. On most mainframe or
workstation network installations, personal M-files which are stored in a
subdirectory of one's home directory named matlab will be
accessible to MATLAB from any directory in which one is working. See
the discussion of MATLABPATH in the User's Guide for further information.
15. Comparing efficiency of algorithms: flops and etime
Two measures of the efficiency of an algorithm are the number of floating
point operations (flops) performed and the elapsed time.
The MATLAB function flops keeps a running total of the flops
performed. The command flops(0) (not flops = 0!) will
reset flops to 0. Hence, entering flops(0) immediately before
executing an algorithm and flops immediately after gives the
flop count for the algorithm.
The MATLAB function clock gives the current time accurate to a hundreth
of a second (see help clock). Given two such times t1 and
t2, etime(t2,t1) gives the elapsed time from t1 to t2.
One can, for example, measure the time required to solve a given linear system
A x = b using Gaussian elimination as follows:
x = inv(A)*b;. Try it.
Version 4.0 has the more convenient tic and toc.
It should be noted that, on timesharing machines, etime may not
be a reliable measure of the efficiency of an algorithm since the rate
of execution depends on how busy the computer is at the time.
16. Output format
While all computations in MATLAB are performed in double precision, the format of the displayed output can be controlled by the following commands.
format short | fixed point with 4 decimal places (the default) |
format long | fixed point with 14 decimal places |
format short e | scientific notation with 4 decimal places |
format long e | scientific notation with 15 decimal places |
Once invoked, the chosen format remains in effect until changed.
The command format compact will suppress most blank lines allowing more
information to be placed on the screen or page.
It is independent of the other format commands.
17. Hardcopy
Hardcopy is most easily obtained with the diary command. The command
diary filename diary) until one gives the
command diary off; the command diary on will cause writing
to the file to resume, etc. When finished, you can edit the file as desired
and print it out on the local system. The !-feature (see section 14) will
permit you to edit and print the file without leaving MATLAB.
plotdemo.
Planar plots.
The plot command creates linear x-y plots; if x and y are vectors of
the same length, the command plot(x,y) opens a graphics window and draws
an x-y plot of the elements of x versus the elements of y. You can, for
example, draw the graph of the sine function over the interval -4 to 4 with
the following commands:
- x = -4:.01:4; y = sin(x); plot(x,y)
Try it. The vector x is a partition of the domain with meshsize 0.01 while
y is a vector giving the values of sine at the nodes of this partition
(recall that sin operates entrywise).
When in the graphics screen, pressing any key will return you to the command
screen while the command shg (show graph) will then return you to the
current graphics screen. If your machine supports multiple windows with a
separate graphics window, you will want to keep the graphics window
exposed---but moved to the side---and the command window active.
As a second example, you can draw the
graph of y = e^(-x^2) over the interval -1.5 to 1.5 as follows:
Note that one must precede ^ by a period to ensure that it operates
entrywise (see section 3).
Plots of parametrically defined curves can also be made. Try, for example,
The command grid will place grid lines on the current graph.
The graphs can be given titles, axes labeled, and text placed within the graph with the following commands which take a string as an argument.
| title | graph title |
| xlabel | x-axis label |
| ylabel | y-axis label |
| gtext | interactively-positioned text |
| text | position text at specified coordinates |
For example, the command
gives a graph a title. The command gtext('The Spot') allows a mouse
or the arrow keys to position a crosshair on the graph, at which the text
will be placed when any key is pressed.
By default, the axes are auto-scaled. This can be overridden by the command
axis. If axis(c) sets the axis scaling to the precribed limits.
By itself, axis freezes the current scaling for subsequent graphs;
entering axis again returns to auto-scaling.
The command axis('square') ensures that the same scale is used on both
axes. In version 4.0, axis has been significantly changed; see
help axis.
Two ways to make multiple plots on a single graph are illustrated by
and by forming a matrix Y containing the functional values as
columns
Another way is with hold. The command hold freezes the current
graphics screen so that subsequent plots are superimposed on it.
Entering hold again releases the "hold." The commands
hold on and hold off are also available in version 4.0.
One can override the default linetypes and pointtypes. For example,
renders a dashed line and dotted line for the first two graphs while for the
third the symbol + is placed at each node. The line- and mark-types are
-), dashed (\tt--). dotted (:),
dashdot (-.)
.), plus (+), star (*),
circle (o), x-mark (x)help plot for line and mark colors.
The command subplot can be used to partition the screen so that
up to four plots can be viewed simultaneously. See help subplot.
Graphics hardcopy [The features described in this
subsection are not available with the Student Edition of Matlab. Graphics hardcopy can be obtained there only with a screen dump: Shift-PrtScr.]
A hardcopy of the graphics screen can be most easily obtained with the MATLAB
command print. It will send a high-resolution copy of the current
graphics screen to the printer, placing the graph on the top half of the page.
In version 4.0 the meta and gpp commands described below have been
absorbed into the print command. See help print.
Producing unified hard copy of several plots requires more effort. The Matlab
command meta filename stores the current graphics screen in a file
named filename.met (a "metafile") in the current directory. Subsequent
meta (no filename) commands append a new current graphics screen to
the previously named metafile. This metafile---which may now contain several
plots---may be processed later with the graphics post-processor (GPP) program
to produce high-resolution hardcopy, two plots per page.
The program GPP (graphics post-processor) is a system command, not a MATLAB command. However, in practice it is usually involked from within MATLAB using the "!" feature (see section 14). It acts on a device-independent metafile to produce an output file appropriate for many different hardcopy devices.
The selection of the specific hardcopy device is made with
the option key "/d". For example, the system commands
will produce files filename.ps and filename.jet suitable for
printing on, respectively, PostScript and HP LaserJet printers. They can be
printed using the usual printing command for the local system---for example,
lpr filename.ps on a Unix system. Entering the system command
gpp with no arguments gives a list of all supported hardcopy devices. On a
PC, most of this can be automated by appropriately editing the file
gpp.bat distributed with MATLAB.
3-D mesh plots.
Three dimensional mesh surface plots are drawn with the function mesh.
The command mesh(z) creates a three-dimensional perspective plot of the
elements of the matrix z. The mesh surface is defined by the z-coordinates
of points above a rectangular grid in the x-y plane. Try mesh(eye(10)).
To draw the graph of a function z = f(x,y) over a rectangle, one first
defines vectors xx and yy which give partitions of the sides of the
rectangle. With the function meshdom (mesh domain; called
meshgrid in version 4.0) one then creates
a matrix x, each row of which equals xx and whose column length is the
length of yy, and similarly a matrix y, each column of which equals yy,
as follows:
One then computes a matrix z, obtained by evaluating f entrywise over the
matrices x and y, to which mesh can be applied.
You can, for example, draw the graph of z = e^(-x^2-y^2) over the
square [-2,2]\times[-2,2] as follows (try it):
One could, of course, replace the first three lines of the preceding with
You are referred to the User's Guide for further details regarding mesh.
In version 4.0, the 3-D graphics capabilities of MATLAB have been
considerably expanded. Consult the on-line help for plot3, mesh,
and surf.