%%%%%%%%%%%%%%%%%%%%%%%%%%%   primer.tex    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                                                                          %
%   This is the (plain) TeX source for the third edition of the            %
%   "MATLAB Primer" (39 pages).  It is based of version 4.0/4.1 of         %
%   MATLAB.  To obtain a copy of "Primer" for your review, you can "TeX"   %
%   this file to produce a "dvi" file  which you can use to print a        %
%   hardcopy.  If you have difficulty producing a copy, contact me at the  %
%   address below and I will send you a hard copy.                         %
%                                                                          %
%   The MATLAB Primer was written to help students begin to use MATLAB.    %
%   It is intended to serve as an introduction to and *not* a manual for   %
%   MATLAB.  While its primary purpose is for use in courses which         %
%   require use of MATLAB, it could, of course, serve as an introduction   %
%   to MATLAB for others.                                                  %
%                                                                          %
%   Extensive experience has shown that the Primer, along with the on-line %
%   help facility, usually suffice for the students to use MATLAB in a     %
%   classroom setting.  It assumes, however, that the complete MATLAB      %
%   User's Guide is available for review at certain locations -- such as   %
%   consulting desks, terminal rooms, computing laboratories, and the      %
%   reference desk in the library -- as a source of more in-depth          %
%   information.                                                           %
%                                                                          %
%   The most convenient method of distribution seems to be through a       %
%   local copy center where the student can purchase it for a few dollars. %
%   Students usually prefer the convenience and durability of a            %
%   "spiral" bound copy with covers, copy center style.                    %
%                                                                          %
%   The MATLAB Primer may be distributed as desired subject to the         %
%   following conditions:                                                  %
%                                                                          %
%   1. It is not altered in any way, except possibly adding an addendum    %
%      giving information about the local computer installation or         %
%      MATLAB toolboxes.                                                   %
%                                                                          %
%   2. It, or any part thereof, is not used as part of a document          %
%      distributed for a commercial purpose.                               %
%                                                                          %
%   In particular, it may be distributed via a local copy center or        %
%   bookstore.  You may use this statement (or the second page or the      %
%   Primer) for copyright clearance.                                       %
%                                                                          %
%   Suggestions for improving Primer are always most welcome.              %
%   Please send them to:                                                   %
%                                                                          %
%       Kermit Sigmon                    sigmon@math.ufl.edu               %
%       Department of Mathematics        sigmon@ufpine.bitnet              %
%       University of Florida                                              %
%       Gainesville, Florida  32611      12-93                             %
%                                                                          %
%%%%%%%%%%%%%%%%%%%%%%%%%%%   primer.tex   %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\magnification=\magstep1  \parindent=16pt  \parskip=\smallskipamount
\vbadness=2500
\font\sc=cmcsc10                 
\font\scten=cmcsc10 at 10truept  
\font\rmten=cmr10 at 10truept    
\font\bften=cmbx10 at 10truept   
\font\rmbig=cmbx10 scaled\magstep5

\def\section#1{\leftline{\bf #1.}\par}
\def\disp#1 {\itemitem{}{#1}\par\noindent}
\def\newpage{\vfill\eject} \def\newline{\hfill\break} \def\nl{\hfill\break}
\def\xxx{\hphantom{xxx}}
\def\power{\widehat{\hphantom{x}}\,}

{\nopagenumbers
\topskip 4.8cm
\centerline{\rmbig MATLAB Primer}
\centerline{\bf Third Edition}
\vskip 1.5cm
\centerline{Kermit Sigmon}
\centerline{Department of Mathematics}
\centerline{University of Florida}
\vfill
\centerline{Department of Mathematics $\bullet$ University of Florida
            $\bullet$ Gainesville, FL  32611}
\centerline{sigmon@math.uf\/l.edu}
% $\bullet$ sigmon@ufpine.bitnet}
\centerline{Copyright \copyright 1989, 1992, 1993 by Kermit Sigmon}
\eject}
\pageno=-1
\centerline{\sc On the Third Edition}
\bigskip
The Third Edition of the MATLAB Primer is based on version 4.0/4.1
of MATLAB.  While this edition reflects an extensive general revision
of the Second Edition, most significant is the new information to help
one begin to use the major new features of version 4.0/4.1, the sparse
matrix and enhanced graphics capabilities.

The plain \TeX\ source and corresponding PostScript file of the latest
printing of the MATLAB Primer are always available via anonymous ftp
from:

\noindent
Address: {\tt math.ufl.edu}\qquad Directory: {\tt pub/matlab}
            \qquad Files: {\tt primer.tex, primer.ps}

\noindent You are advised to download anew each term the latest
printing of the Primer since minor improvements and corrections may
have been made in the interim.  If ftp is unavailable to you, the
Primer can be obtained via {\tt listserv} by sending an email message
to {\tt listserv@math.ufl.edu} containing the single line 
{\tt send matlab/primer.tex}.

Also available at this ftp site are both English 
({\tt primer35.tex, primer35.ps}) and Spanish 
({\tt primer35sp.tex, primer35sp.ps}) versions of the Second Edition
of the Primer, which was based on version 3.5 of MATLAB.  The Spanish
translation is by Celestino Montes, University of Seville, Spain.
A Spanish translation of the Third Edition is under development.

Users of the Primer usually appreciate the convenience and durability
of a bound copy with a cover, copy center style.

\noindent (12-93)
\bigskip\bigskip
\hrule
\bigskip
$$\vbox{\leftline{Copyright \copyright 1989, 1992, 1993 by Kermit Sigmon}
\narrower
\noindent The MATLAB Primer may be distributed as desired
subject to the following conditions:
\item{1.} It may not be altered in any way, except possibly adding an
       addendum giving information about the local computer installation
       or MATLAB toolboxes.
\item{2.} It, or any part thereof, may not be used as part of a document
       distributed for a commercial purpose.

\noindent In particular, it may be distributed via a local copy center
or bookstore. 
\vskip 1cm
\centerline{Department of Mathematics $\bullet$ University of Florida
            $\bullet$ Gainesville, FL  32611}
\centerline{sigmon@math.uf\/l.edu}
% $\bullet$ sigmon@ufpine.bitnet}
}$$
\eject
\centerline{\sc Introduction}

\bigskip
MATLAB is an interactive, matrix-based system for scientific and engineering 
numeric computation and visualization.  You can solve complex numerical
problems in a fraction of the time required with a programming
language such as Fortran or C.
The name MATLAB is derived from MATrix LABoratory.
\bigskip
The purpose of this Primer is to help you begin to use MATLAB. 
It is not intended to be a substitute for the User's Guide and
Reference Guide for MATLAB.  The Primer can best be used hands-on.
You are encouraged to work at the computer as you read  the Primer and
freely experiment with examples.  This Primer, along with the on-line
help facility, usually suffice for students in a class requiring use
of MATLAB.
\bigskip
You should liberally use the on-line help facility for more detailed 
information.  When using MATLAB, the command {\tt help \it functionname}
will give information about a specific function. For example, the
command {\tt help eig} will give information about the eigenvalue
function {\tt eig}.  By itself, the command {\tt help} will display a
list of topics for which on-line help is  available; then 
{\tt help \it topic} will list those specific functions under this
topic for which help is available.  The list of functions in the last
section of this Primer also gives most of this information.  You can
preview  some of the features of MATLAB by first entering the command 
{\tt demo} and then selecting from the options offered.
\bigskip
The scope and power of MATLAB go far beyond these notes.  Eventually
you will want to consult the MATLAB User's Guide and Reference Guide.
Copies of the complete documentation are often available for review at
locations such as consulting desks, terminal rooms, computing labs,
and the reserve desk of the library. Consult your instructor or your
local computing center to learn where this documentation is located at
your institution.   
\bigskip
MATLAB is available for a number of environments: Sun/Apollo/VAXstation/HP
workstations, VAX, MicroVAX, Gould, PC and AT compatibles, 80386 and 80486
computers,  Apple Macintosh, and several parallel machines.  There is a
relatively inexpensive Student Edition available from Prentice Hall
publishers.  The information in these notes applies generally to all of
these environments.
\bigskip
MATLAB is licensed by The MathWorks, Inc., 
24 Prime Park Way, Natick, MA  01760, (508)653-1415,
Fax: (508)653-2997, Email: info@mathworks.com.

\footnote{}{\rmten Copyright \copyright 1989, 1992, 1993 by Kermit Sigmon}
\newpage
\centerline{\sc Contents}
\vskip 0.6cm

\def\ln#1{\leftline{#1}\bigskip}
\def\x{\hphantom{x}}
\rightline{Page}\medskip
\ln{\x 1. Accessing MATLAB \dotfill\ 1}
\ln{\x 2. Entering matrices \dotfill\ 1}
\ln{\x 3. Matrix operations, array operations \dotfill\ 2}
\ln{\x 4. Statements, expressions, variables; saving a session \dotfill\ 3}
\ln{\x 5. Matrix building functions \dotfill\ 4}
\ln{\x 6. For, while, if --- and relations \dotfill\ 4}
\ln{\x 7. Scalar functions \dotfill\ 7}
\ln{\x 8. Vector functions \dotfill\ 7}
\ln{\x 9. Matrix functions \dotfill\ 7}
\ln{10. Command line editing and recall \dotfill\ 8}
\ln{11. Submatrices and colon notation \dotfill\ 8}
\ln{12. M-files: script files, function files \dotfill\ 9}
\ln{13. Text strings, error messages, input \dotfill\ 12}
\ln{14. Managing M-files \dotfill\ 13}
\ln{15. Comparing efficiency of algorithms: flops, tic, toc \dotfill\ 14}
\ln{16. Output format \dotfill\ 14}
\ln{17. Hard copy \dotfill\ 15}
\line{18. Graphics \dotfill\ 15}
\line{\qquad\qquad planar plots (15), hardcopy (17), 3-D line plots (18)\hfil} 
\ln{\qquad\qquad mesh and surface plots (18), Handle Graphics (20)\hfil}
\ln{19. Sparse matrix computations \dotfill\ 20}
\ln{20. Reference \dotfill\ 22}

\newpage

\pageno=1
\section{1. Accessing MATLAB}
\smallskip
On most systems, after logging in one can enter MATLAB with the system
command {\tt matlab} and exit MATLAB with the MATLAB command
{\tt quit} or {\tt exit}.  However, your local installation may permit
MATLAB to be accessed from a menu or by clicking an icon.

On systems permitting multiple processes, such as a Unix system or 
MS Windows, you will find it convenient, for reasons discussed in
section 14, to keep both MATLAB and your local editor active. 
If you are working on a platform which runs processes in multiple
windows, you will want to keep MATLAB active in one window and your
local editor active in another.

You should  consult your instructor or your local computer center for
details of the local installation.  

\bigskip
\section{2. Entering matrices}

MATLAB works with essentially only one kind of object---a rectangular 
numerical matrix with possibly complex entries; all variables represent
matrices.  In some situations, 1-by-1 matrices are interpreted as scalars
and matrices with only one row or one column are interpreted as vectors.

Matrices can be introduced into MATLAB in several different ways:
\smallskip
\itemitem{$\bullet$}{Entered by an explicit list of elements,}
\itemitem{$\bullet$}{Generated by built-in statements and functions,}
\itemitem{$\bullet$}{Created in a diskfile with your local editor,}
\itemitem{$\bullet$}{Loaded from external data files or applications
             (see the User's Guide).} 

\smallskip\noindent
For example, either of the statements
\disp{\tt A = [1 2 3; 4 5 6; 7 8 9]}
and
\disp{\tt A = [ \nl
        1  2  3 \nl
        4  5  6 \nl
        7  8  9 ]}
creates the obvious 3-by-3 matrix and assigns it to a variable $A$.  Try it.
The elements within a row of a matrix may be separated by commas as well as
a blank.  When listing a number in exponential form (e.g. 2.34e-9),
blank spaces must be avoided.

MATLAB allows complex numbers in all its operations and functions.  
Two convenient ways to enter complex matrices are:
\disp{\tt A = [1 2;3 4] + i*[5 6;7 8] \nl
          A = [1+5i 2+6i;3+7i 4+8i]}
When listing complex numbers (e.g. 2+6i) in a matrix, blank spaces
must be avoided.  Either $i$ or $j$ may be used as the imaginary unit.
If, however, you use $i$ and $j$ as variables and overwrite their
values, you may generate a new imaginary unit with, say, \break
{\tt ii = sqrt(-1)}.

Listing entries of a large matrix is best done in an ASCII file with
your local editor, where errors can be easily corrected (see sections
12 and 14).  The file should consist of a rectangular array of just
the numeric matrix entries.  If this file is named, say, {\tt data.ext}
(where {\tt .ext} is any extension), the MATLAB command {\tt load data.ext}
will read this file to the variable $data$ in your MATLAB workspace.
This may also be done with a script file (see section 12).

The built-in functions {\tt rand}, {\tt magic}, and {\tt hilb}, for example, 
provide an easy way to create matrices with which to experiment.  The command 
{\tt rand(n)} will create an $n\times n$ matrix with randomly generated
entries distributed uniformly between 0 and 1, while {\tt rand(m,n)}
will create an $m\times n$ one.  {\tt magic(n)} will create an
integral $n\times n$ matrix which is a magic square (rows, columns,
and diagonals have common sum); {\tt hilb(n)} will create the $n\times
n$ Hilbert matrix, the king of ill-conditioned matrices ($m$ and $n$
denote, of course, positive integers).  Matrices can also be generated
with a for-loop (see section 6 below).  

Individual matrix and vector entries can be referenced with indices inside 
parentheses in the usual manner.  For example, $A(2,3)$ denotes the entry in 
the second row, third column of matrix $A$ and $x(3)$ denotes the third 
coordinate of vector $x$.  Try it.  A matrix or a vector will only 
accept {\it positive} integers as indices.

\bigskip
\section{3. Matrix operations, array operations}

The following matrix operations are available in MATLAB:
$$\vbox{\halign{
 # \qquad\hfil & # \hfil \cr
 + & addition \cr
 $-$ & subtraction \cr
 $*$ &  multiplication \cr
 $\power$ & power \cr
 $'$ & conjugate transpose \cr
 $\backslash$ & left division \cr
 / & right division \cr
}}$$
These matrix operations apply, of course, to scalars (1-by-1 matrices) as well.
If the sizes of the matrices are incompatible for the matrix operation, an 
error message will result, except in the case of scalar-matrix operations
(for addition, subtraction, and division as well as for
multiplication) in which case each entry of the matrix is operated on
by the scalar.  

The ``matrix division'' operations deserve special comment.  If $A$ is an
invertible square matrix and $b$ is a compatible column, resp. row, vector, 
then 
\disp{$x=A\backslash b$ is the solution of $A*x=b$ and, resp., \nl
         $x=b/A$  is the solution of $x*A=b$.}
In left division, if $A$ is square, then it is factored using Gaussian 
elimination and these factors are used to solve $A*x=b$.  If A is not
square, it is factored using Householder orthogonalization with column
pivoting and the factors are used to solve the under- or over-
determined system in the least squares sense.  Right division is
defined in terms of left division by $b/A=(A'\backslash b')'$.

\newpage
\noindent{\bf Array operations.}

The matrix operations of addition and subtraction already operate
entry-wise but the other matrix operations given above do not---they
are {\it matrix} operations.  It is important to observe that these other
operations, $*$, $\power$, $\backslash$, and /, can be made to operate 
entry-wise by preceding them by a period.  For example, either
{\tt [1,2,3,4].*[1,2,3,4]} or {\tt [1,2,3,4].$\power$2} will 
yield {\tt [1,4,9,16]}.  Try it.  This is particularly useful when
using Matlab graphics.

\bigskip
\section{4. Statements, expressions, and variables; saving a session}

MATLAB is an {\it expression} language; the expressions you type are 
interpreted and evaluated.  MATLAB statements are usually of the form
\disp{{\it variable = expression},  or simply \nl
         {\it expression}}
Expressions are usually composed from operators, functions, and variable names.
Evaluation of the expression produces a matrix, which is then displayed on the 
screen and assigned to the variable for future use.  If the variable name and
= sign are omitted, a variable {\tt ans} (for answer) is automatically 
created to which the result is assigned.

A statement is normally terminated with the carriage return.  However, a 
statement can be continued to the next line with three or more periods followed
by a carriage return.  On the other hand, several statements can be placed on 
a single line if separated by commas or semicolons. 
      
If the last character of a statement is a semicolon, the printing is 
suppressed, but the assignment is carried out. This is essential
in suppressing unwanted printing of intermediate results.

MATLAB is case-sensitive in the names of commands, functions, and variables.
For example, {\tt solveUT} is not the same as {\tt solveut}.

The command {\tt who} (or {\tt whos}) will list the variables
currently in the workspace. A variable can be cleared from the
workspace with the command  {\tt clear} {\it variablename}.  The
command {\tt clear} alone will clear all nonpermanent variables.

The permanent variable {\tt eps} (epsilon) gives the machine
unit roundoff---about $10^{-16}$ on most machines.  It is useful in
specifying tolerences for convergence of iterative processes.

A runaway display or computation can be stopped on most machines
without leaving MATLAB with CTRL-C (CTRL-BREAK on a PC).

\noindent{\bf Saving a session.}

When one logs out or exits MATLAB all
variables are lost.  However, invoking the command {\tt save} before
exiting causes all variables to be written to a non-human-readable
diskfile named {\tt matlab.mat}.  When one later reenters MATLAB, the
command {\tt load} will restore the workspace to its former state.

\newpage
\bigskip
\section{5. Matrix building functions}

Convenient matrix building functions are
$$\vbox{\halign{
 # \qquad\hfil & # \hfil \cr
 eye   & identity matrix \cr
 zeros & matrix of zeros \cr
 ones  & matrix of ones \cr
 diag  & create or extract diagonals \cr
 triu  & upper triangular part of a matrix \cr
 tril  & lower triangular part of a matrix \cr
 rand  & randomly generated matrix \cr
 hilb  & Hilbert matrix \cr
 magic & magic square \cr
 toeplitz & see {\tt help toeplitz} \cr
}}$$
For example, {\tt zeros(m,n)} produces an $m$-by-$n$ matrix of zeros and
{\tt zeros(n)} produces an $n$-by-$n$ one.  If $A$ is a matrix, then
{\tt zeros(size(A))} produces a matrix of zeros having the same size as $A$.

If $x$ is a vector, {\tt diag(x)} is the diagonal matrix with $x$ down the 
diagonal; if $A$ is a square matrix, then {\tt diag(A)} is a vector consisting 
of the diagonal of $A$.  What is {\tt diag(diag(A))}?  Try it. 

Matrices can be built from blocks.  For example, if  A  is a 3-by-3 matrix,
then
\disp{\tt B = [A, zeros(3,2); zeros(2,3), eye(2)]}
will build a certain 5-by-5 matrix.  Try it.

\bigskip
\section{6. For, while, if --- and relations}

In their basic forms, these MATLAB flow control statements operate like those 
in most computer languages.  

\noindent{\bf For.} 

For example, for a given n, the statement
\disp{\tt x = []; for i = 1:n, x=[x,i$\power 2$], end}
or
\disp{\tt x = []; \nl
        for i = 1:n \nl
        \xxx x = [x,i$\power 2$] \nl
        end}
will produce a certain $n$-vector and the statement
\disp{\tt x = []; for i = n:-1:1, x=[x,i$\power 2$], end}
will produce the same vector in reverse order.  Try them.  Note that a
matrix may be empty (such as {\tt x = []}).  

\newpage
The statements
\disp{\tt for i = 1:m \nl
        \xxx for j = 1:n \nl
        \xxx\xxx H(i, j) = 1/(i+j-1); \nl
        \xxx end \nl
        end \nl
        H}
will produce and print to the screen the $m$-by-$n$ hilbert matrix.
The semicolon on the 
inner statement is essential to suppress printing of unwanted
intermediate results while the last {\tt H} displays the final result. 

The {\tt for} statement permits {\it any} matrix to be used instead of
{\tt 1:n}.  The variable just consecutively assumes the value of each
column of the matrix.  For example,
\disp{\tt s = 0; \nl
       for c = A \nl
       \xxx s = s + sum(c); \nl
       end}
computes the sum of all entries of the matrix $A$ by adding its column
sums (Of course, {\tt sum(sum(A))} does it more efficiently; see
section 8).  In fact, since {\tt 1:n = [1,2,3,\dots,n]}, this
column-by-column assigment is what occurs with 
``{\tt if i = 1:n,\dots}'' (see section 11).

\noindent{\bf While.} 

The general form of a {\tt while} loop is
\disp{{\tt while} {\it relation} \nl
         \xxx {\it statements} \nl
         {\tt end}}
The statements will be repeatedly executed as long as the relation 
remains true.  For example, for a given number $a$, the following will
compute and display the smallest nonnegative integer $n$ such that 
$2^n\ge a$:
\disp{\tt n = 0; \nl
       while  2$\power $n < a \nl
       \xxx n = n + 1;  \nl
       end \nl
       n }

\noindent{\bf If.} 

The general form of a simple {\tt if} statement is
\disp{{\tt if} {\it relation} \nl
         \xxx {\it statements} \nl
         {\tt end}}
The statements will be executed only if the relation is true.
Multiple branching is also possible, as is illustrated by
\disp{\tt if n $<$ 0  \nl
         \xxx parity = 0; \nl
         elseif  rem(n,2) == 0 \nl
         \xxx parity = 2; \nl
         else \nl
         \xxx parity = 1; \nl
         end }
In two-way branching the elseif portion would, of course, be omitted.

\noindent{\bf Relations.} 

The relational operators in MATLAB are
$$\vbox{\halign{
 # \qquad\hfil & # \hfil \cr
 $<$  & less than \cr
 $>$  & greater than \cr
 $<=$ &less than or equal \cr
 $>=$ & greater than or equal \cr
 $==$ & equal \cr
 $\sim =$ & not equal. \cr
}}$$
Note that ``='' is used in an assignment statement while ``=='' is 
used in a relation.
Relations may be connected or quantified by the logical operators
$$\vbox{\halign{
 # \qquad\hfil & # \hfil \cr
 {\tt $\&$} & and \cr
 {\tt $|$}  & or \cr 
 {\tt $\sim$} & not. \cr
}}$$

When applied to scalars, a relation is actually the scalar 1 or 0 depending on 
whether the relation is true or false.  Try entering 
{\tt 3 < 5, 3 > 5, 3 == 5,} and {\tt 3 == 3}.
When applied to matrices of the same size, a relation is a matrix of 
0's and 1's
giving the value of the relation between corresponding entries.
Try {\tt a = rand(5), b = triu(a), a == b}.

A relation between matrices is interpreted by {\tt while} and {\tt if} to be
true if each entry of the relation matrix is nonzero.  Hence, if
you wish to execute {\it statement} when matrices $A$ and $B$
are equal you could type
\disp{\tt if  A == B \nl
        \xxx {\it statement} \nl
        end }
but if you wish to execute {\it statement} when $A$ and $B$ are not equal, 
you would type
\disp{\tt if  any(any(A $\sim$= B))  \nl
         \xxx {\it statement}  \nl
         end }
or, more simply,
\disp{\tt  if  A == B  else  \nl
           \xxx {\it statement} \nl
        end }
Note that the seemingly obvious
\disp{\tt if  A $\sim$= B, {\it statement}, end} 
will not give what is intended since {\it statement} would execute only if 
{\it each} of the corresponding entries of $A$ and $B$ differ.  The functions
{\tt any} and {\tt all} can be creatively used to reduce matrix relations to
vectors or scalars.  Two {\tt any}'s are required above since {\tt any} is a 
vector operator (see section 8).

\bigskip
\section{7. Scalar functions}

Certain MATLAB functions operate essentially on scalars, but operate 
element-wise when applied to a matrix.  The most common such functions are
$$\vbox{
\settabs 5 \columns
\+ sin  & asin  & exp               & abs   & round \cr
\+ cos  & acos  & log (natural log) & sqrt  & floor \cr
\+ tan  & atan  & rem (remainder)   & sign  & ceil  \cr
}$$

\bigskip
\section{8. Vector functions}

Other MATLAB functions operate essentially on a vector (row or column), but act
on an $m$-by-$n$ matrix ($m\ge2$) in a column-by-column fashion to produce a 
row vector containing the results of their application to each column.
Row-by-row action can be obtained by using the transpose; for example,
{\tt mean(A')'}.  A few of these functions are 
$$\vbox{ 
\settabs 4 \columns 
\+ max  & sum  & median & any \cr 
\+ min  & prod & mean   & all \cr 
\+ sort &      & std  \cr    
}$$ 
For example, the 
maximum entry in a matrix $A$ is given by {\tt max(max(A))} rather than
{\tt max(A)}.  Try it.  

\bigskip
\section{9. Matrix functions}

Much of MATLAB's power comes from its matrix functions.  The most useful ones 
are
$$\vbox{\halign{
 # \qquad\hfil & # \hfil \cr
 eig   & eigenvalues and eigenvectors \cr
 chol  & cholesky factorization \cr
 svd   & singular value decomposition \cr
 inv   & inverse \cr
 lu    & LU factorization \cr
 qr    & QR factorization \cr
 hess  & hessenberg form \cr
 schur & schur decomposition \cr
 rref  & reduced row echelon form \cr
 expm  & matrix exponential \cr
 sqrtm & matrix square root \cr
 poly  & characteristic polynomial \cr
 det   & determinant \cr
 size  & size \cr
 norm  & 1-norm, 2-norm, F-norm, $\infty$-norm \cr
 cond  & condition number in the 2-norm \cr
 rank  & rank \cr
}}$$
MATLAB functions may have single or multiple output arguments.  For example, 
\disp{{\tt y = eig(A)}, or simply {\tt eig(A)}}
produces a column vector containing the eigenvalues of $A$
while  
\disp{\tt [U,D] = eig(A)}
produces a matrix $U$ whose columns are the eigenvectors of $A$ and a diagonal 
matrix $D$ with the eigenvalues of $A$ on its diagonal.  Try it.

\bigskip
\section{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 a Unix system or a PC the Emacs commands Ctl-a, Ctl-e,
Ctl-d, and Ctl-k work; on other systems see {\tt help cedit} or 
{\tt 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
\disp{\tt  a = rand(8); flops(0), inv(a); flops}
If one wanted to compare plots of the functions $y=\sin mx$ and
$y=\sin nx$ on the interval $[0,2\pi]$ for various $m$ and $n$, one
might do the same for the command line: 
\disp{\tt m=2; n=3; x=0:.01:2*pi; y=sin(m*x); z=cos(n*x); plot(x,y,x,z)}

\bigskip
\section{11. Submatrices and colon notation}

Vectors and submatrices are often used in MATLAB to achieve fairly complex 
data manipulation effects.  \lq\lq Colon notation" (which is used both to 
generate vectors and reference submatrices) and subscripting by
integral vectors are keys to efficient manipulation of these objects.
Creative use of these features to vectorize operations permits one to
minimize the use of loops (which slows MATLAB) and to make code simple and 
readable. {\it Special effort should be made to become familiar with them.}

The expression {\tt 1:5} (met earlier in {\tt for} statements) is actually 
the row vector {\tt [1 2 3 4 5]}. The numbers need not be integers nor the 
increment one.  For example, 
\disp{\tt 0.2:0.2:1.2} 
gives {\tt [0.2, 0.4, 0.6, 0.8, 1.0, 1.2]}, and 
\disp{{\tt 5:-1:1} gives {\tt [5 4 3 2 1]}.}
The following statements 
will, for example, generate a table of sines. Try it.
\disp{\tt x = [0.0:0.1:2.0]$'$; \nl
         y = sin(x); \nl
         [x y]} 
Note that since {\tt 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,
\disp{{\tt A(1:4,3)} is the column vector consisting of the first four 
       entries of the third column of $A$.}
A colon by itself denotes an entire row or column:
\disp{{\tt A(:,3)} is the third column of $A$, and
         {\tt A(1:4,:)} is the first four rows.}
Arbitrary integral vectors can be used as subscripts:
\disp{{\tt A(:,[2 4])} contains as columns, columns 2 and 4 of $A$.}
Such subscripting can be used on both sides of an assignment statement:
\disp{{\tt A(:,[2 4 5]) = B(:,1:3)}  replaces columns 2,4,5 of $A$ with the 
        first three columns of $B$. Note that the {\it entire} altered 
        matrix $A$ is printed and assigned.  Try it.}
Columns 2 and 4 of $A$ can be multiplied on the right by the 
2-by-2 matrix  [1 2;3 4]:
\disp{\tt A(:,[2,4]) = A(:,[2,4])*[1 2;3 4]}
Once again, the entire altered matrix is printed and assigned.

If $x$ is an $n$-vector, what is the effect of the statement 
{\tt x = x(n:-1:1)}?  Try it.  Also try {\tt y = fliplr(x)}
and {\tt y = flipud(x')}.

To appreciate the usefulness of these features, compare these MATLAB 
statements with a Pascal, FORTRAN, or C routine to effect the same. 

\bigskip
\section{12. M-files}

MATLAB can execute a sequence of statements stored in 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.  M-files are usually created using your
local editor.

There are two types of M-files: {\it script files} and {\it function files}.

\noindent{\bf Script files.} 

A script file consists of a sequence of normal
MATLAB statements.  If the file has the filename, say, {\tt rotate.m},
then the MATLAB command {\tt 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 may be used to enter data into a large matrix;  in
such a file, entry errors can be easily corrected.  If, for example,
one enters in a diskfile {\tt data.m}
\disp{\tt A = [ \nl
        1 2 3 4    \nl
        5 6 7 8 \nl
        ]; }
then the MATLAB statement {\tt data} will cause the assignment given in
{\tt data.m} to be carried out.  However, it is usually easier to use
the MATLAB function {\tt load} (see section 2).

An M-file can reference other M-files, including referencing itself 
recursively. 

\noindent{\bf 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.  A variable can, however, be
declared global (see {\tt help global}).

We first illustrate with a simple example of a function file.

\disp{\tt
function  a = randint(m,n)\nl
\%RANDINT  Randomly generated integral matrix.\nl
\% \xxx    randint(m,n) returns an m-by-n such matrix with entries\nl
\% \xxx    between 0 and 9.  \nl
a = floor(10*rand(m,n));
}

A more general version of this function is the following:

\disp{\tt
function  a = randint(m,n,a,b)\nl
\%RANDINT  Randomly generated integral matrix.\nl
\% \xxx    randint(m,n) returns an m-by-n such matrix with entries\nl
\% \xxx    between 0 and 9.  \nl
\% \xxx    rand(m,n,a,b) return entries between integers $a$ and $b$.\nl
if nargin < 3, a = 0; b = 9; end \nl
a = floor((b-a+1)*rand(m,n)) + a;
}
This should be placed in a diskfile with filename {\tt 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 \nl {\tt z = randint(4,5)}, for 
example, will cause the numbers 4 and 5 to be passed to the variables $m$ 
and $n$ in the function file with the output result being passed out to the 
variable $z$.  Since variables in a function file are local, their names are 
independent of those in the current MATLAB environment.

Note that use of {\tt 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:
\disp{\tt
 function  [mean, stdev] = stat(x) \nl
 \% STAT  Mean and standard deviation \nl
 \% \xxx For a vector x, stat(x) returns the mean of x; \nl
 \% \xxx [mean, stdev] = stat(x) both the mean and standard deviation. \nl
 \% \xxx For a matrix x, stat(x) acts columnwise. \nl
 [m  n] = size(x); \nl
 if m == 1 \nl
  \xxx m = n;    \% handle case of a row vector  \nl
 end \nl
 mean = sum(x)/m; \nl
 stdev = sqrt(sum(x.$\power 2$)/m - mean.$\power 2$);
}
Once this is placed in a diskfile {\tt stat.m}, a MATLAB command 
{\tt [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, {\tt xm = stat(x)}
(no brackets needed around $xm$) will assign the mean of $x$ to $xm$.

The {\tt \%} symbol indicates that the rest of the line is a comment;
MATLAB will ignore the rest of the line.  Moreover, the first few
contiguous comment lines, which document the M-file, are available to
the on-line help facility and will be displayed if,  for example, {\tt
help stat} is entered.  Such documentation should {\it 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 {\tt x.$\power$2} is the
matrix of squares of the entries of $x$, that {\tt sum} is a vector function
(section 8), that {\tt sqrt} is a scalar function (section 7), and that
the division in {\tt sum(x)/m} is a matrix-scalar operation.  Thus all
operations are vectorized and loops avoided.

If you can't vectorize some computations, you can make your {\tt for}
loops go faster by preallocating any vectors or matrices in which
output is stored.  For example, by including the second statement
below, which uses the function {\tt zeros}, space for storing $E$ in
memory is preallocated.  Without this MATLAB must resize $E$ one
column larger in each iteration, slowing execution.
\disp{\tt 
M = magic(6); \nl
E = zeros(6,50); \nl
for j = 1:50 \nl
\xxx E(:,j) = eig(M$\power$i); \nl
end}

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 this example, may be made optional through use of {\tt nargin}
(``number of input arguments'').  The variable {\tt 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 {\tt while} or {\tt if} evaluates a relation,
``nonzero'' means ``true'' and $0$ means ``false''.  Finally, the
MATLAB function {\tt feval} permits one to have as an input variable a
string naming another function. (Also see {\tt eval}.)
\disp{\tt
function  [b, steps] = bisect(fun, x, tol) \nl
\%BISECT Zero of a function of one variable via the bisection method.\nl
\% \xxx    bisect(fun,x) returns a zero of the function.  fun is a string\nl
\% \xxx    containing the name of a real-valued MATLAB function of a\nl
\% \xxx    single real variable; ordinarily functions are defined in\nl
\% \xxx    M-files.  x  is a starting guess.  The value returned is near\nl
\% \xxx    a point where  fun  changes sign.  For example,\nl
\% \xxx    bisect('sin',3) is pi.  Note the quotes around sin.\nl
\% \xxx\nl
\% \xxx    An optional third input argument sets a tolerence for the \nl
\% \xxx    relative accuracy of the result.  The default is eps.  \nl
\% \xxx    An optional second output argument gives a matrix containing a \nl
\% \xxx    trace of the steps; the rows are of form  [c f(c)]. \nl
\xxx \nl
\% Initialization \nl
if nargin < 3, tol = eps; end \nl
trace = (nargout == 2); \nl
if x $\sim$= 0, dx = x/20; else, dx = 1/20; end \nl
a = x - dx;  fa = feval(fun,a); \nl
b = x + dx;  fb = feval(fun,b); \nl
\xxx \nl
\% Find change of sign. \nl
while (fa > 0) == (fb > 0) \nl
\xxx dx = 2.0*dx; \nl
\xxx a = x - dx;  fa = feval(fun,a); \nl
\xxx if (fa > 0) $\sim$= (fb > 0), break, end \nl
\xxx b = x + dx;  fb = feval(fun,b); \nl
end \nl
if trace, steps = [a fa; b fb]; end \nl
\xxx \nl
\% Main loop \nl
while  abs(b - a) > 2.0*tol*max(abs(b),1.0) \nl
\xxx c = a + 0.5*(b - a);  fc = feval(fun,c); \nl
\xxx if trace, steps = [steps; [c fc]]; end \nl
\xxx if (fb > 0) == (fc > 0) \nl
\xxx\xxx  b = c;  fb = fc; \nl
\xxx   else \nl
\xxx\xxx a = c;  fa = fc; \nl
\xxx end \nl
end
}

Some of MATLAB's functions are built-in while others are distributed
as M-files.  The actual listing of any non-built-in M-file---MATLAB's or
your own---can be viewed with the MATLAB command {\tt type \it
functionname}.  Try entering {\tt type eig}, {\tt type vander}, and
{\tt type rank}. 

\bigskip
\section{13. Text strings, error messages, input}

Text strings are entered into MATLAB surrounded by single quotes.  For 
example,
\disp{\tt s = 'This is a test'}
assigns the given text string to the variable {\tt s}.

Text strings can be displayed with the function {\tt disp}.  For example:
\disp{\tt disp('this message is hereby displayed')}
Error messages are best displayed with the function {\tt error}
\disp{\tt error('Sorry, the matrix must be symmetric')}
since when placed in an M-File, it aborts execution of the M-file.

\newpage
In an M-file the user can be prompted to interactively enter input data with 
the function {\tt input}.  When, for example, the statement
\disp{\tt iter = input('Enter the number of iterations:  ')}
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 {\tt iter} and execution resumes.

\bigskip
\section{14. Managing M-files}

While using MATLAB one frequently wishes to create or edit an M-file
with the local editor 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 {\tt ed} accesses  your editor,
the MATLAB command 
\disp{\tt >>  !ed  rotate.m}
will let you edit the file named {\tt rotate.m} using your local editor.
Upon leaving the editor, you will be returned to MATLAB just where you left 
it.

However, as noted in section 1, on systems permitting multiple
processes, such as one running Unix or MS Windows, 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, you will want to keep MATLAB active in
one window and your editor active in another. 

You should consult your instructor or your local computing center for
details of the local installation.

Many debugging tools are available.  See {\tt help dbtype} or the list
of functions in the last section.

When in MATLAB, the command {\tt pwd} will return the name of the
present working directory and {\tt cd} can be used to
change the working directory.  Either {\tt dir} or {\tt ls} will list the
contents of the working directory while the command {\tt what}
lists only the M-files in the directory.  The MATLAB commands 
{\tt delete} and {\tt type} can be used to delete a diskfile and print
an M-file to the screen, respectively. While these commands may
duplicate system commands, they avoid the use of an !.  You may enjoy
entering the command {\tt why} a few times. 

M-files must be in a directory accessible to MATLAB.  M-files in the
present working directory are always accessible.  On most mainframe or
workstation network installations, personal M-files which are stored
in a subdirectory of one's home directory named\break {\tt matlab}
will be accessible to MATLAB from any directory in which one is
working.   The current list of directories in MATLAB's search path is
obtained by the command {\tt path}.  This command can also be used to
add or delete directories from the search path.  See {\tt help path}.

\newpage
\bigskip
\section{15. Comparing efficiency of algorithms: flops, tic and toc}

Two measures of the efficiency of an algorithm are the number of floating
point operations (flops) performed and the elapsed time.

The MATLAB function {\tt flops} keeps a running total of the flops
performed.  The command {\tt flops(0)} (not {\tt flops = 0}!) will
reset flops to 0.  Hence, entering {\tt flops(0)} immediately before
executing an algorithm and {\tt flops} immediately after gives the
flop count for the algorithm.  For example, the number of flops
required to solve a given linear system via Gaussian elimination can
be obtained with:
\disp{\tt flops(0), x = A$\backslash$b; flops}

The elapsed time (in seconds) can be obtained with the stopwatch
timers {\tt tic} and {\tt toc}; {\tt tic} starts the timer and 
{\tt toc} returns the elapsed time.  Hence, the commands
\disp{\tt tic, \it any statement, \tt toc}
will return the elapsed time for execution of the statement. The
elapsed time for solving the linear system above can be obtained,
for example, with:
\disp{\tt tic, x = A$\backslash$b; toc}
You may wish to compare this time---and flop count---with that for solving 
the system using {\tt x = inv(A)*b;}.  Try it.

It should be noted that, on timesharing machines, elapsed time 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.

\bigskip
\section{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.
$$\vbox{\halign{
 \tt # \qquad\hfil & # \hfil \cr
 format short   & fixed point with 4 decimal places (the default) \cr
 format long    & fixed point with 14 decimal places \cr
 format short e & scientific notation with 4 decimal places \cr
 format long e  & scientific notation with 15 decimal places \cr
 format rat     & approximation by ratio of small integers \cr
 format hex     & hexadecimal format \cr
 format bank    & fixed dollars and cents \cr
 format +       & +, -, blank \cr
}}$$
Once invoked, the chosen format remains in effect until changed.

The command {\tt format compact} will suppress most blank lines allowing more 
information to be placed on the screen or page.  The command
{\tt format loose} returns to the non-compact format.
These commands are independent of the other format commands.

\newpage
\bigskip
\section{17. Hardcopy}

Hardcopy is most easily obtained with the {\bf diary} command.  The command
\disp{\tt diary {\it filename}}
causes what appears subsequently on the screen (except graphics) to be written 
to the named diskfile (if the filename is omitted it will be written to a 
default file named {\tt diary}) until one gives the 
command {\tt diary off}; the command {\tt 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.

\bigskip
\section{18. Graphics}

MATLAB can produce planar plots of curves, 3-D plots of curves, 3-D
mesh surface plots, and 3-D faceted surface plots.  The primary
commands for these facilities are {\tt plot, plot3, mesh,} and
{\tt surf}, respectively.  An introduction to each of these is given
below.

To preview some of these capabilities, enter the command {\tt demo}
and select some of the graphics options.

\noindent{\bf Planar plots.}

The {\tt plot} command creates linear x-y plots; if $x$ and $y$ are vectors of
the same length, the command {\tt 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:
\disp{\tt  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 {\tt sin} operates entrywise).

You will usually want to keep the current graphics window (``figure'')
exposed---but moved to the side---and the command window active.

One can have several graphics figures, one of which will at any time
be the designated ``current'' figure where graphs from subsequent
plotting commands will be placed.  If, for example, figure 1 is the
current figure, then the command {\tt figure(2)} (or simply {\tt figure})
will open a second figure (if necessary) and make it the current figure.
The command {\tt figure(1)} will then expose figure 1 and make it
again the current figure.  The command {\tt gcf} will return the
number of the current figure.

As a second example, you can draw the 
graph of $y=e^{-x^2}$ over the interval -1.5 to 1.5  as follows:
\disp{\tt  x = -1.5:.01:1.5;  y = exp(-x.$\power $2);  plot(x,y) }
Note that one must precede $\power $ by a period to ensure that it operates
entrywise (see section 3).

MATLAB supplies a function {\tt fplot} to easily and efficiently plot
the graph of a function.  For example, to plot the graph of the
function above, one can first define the function in an M-file
called, say, {\tt expnormal.m} containing
\disp{\tt function y = expnormal(x) \nl
          y = exp(-x.$\power $2);}
Then the command
\disp{\tt fplot('expnormal', [-1.5,1.5])}
will produce the graph.  Try it.

Plots of parametrically defined curves can also be made.  Try, for example,
\disp{\tt t=0:.001:2*pi; x=cos(3*t); y=sin(2*t); plot(x,y)}

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. 
\disp{\hbox{\vbox{\halign{\tt #\hfill & \qquad#\hfill \cr
title  & graph title \cr
xlabel & x-axis label \cr
ylabel & y-axis label \cr
gtext  & place text on the graph using the mouse \cr
text   & position text at specified coordinates \cr
}}}}
For example, the command
\disp{\tt title('Best Least Squares Fit')}
gives a graph a title.   The command {\tt gtext('The Spot')} allows
one to interactively place the designated text on the current graph by
placing the mouse pointer at the desired position and clicking the
mouse. To place text in a graph at designated coordinates, one would use the
command {\tt text} (see {\tt help text}).

The command {\tt grid} will place grid lines on the current graph.

By default, the axes are auto-scaled.  This can be overridden by the command 
{\tt axis}.  Some features of {\tt axis} are:
\disp{\hbox{\vbox{\halign{\tt #\hfill & \qquad#\hfill \cr
axis([x$_{\min}$,x$_{\max}$,y$_{\min}$,y$_{\max}$]) & set axis scaling to
                              prescribed limits \cr
axis(axis)   & freezes scaling for subsequent graphs \cr
axis auto    & returns to auto-scaling \cr
v = axis     & returns vector $v$ showing current scaling \cr
axis square  & same scale on both axes \cr
axis equal   & same scale and tic marks on both axes \cr
axis off     & turns off axis scaling and tic marks \cr
axis on      & turns on axis scaling and tic marks \cr
}}}}
The {\tt axis} command should be given {\it after} the {\tt plot} command.

Two ways to make multiple plots on a single graph are illustrated by
\disp{\tt 
x=0:.01:2*pi;y1=sin(x);y2=sin(2*x);y3=sin(4*x);plot(x,y1,x,y2,x,y3)}
and by forming a matrix {\tt Y} containing the functional values as 
columns
\disp{\tt x=0:.01:2*pi; Y=[sin(x)', sin(2*x)', sin(4*x)']; plot(x,Y)}
Another way is with {\tt hold}.  The command {\tt hold on} freezes the
current graphics screen so that subsequent plots are superimposed on it.  
The axes may, however, become rescaled. Entering {\tt hold off} releases
the ``hold.'' 

\newpage
One can override the default linetypes, pointtypes and colors.
For example,
\disp{\tt x=0:.01:2*pi; y1=sin(x); y2=sin(2*x); y3=sin(4*x);\nl
        plot(x,y1,'--',x,y2,':',x,y3,'+')}
renders a dashed line and dotted line for the first two graphs while for the
third the symbol {\tt+} is placed at each node.  The line- and mark-types are
\disp{Linetypes: solid ({\tt-}), dashed (\tt--\rm). dotted ({\tt:}),
                 dashdot ({\tt-.}) \nl
     Marktypes: point ({\tt.}), plus ({\tt+}), star ({\tt*}), 
                 circle ({\tt o}), x-mark ({\tt x})}
Colors can be specified for the line- and mark-types.
\disp{Colors: yellow ({\tt y}), magenta ({\tt m}), cyan ({\tt c}), 
              red ({\tt r}) \nl \hphantom{Colors:x}
    green ({\tt g}), blue ({\tt b}), white ({\tt w}), black ({\tt k})}
For example, {\tt plot(x,y,'r--')} plots a red dashed line.

The command {\tt subplot} can be used to partition the screen so that
several small plots can be placed in one figure.  See {\tt help subplot}.

Other specialized 2-D plotting functions you may wish to explore
via {\tt help} are:
\disp{\tt polar, bar, hist, quiver, compass, feather, rose, stairs, fill}

\noindent{\bf Graphics hardcopy}

A hardcopy of the current graphics figure can be most easily obtained
with the MATLAB  command {\tt print}.  Entered by itself, it will send
a high-resolution copy of the current graphics figure to the default
printer. 

The {\tt printopt} M-file is used to specify the default setting used
by the {\tt print} command.  If desired, one can change the defaults
by editing this file (see {\tt help printopt}).

The command \quad {\tt print \it filename}\quad saves the current
graphics figure to the designated filename in the default file format.
If {\it filename} has no extension, then an appropriate extension such
as {\tt .ps, .eps,} or {\tt .jet} is appended.  If, for example,
PostScript is the default file format, then
\disp{\tt print lissajous}
will create a PostScript file {\tt lissajous.ps} of the current
graphics figure which can subsequently be printed using the system
print command.  If {\tt filename} already exists, it will be
overwritten unless you use the {\tt -append} option.  The command
\disp{\tt print -append lissajous}
will append the (hopefully different) current graphics figure to the
existing file \hfil\break {\tt lissajous.ps}.  In this way one can save
several graphics figures in a single file.

The default settings can, of course, be overwritten.  For example,
\disp{\tt print -deps -f3 saddle}
will save to an Encapsulated PostScript file {\tt saddle.eps} the 
graphics figure 3 --- even if it is not the current figure.

\newpage
\noindent{\bf 3-D line plots.}

Completely analogous to {\tt plot} in two dimensions, the command 
{\tt plot3} produces curves in three dimensional space.  If $x$, $y$,
and $z$ are three vectors of the same size, then the command
{\tt plot3(x,y,z)} will produce a perspective plot of the piecewise
linear curve in 3-space passing through the points whose coordinates
are the respective elements of $x$, $y$, and $z$.  These vectors are
usually defined parametrically.  For example,
\disp{\tt
t=.01:.01:20*pi; x=cos(t); y=sin(t); z=t.$\power $3; plot3(x,y,z)}
will produce a helix which is compressed near the $x$-$y$ plane 
(a ``slinky'').  Try it.

Just as for planar plots, a title and axis labels (including 
{\tt zlabel}) can be added.  The features of 
{\tt axis} command described there also hold for 3-D plots; 
setting the axis scaling to prescribed limits will, of course,
now require a 6-vector.

\noindent{\bf 3-D mesh and surface plots.}

Three dimensional wire mesh surface plots are drawn with the command
{\tt mesh}. The command {\tt 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 {\tt mesh(eye(10))}.

Similarly,  three dimensional faceted surface plots are drawn with the
command {\tt surf}.  Try {\tt surf(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 {\tt meshgrid} 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:
\disp{\tt [x,y] = meshgrid(xx,yy);}
One then computes a matrix $z$, obtained by evaluating $f$ entrywise over the 
matrices $x$ and $y$, to which {\tt mesh} or {\tt surf} 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):
\disp{\tt xx = -2:.2:2; \nl
            yy = xx; \nl
            [x,y] = meshgrid(xx,yy);  \nl
            z = exp(-x.$\power $2 - y.$\power $2); \nl
            mesh(z) }
One could, of course, replace the first three lines of the preceding with 
\disp{\tt [x,y] = meshgrid(-2:.2:2, -2:.2:2);}
Try this plot with {\tt surf} instead of {\tt mesh}.

As noted above, the features of the {\tt axis} command described in the
section on planar plots also hold for 3-D plots as do the commands for
titles, axes labelling and the command {\tt hold}.

The color shading of surfaces is set by the {\tt shading} command.
There are three settings for shading: {\tt faceted} (default), 
{\tt interpolated,} and {\tt flat}.  These are set by the commands
\disp{\tt shading faceted,\quad shading interp,\quad{\rm or}\quad shading flat}
Note that on surfaces produced by {\tt surf}, the settings 
{\tt interpolated} and {\tt flat} remove the superimposed mesh lines.
Experiment with various shadings on the surface produced above.
The command {\tt shading} (as well as {\tt colormap} and 
{\tt view} below) should be entered {\it after} the {\tt surf} command.

The color profile of a surface is controlled by the {\tt colormap}
command.  Available predefined colormaps include:
\disp{\tt hsv {\rm (default)}, hot, cool, jet, pink, copper, flag,
          gray, bone}
The command {\tt colormap(cool)} will, for example, set a certain
color profile for the current figure.  Experiment with various
colormaps on the surface produced above. 

The command {\tt view} can be used to specify in spherical or
cartesian coordinates the viewpoint from which the 3-D object
is to be viewed.  See {\tt help view}.

The MATLAB function {\tt peaks} generates an interesting surface on
which to experiment with {\tt shading}, {\tt colormap}, and
{\tt view}.

Plots of parametrically defined surfaces can also be made.  The MATLAB
functions {\tt sphere} and {\tt cylinder} will generate such plots of
the named surfaces. (See {\tt type sphere} and {\tt type cylinder}.)
The following is an example of a similar function which generates a
plot of a torus.
\disp{\tt
function  [x,y,z] = torus(r,n,a) \nl
\%TORUS Generate a torus \nl
\%\xxx  torus(r,n,a) generates a plot of a torus with central \nl
\%\xxx  radius  a  and lateral radius  r.  n  controls the number \nl
\%\xxx  of facets on the surface.  These input variables are optional \nl
\%\xxx  with defaults  r = 0.5, n = 30, a = 1.\nl
\% \nl
\%\xxx  [x,y,z] = torus(r,n,a) generates three (n+1)-by-(n+1) \nl
\%\xxx  matrices so that surf(x,y,z) will produce the torus. \nl
\% \nl
\%\xxx  See also SPHERE, CYLINDER \nl
\hbox{}\nl
if nargin < 3, a = 1; end \nl
if nargin < 2, n = 30; end \nl
if nargin < 1, r = 0.5; end\nl 
theta = pi*(0:2:2*n)/n; \nl
phi   = 2*pi*(0:2:n)'/n; \nl
xx = (a + r*cos(phi))*cos(theta); \nl 
yy = (a + r*cos(phi))*sin(theta); \nl
zz = r*sin(phi)*ones(size(theta));\nl 
if nargout == 0\nl 
\xxx surf(xx,yy,zz) \nl
\xxx ar = (a + r)/sqrt(2);\nl 
\xxx axis([-ar,ar,-ar,ar,-ar,ar]) \nl 
else \nl
\xxx x = xx; y = yy; z = zz;\nl 
end}

Other 3-D plotting functions you may wish to explore via {\tt help} are:
\disp{\tt meshz, surfc, surfl, contour, pcolor}

\noindent{\bf Handle Graphics.}

Beyond those described above, MATLAB's graphics system provides 
low level functions which permit one to control virtually all
aspects of the graphics environment to produce sophisticated plots.
Enter the command {\tt set(1)} and {\tt gca,set(ans)} to see some of the
properties of figure 1 which one can control. This system is called Handle
Graphics, for which one is referred to the MATLAB User's Guide.

\bigskip
\section{19. Sparse Matrix Computations}

In performing matrix computations, MATLAB normally assumes that a
matrix is dense; that is, any entry in a matrix {\it may} be nonzero.
If, however, a matrix contains sufficiently many zero entries,
computation time could be reduced by avoiding arithmetic operations on
zero entries and less memory could be required by storing only the
nonzero entries of the matrix.  This increase in efficiency in time
and storage can make feasible the solution of significantly larger
problems than would otherwise be possible.  MATLAB provides the
capability to take advantage of the sparsity of matrices.

Matlab has two storage modes, full and sparse, with full the default.
The functions {\tt full} and {\tt sparse} convert between the two
modes.  For a matrix $A$, full or sparse, {\tt nnz(A)} returns 
the number of nonzero elements in $A$.   

A sparse matrix is stored as a linear array of its nonzero elements
along with their row and column indices.
If a full tridiagonal matrix $F$ is created via, say,
\disp{\tt F = floor(10*rand(6)); F = triu(tril(F,1),-1);}
then the statement {\tt S = sparse(F)} will convert $F$ to sparse mode.
Try it.  Note that the output lists the nonzero entries in column
major order along with their row and column indices.   The statement
{\tt F = full(S)} restores $S$ to full storage mode.  One can check
the storage mode of a matrix $A$ with the command {\tt issparse(A)}.

A sparse matrix is, of course, usually generated directly rather than
by applying the function {\tt sparse} to a full matrix.  A sparse
banded matrix can be easily created via the function {\tt spdiags} by
specifying diagonals.  For example, a familiar sparse tridiagonal
matrix is created by
\disp{\tt m = 6; n = 6; e = ones(n,1); d = -2*e; \nl
          T = spdiags([e,d,e],[-1,0,1],m,n)}
Try it.  The integral vector [-1,0,1] specifies in which diagonals the
columns of [e,d,e] should be placed (use {\tt full(T)} to view).
Experiment with other values of $m$ and $n$ and, say, [-3,0,2] instead
of [-1,0,1].  See {\tt help spdiags} for further features of {\tt spdiags}.

\newpage
The sparse analogs of {\tt eye}, {\tt zeros}, {\tt ones}, and 
{\tt randn} for full matrices are, respectively,
\disp{\tt speye,\quad sparse,\quad spones,\quad sprandn}
The latter two take a matrix argument and replace only the nonzero
entries with ones and normally distributed random numbers, respectively.
{\tt randn} also permits the sparsity structure to be randomized.
The command {\tt sparse(m,n)} creates a sparse zero matrix.

The versatile function {\tt sparse} permits creation of a sparse
matrix via listing its nonzero entries.  Try, for example,
\disp{\tt i = [1 2 3 4 4 4]; j = [1 2 3 1 2 3]; s = [5 6 7 8 9 10];\nl
          S = sparse(i,j,s,4,3), full(S)}
In general, if the vector $s$ lists the nonzero entries of $S$ and the
integral vectors $i$ and $j$ list their corresponding row and column
indices, then
\disp{\tt sparse(i,j,s,m,n)}
will create the desired sparse $m\times n$ matrix $S$.
As another example try
\disp{\tt n = 6; e = floor(10*rand(n-1,1)); E = sparse(2:n,1:n-1,e,n,n)}

The arithmetic operations and most MATLAB functions can be applied
independent of storage mode.  The storage mode of the result?
Operations on full matrices always give full results.  Selected other
results are (S=sparse, F=full):
\disp{Sparse:\quad{\tt S+S, S*S, S.*S, S.*F, S$\power$n, S.$\power$n,
             S$\backslash$S} \nl
Full:\quad{\tt S+F, S*F, S$\backslash$F, F$\backslash$S} \nl
Sparse:\quad{\tt inv(S), chol(S), lu(S), diag(S), max(S), sum(S)}
}
For sparse $S$, {\tt eig(S)} is full if $S$ is symmetric but undefined
if $S$ is unsymmetric; {\tt svd} requires a full argument.  A matrix
built from blocks, such as {\tt [A,B;C,D]}, is sparse if any constituent
block is sparse.

You may wish to compare, for the two storage modes, the efficiency of
solving a tridiagonal system of equations for, say, $n=20,50,500,1000$
by entering, recalling and editing the following two command lines:
\disp{\tt
n=20;e=ones(n,1);d=-2*e; T=spdiags([e,d,e],[-1,0,1],n,n); A=full(T);\nl
b=ones(n,1);s=sparse(b);tic,T$\backslash$s;sparsetime=toc,  
   tic,A$\backslash$b;fulltime=toc
}

\newpage
\bigskip
\section{20. Reference}

There are many MATLAB features which cannot be included in these introductory 
notes. Listed below are some of the MATLAB functions and operators available, 
grouped by subject area\footnote{${}^1$}{\rmten Source: MATLAB Reference Guide,
version 4.1}.  Use the on-line help facility or consult the Reference
Guide for more detailed information on the functions. 

There are many functions beyond these.  There exist, in particular,
several ``toolboxes'' of functions for specific areas\footnote{${}^2$}
{\rmten The toolboxes, which are optional, may not be installed on 
your system.}.  Included among such are signal processing, control
systems, robust-control, system identification, optimization, splines,
chemometrics, $\mu$-analysis and synthesis, state-space
identification, neural networks, image processing, symbolic math
(Maple kernel), and statistics.  These can be explored via the command
{\tt help}.  

\rmten   % Ensure ten point font for lists of functions
%%%%%%%%%%%% Managing Commands and Functions %%%%%%%%%%%%%%%
$$
\vbox{\offinterlineskip
\halign{
\strut\vrule \quad\bften # \quad\hfil & # \quad\hfil \vrule \cr
\noalign{\hrule}
\multispan2\strut\vrule \hfil \scten 
Managing Commands and Functions \hfil \vrule \cr
\noalign{\hrule}
help & help facility \cr
what & list M-files on disk \cr
type & list named M-file \cr
lookfor & keywork search through the help entries \cr
which & locate functions and files \cr
demo & run demonstrations \cr
path & control MATLAB's search path \cr
cedit& set parameters for command line editing and recall\cr
version& display MATLAB version you are running \cr
whatsnew & display toolbox README files \cr
info & info about MATLAB and The MathWorks \cr
why  & receive flippant answer \cr
\noalign{\hrule}
}}$$
\bigskip
%%%%%%%% Managing Variables and the Workspace %%%%%%%%%%%%
$$
\vbox{\offinterlineskip
\halign{
\strut\vrule \quad\bften # \quad\hfil & # \quad\hfil \vrule \cr
\noalign{\hrule}
\multispan2\strut\vrule \hfil \scten 
Managing Variables and the Workspace \hfil \vrule \cr
\noalign{\hrule}
who  & list current variables \cr
whos & list current variables, long form \cr
save & save workspace variables to disk \cr
load & retrieve variables from disk \cr
clear & clear variables and functions from memory \cr
pack  & consolidate workspace memory \cr
size & size of matrix \cr
length & length of vector \cr
disp & display matrix or text \cr
\noalign{\hrule}
}}$$

%%%%%%%%% Working with Files and the Operating System %%%%%%%%%%
$$
\vbox{\offinterlineskip
\halign{
\strut\vrule \quad\bften # \quad\hfil & # \quad\hfil \vrule \cr
\noalign{\hrule}
\multispan2\strut\vrule \hfil \scten 
Working with Files and the Operating System \hfil \vrule \cr
\noalign{\hrule}
cd  & change current working directory \cr
pwd & show current working directory \cr
dir, ls & directory listing \cr
delete & delete file \cr
getenv & get environment variable \cr
!   & execute operating system command \cr
unix& execute operating system command; return result \cr
diary & save text of MATLAB session \cr
\noalign{\hrule}
}}$$

%%%%%%%% Controlling the Command Window %%%%%%%%%%%%
$$
\vbox{\offinterlineskip
\halign{
\strut\vrule \quad\bften # \quad\hfil & # \quad\hfil \vrule \cr
\noalign{\hrule}
\multispan2\strut\vrule \hfil \scten 
Controlling the Command Window \hfil \vrule \cr
\noalign{\hrule}
clc  & clear command window \cr
home & send cursor home---to top of screen \cr
format & set output format \cr
echo & echo commands inside script commands \cr
more & control paged output in command window \cr
\noalign{\hrule}
}}$$

%%%%%%%% Starting and Quitting from Matlab %%%%%%%%%
$$
\vbox{\offinterlineskip
\halign{
\strut\vrule \quad\bften # \quad\hfil & # \quad\hfil \vrule \cr
\noalign{\hrule}
\multispan2\strut\vrule \hfil \scten 
Starting and Quitting from MATLAB \hfil \vrule \cr
\noalign{\hrule}
quit & terminate MATLAB \cr
startup & M-file executed when MATLAB is started \cr
matlabrc & master startup M-file \cr
\noalign{\hrule}
}}$$

%%%%%%%%%%%%%%%  Matrix/Array Operators  %%%%%%%%%%%%%%
$$
\vbox{\offinterlineskip
\halign{
\strut\vrule\quad\bften#\quad\hfil&#\quad\hfil\vrule&
                                \quad\bften#\quad\hfil&#\quad\hfil\vrule \cr
\noalign{\hrule}
\multispan2\strut\vrule\hfil\scten Matrix Operators \hfil\vrule &
        \multispan2\hfil\scten Array Operators \hfil\vrule \cr
\noalign{\hrule}
+  & addition     & +  & addition\cr
$-$& subtraction &$-$ & subtraction\cr
$*$& multiplication &.$*$ & multiplication\cr
$\power$ & power    & .$\power$ & power\cr
/  & right division & ./  & right division\cr
$\backslash$&left division &.$\backslash$ & left division\cr
'  & conjugate transpose  & & \cr
.' & transpose & & \cr
kron & Kronecker tensor product & & \cr
\noalign{\hrule}
}}$$

%%%%%%%%%%%%  Relational and Logical Operators %%%%%%%%
$$
\vbox{\offinterlineskip
\halign{
\strut\vrule\quad\bften#\quad\hfil&#\quad\hfil\vrule&
                               \quad\bften#\quad\hfil&#\quad\hfil\vrule \cr
\noalign{\hrule}
\multispan4\strut\vrule\hfil\scten Relational and Logical Operators \hfil\vrule\cr
\noalign{\hrule}
$<$   & less than          & \& & and \cr
$<$=  & less than or equal & $|$ & or \cr
$>$   & greater than       & $\sim$ & not \cr
$>$=  & greater than or equal & xor& exclusive or \cr
==    & equal              && \cr
$\sim$= & not equal        && \cr
\noalign{\hrule}
}}$$

%%%%%%%%%%%%%%%%  Special Characters  %%%%%%%%%%%%%%%%%
$$
\vbox{\offinterlineskip
\halign{
\strut\vrule \quad\bften # \quad\hfil & # \quad\hfil \vrule \cr
\noalign{\hrule}
\multispan2\strut\vrule\hfil\scten Special Characters \hfil\vrule\cr
\noalign{\hrule}
=  & assignment statement\cr
[\ ] & used to form vectors and matrices; enclose multiple function
       output variables \cr
(\ ) & arithmetic expression precedence; enclose function input variables \cr
.  & decimal point\cr
.. & parent directory \cr
... & continue statement to next line\cr
,  & separate subscripts, function arguments, statements\cr
;  & end rows, suppress printing\cr
\% & comments\cr
:  & subscripting, vector generation\cr
!  & execute operating system command\cr
\noalign{\hrule}
}}$$
\bigskip
%%%%%%%%%%%%  Special Variables and Constants  %%%%%%%%%%%%%%
$$
\vbox{\offinterlineskip
\halign{
\strut\vrule \quad\bften # \quad\hfil & # \quad\hfil \vrule \cr
\noalign{\hrule}
\multispan2\strut\vrule\hfil\scten 
Special Variables and Constraints \hfil\vrule\cr
\noalign{\hrule}
ans  & answer when expression not assigned\cr
eps  & floating point precision\cr
realmax & largest floating point number \cr
reammin & smallest positive floating point number \cr
pi   & $\pi$\cr
i, j & imaginary unit \cr
inf  & infinity \cr
NaN  & Not-a-Number\cr
flops & floating point operation count\cr
nargin & number of function input arguments\cr
nargout& number of function output arguments\cr
computer & computer type \cr
\noalign{\hrule}
}}$$
\bigskip
%%%%%%%%  Time and Dates  %%%%%%%%%%%%%
$$
\vbox{\offinterlineskip
\halign{
\strut\vrule \quad\bften # \quad\hfil & # \quad\hfil \vrule \cr
\noalign{\hrule}
\multispan2\strut\vrule\hfil\scten 
Time and Date \hfil\vrule\cr
\noalign{\hrule}
date & current date \cr
clock & wall clock \cr
etime & elapsed time function \cr
tic, toc & stopwatch timer functions \cr
cputime & elapsed CPU time \cr
\noalign{\hrule}
}}$$

%%%%%%%%%%%%%%%  Special Matrices  %%%%%%%%%%%%%%%
$$
\vbox{\offinterlineskip
\halign{
\strut\vrule \quad\bften # \quad\hfil & # \quad\hfil \vrule \cr
\noalign{\hrule}
\multispan2\strut\vrule\hfil\scten Special Matrices \hfil\vrule\cr
\noalign{\hrule}
zeros & matrix of zeros\cr
ones  & matrix of ones \cr
eye   & identity \cr
diag  & diagonal \cr
toeplitz & Toeplitz\cr
magic & magic square\cr
compan & companion \cr
linspace & linearly spaced vectors\cr
logspace & logarithmically spaced vectors\cr
meshgrid & array for 3-D plots\cr
rand  & uniformly distributed random numbers \cr
randn & normally distributed randon numbers \cr
hilb  & Hilbert\cr
invhilb & inverse Hilbert (exact)\cr
vander & Vandermonde\cr
pascal & Pascal\cr
hadamard & Hadamard\cr
hankel & Hankel\cr
rosser & symmetric eigenvalue test matrix \cr
wilkinson & Wilkinson's eigenvalue test matrix \cr
gallery & two small test matrices\cr
\noalign{\hrule}
}}$$
\bigskip
%%%%%%%%%%%%%%%  Matrix Manipulation  %%%%%%%%%%%%%%%
$$
\vbox{\offinterlineskip
\halign{
\strut\vrule \quad\bften # \quad\hfil & # \quad\hfil \vrule \cr
\noalign{\hrule}
\multispan2\strut\vrule\hfil\scten  Matrix Manipulation \hfil\vrule\cr
\noalign{\hrule}
diag  & create or extract diagonals \cr
rot90 & rotate matrix 90 degrees\cr
fliplr & flip matrix left-to-right\cr
flipud & flip matrix up-to-down\cr
reshape & change size\cr
tril  & lower triangular part\cr
triu  & upper triangular part\cr
.'    & transpose\cr
:     & convert matrix to single column; {\tt A(:)}\cr
\noalign{\hrule}
}}$$

\newpage
%%%%%%%%%%%%  Logical Functions  %%%%%%%%%
$$
\vbox{\offinterlineskip
\halign{
\strut\vrule \quad\bften # \quad\hfil & # \quad\hfil \vrule \cr
\noalign{\hrule}
\multispan2\strut\vrule\hfil\scten Logical Functions\hfil\vrule\cr
\noalign{\hrule}
exist & check if variables or functions exist \cr
any   & true if any element of vector is true \cr
all   & true if all elements of vector are true \cr
find  & find indices of non-zero elements \cr
isnan & true for NaNs \cr
isinf & true for infinite elements \cr
finite & true for finite elements \cr
isieee & true for IEEE floating point arithmetic \cr
isempty & true for empty matrix\cr
issparse & true for sparse matrix \cr
isstr & true for text string \cr
strcmp & compare string variables\cr
\noalign{\hrule}
}}$$
\bigskip
%%%%%%%%%%%%%%%  Control Flow  %%%%%%%%%%%%%%
$$
\vbox{\offinterlineskip
\halign{
\strut\vrule \quad\bften # \quad\hfil & # \quad\hfil \vrule \cr
\noalign{\hrule}
\multispan2\strut\vrule\hfil\scten Control Flow \hfil\vrule\cr
\noalign{\hrule}
if    & conditionally execute statements\cr
else  & used with {\bften if}\cr
elseif& used with {\bften if}\cr
end   & terminate {\bften if, for, while}\cr
for   & repeat statements for a specific number of times\cr
while & repeat statments while condition is true \cr
break & terminate execution of {\bften for} or {\bften while} loops\cr
return& return to invoking function \cr
error & display message and abort function \cr
\noalign{\hrule}
}}$$
\bigskip
%%%%%%%%%%%%%%  Programming   %%%%%%%%%%%
$$
\vbox{\offinterlineskip
\halign{
\strut\vrule \quad\bften # \quad\hfil & # \quad\hfil \vrule \cr
\noalign{\hrule}
\multispan2\strut\vrule\hfil\scten Programming  \hfil\vrule\cr
\noalign{\hrule}
input   & prompt for user input \cr
keyboard& invoke keyboard as if it were a script file\cr
menu & generate menu of choices for user input \cr
pause & wait for user response \cr
function& define function\cr
eval    & execute string with MATLAB expression \cr
feval   & evaluate function specified by string\cr
global  & define global variables\cr
nargchk & validate number of input arguments \cr
\noalign{\hrule}
}}$$

%%%%%%%%%%%%  Text and Strings  %%%%%%%%%%%%%%%%%
$$
\vbox{\offinterlineskip
\halign{
\strut\vrule \quad\bften # \quad\hfil & # \quad\hfil \vrule \cr
\noalign{\hrule}
\multispan2\strut\vrule\hfil\scten Text and Strings \hfil\vrule\cr
\noalign{\hrule}
string & about character strings in MATLAB \cr
abs    & convert string to numeric values\cr
blanks & a string of blanks \cr
eval   & evaluate string with MATLAB expression \cr
num2str& convert number to string\cr
int2str& convert integer to string\cr
str2num& convert string to number \cr
isstr  & true for string variables\cr
strcmp & compare string variables\cr
upper  & convert string to uppercase \cr
lower  & convert string to lowercase \cr
hex2num& convert hex string to floating point number \cr
hex2dec& convert hex string to decimal integer \cr
dec2hex& convert decimal integer to hex string \cr
\noalign{\hrule}
}}$$
\bigskip
%%%%%%%%%%%%%%  Debugging  %%%%%%%%%%%%%
$$
\vbox{\offinterlineskip
\halign{
\strut\vrule \quad\bften # \quad\hfil & # \quad\hfil \vrule \cr
\noalign{\hrule}
\multispan2\strut\vrule\hfil\scten Debugging \hfil\vrule\cr
\noalign{\hrule}
dbstop  & set breakpoint \cr
dbclear & remove breakpoint \cr
dbcont  & remove execution \cr
dbdown  & change local workspace context \cr
dbstack & list who called whom \cr
dbstatus& list all breakpoints \cr
dbstep  & execute one or more lines \cr
dbtype  & list M-file with line numbers \cr
dbup    & change local workspace context \cr
dbdown  & opposite of {\bften dbup} \cr
dbquit  & quit debug mode \cr
\noalign{\hrule}
}}$$
\bigskip
%%%%%%%%%%  Sound Processing  Functions  %%%%%%%%%%%%
$$
\vbox{\offinterlineskip
\halign{
\strut\vrule \quad\bften # \quad\hfil & # \quad\hfil \vrule \cr
\noalign{\hrule}
\multispan2\strut\vrule\hfil\scten Sound Processing Functions \hfil\vrule\cr
\noalign{\hrule}
saxis   & sound axis scaling \cr
sound   & convert vector to sound \cr
auread  & Read Sun audio file \cr
auwrite & Write Sun audio file \cr
lin2mu  & linear to mu-law conversion \cr
mu2lin  & mu-law to linear conversion \cr
\noalign{\hrule}
}}$$

%%%%%%%%%  Elementary Math Functions  %%%%%%%%%%%
$$
\vbox{\offinterlineskip
\halign{
\strut\vrule \quad\bften # \quad\hfil & # \quad\hfil \vrule \cr
\noalign{\hrule}
\multispan2\strut\vrule\hfil \scten Elementary Math Functions \hfil\vrule \cr
\noalign{\hrule}
abs  & absolute value or complex magnitude\cr
angle & phase angle\cr
sqrt  & square root\cr
real  & real part\cr
imag  & imaginary part\cr
conj  & complex conjugate\cr
gcd   & greatest common divisor \cr
lcm   & least common multiple \cr
round & round to nearest integer\cr
fix   & round toward zero\cr
floor & round toward $-\infty$\cr
ceil  & round toward $\infty$\cr
sign  & signum function\cr
rem   & remainder\cr
exp   & exponential base e\cr
log   & natural logarithm\cr
log10 & log base 10\cr
\noalign{\hrule}
}}$$

%%%%%%%%%%%   Trigonometric Functions   %%%%%%%%%%%%%%%
$$
\vbox{\offinterlineskip
\halign{
\strut\vrule \quad\bften # \quad\hfil & # \quad\hfil \vrule \cr
\noalign{\hrule}
\multispan2\strut\vrule\hfil \scten Trigonometric Functions \hfil\vrule \cr
\noalign{\hrule}
sin, asin, sinh, asinh & sine, arcsine, hyperbolic sine, 
                         hyperbolic arcsine \cr 
cos, acos, cosh, acosh & cosine, arccosine, hyperbolic cosine,
                         hyperbolic arccosine \cr
tan, atan, tanh, atanh & tangent, arctangent, hyperbolic tangent,
                         hyperbolic arctangent  \cr
cot, acot, coth, acoth & cotangent, arccotangent, hyperbolic cotan.,
                         hyperbolic arccotan. \cr
sec, asec, sech, asech & secant, arcsecant, hyperbolic secant, 
                         hyperbolic arcsecant \cr
csc, acsc, csch, acsch & cosecant, arccosecant, hyperbolic cosecant,
                         hyperbolic arccosecant \cr
\noalign{\hrule}
}}$$

%%%%%%%%%%%%%%%   Special Functions   %%%%%%%%%%%%%%%%%
$$
\vbox{\offinterlineskip
\halign{
\strut\vrule \quad\bften # \quad\hfil & # \quad\hfil \vrule \cr
\noalign{\hrule}
\multispan2\strut\vrule\hfil \scten Special Functions \hfil\vrule \cr
\noalign{\hrule}
bessel & bessel function\cr
beta  & beta function \cr
gamma & gamma function\cr
rat   & rational approximation\cr
rats  & rational output \cr
erf   & error function\cr
erf\/inv& inverse error function\cr
ellipke& complete elliptic integral \cr
ellipj& Jacobian elliptic integral\cr
expint& exponential integral\cr
log2  & dissect floating point numbers \cr
pow2  & scale floating point numbers \cr
\noalign{\hrule}
}}$$

%%%%%%%%%%  Matrix Decompositions and Factorizations  %%%%%%%%% 
$$
\vbox{\offinterlineskip
\halign{
\strut\vrule \quad\bften # \quad\hfil & # \quad\hfil \vrule \cr
\noalign{\hrule}
\multispan2\strut\vrule\hfil\scten Matrix Decompositions and Factorizations 
                                                     \hfil\vrule\cr
\noalign{\hrule}
inv  & inverse\cr
lu   & factors from Gaussian elimination\cr
rref & reduced row echelon form\cr
chol & Cholesky factorization\cr
qr   & orthogonal-triangular decomposition\cr
nnls & nonnegative least squares\cr
lscov& least squares in presence of know covariance \cr
null & null space\cr
orth & orthogonalization\cr
eig  & eigenvalues and eigenvectors\cr
hess & Hessenberg form\cr
schur& Schur decomposition\cr
cdf2rdf & complex diagonal form to real block diagonal form\cr
rsf2csf & real block diagonal form to complex diagonal form \cr
balance & diagonal scaling for eigenvalue accuracy \cr
qz   & generalized eigenvalues \cr
polyeig & polynomial eigenvalue solver \cr
svd  & singular value decomposition\cr
pinv & pseudoinverse\cr
\noalign{\hrule}
}}$$

\bigskip
%%%%%%%%%%%%  Matrix Conditioning  %%%%%%%%%%%%%
$$
\vbox{\offinterlineskip
\halign{
\strut\vrule \quad\bften # \quad\hfil & # \quad\hfil \vrule \cr
\noalign{\hrule}
\multispan2\strut\vrule\hfil\scten Matrix Conditioning \hfil\vrule\cr
\noalign{\hrule}
cond & condition number in 2-norm\cr
rcond& LINPACK reciprocal condition number estimator \cr
condest & Hager/Higham condition number estimator \cr
norm & 1-norm,2-norm,F-norm,$\infty$-norm\cr
normest & 2-norm estimator \cr
rank & rank\cr
\noalign{\hrule}
}}$$

\bigskip
%%%%%%%%%%%%  Elementary Matrix Functions  %%%%%%%%%%%%%%%
$$
\vbox{\offinterlineskip
\halign{
\strut\vrule \quad\bften # \quad\hfil & # \quad\hfil \vrule \cr
\noalign{\hrule}
\multispan2\strut\vrule\hfil\scten Elementary Matrix Functions \hfil\vrule\cr
\noalign{\hrule}
expm & matrix exponential\cr
expm1& M-file implementation of {\bften expm} \cr
expm2& matrix exponential via Taylor series \cr
expm3& matrix exponential via eigenvalues and eigenvectors \cr
logm & matrix logarithm\cr
sqrtm& matrix square root\cr
funm & evaluate general matrix function\cr
poly & characteristic polynomial\cr
det  & determinant\cr
trace & trace\cr
\noalign{\hrule}
}}$$

%%%%%%%%%%%%%%%%  Polynomials  %%%%%%%%%%%%%%%%
$$
\vbox{\offinterlineskip
\halign{
\strut\vrule \quad\bften # \quad\hfil & # \quad\hfil \vrule \cr
\noalign{\hrule}
\multispan2\strut\vrule\hfil\scten Polynomials \hfil\vrule\cr
\noalign{\hrule}
poly   & construct polynomial with specified roots\cr
roots  & polynomial roots---companion matrix method\cr
roots1 & polynomial roots---Laguerre's method\cr
polyval& evaluate polynomial \cr
polyvalm& evaluate polynomial with matrix argument \cr
conv   & multiply polynomials\cr
deconv & divide polynomials \cr
residue& partial-fraction expansion (residues)\cr
polyfit& fit polynomial to data\cr
polyder& differentiate polynomial \cr
\noalign{\hrule}
}}$$

%%%%%%%%%%%%%%%  Column-wise Data Analysis  %%%%%%%%%%%%%%
$$
\vbox{\offinterlineskip
\halign{
\strut\vrule \quad\bften # \quad\hfil & # \quad\hfil \vrule \cr
\noalign{\hrule}
\multispan2\strut\vrule\hfil\scten Column-wise Data Analysis \hfil\vrule\cr
\noalign{\hrule}
max   & largest component \cr
min   & smallest component\cr
mean  & average or mean value\cr
median& median value\cr
std   & standard deviation\cr
sort  & sort in ascending order \cr
sum   & sum of elements\cr
prod  & product of elements\cr
cumsum& cumulative sum of elements\cr
cumprod& cumulative product of elements\cr
hist  & histogram\cr
\noalign{\hrule}
}}$$

%%%%%%%%%%%  Signal Processing  %%%%%%%%%%%%%%%
$$
\vbox{\offinterlineskip
\halign{
\strut\vrule \quad\bften # \quad\hfil & # \quad\hfil \vrule \cr
\noalign{\hrule}
\multispan2\strut\vrule\hfil\scten Signal Processing \hfil\vrule\cr
\noalign{\hrule}
abs   & complex magnitude\cr
angle & phase angle\cr
conv  & convolution and polynomial multiplication \cr
deconv& deconvolution and polynomial division\cr
corrcoef & correlation coefficients\cr
cov   & covariance matrix \cr
filter & one-dimensional digital filter \cr
filter2& two-dimensional digital filter \cr
cplxpair & sort numbers into complex pairs\cr
unwrap & remove phase angle jumps across 360$^\circ$ boundaries \cr
nextpow2& next higher power of 2 \cr
fft   & radix-2 fast Fourier transform\cr
fft2  & two-dimensional FFT\cr
ifft  & inverse fast Fourier transform\cr
ifft2 & inverse 2-D FFT\cr
fftshift& zero-th lag to center of spectrum \cr
\noalign{\hrule}
}}$$

%%%%%%%%%%  Finite Differences and Data Interpolation  %%%%%%%%%%%%%%%%
$$
\vbox{\offinterlineskip
\halign{
\strut\vrule \quad\bften # \quad\hfil & # \quad\hfil \vrule \cr
\noalign{\hrule}
\multispan2\strut\vrule\hfil\scten 
Finite Differences and Data Interpolation \hfil\vrule\cr
\noalign{\hrule}
diff  & approximate derivatives\cr
gradient & approximate gradient \cr
del2 & five point discrete Laplacian \cr
subspace & angle between two subspaces \cr
spline  & cubic spline interpolation \cr
interp1 & 1-D data interpolation \cr
interp2 & 2-D data interpolation \cr
interpft& 1-D data interpolation via FFT method \cr
griddata& data gridding \cr
\noalign{\hrule}
}}$$
\bigskip
%%%%%%%%%  Numerical Integration  %%%%%%%%%%%%%%%%%%
$$
\vbox{\offinterlineskip
\halign{
\strut\vrule \quad\bften # \quad\hfil & # \quad\hfil \vrule \cr
\noalign{\hrule}
\multispan2\strut\vrule\hfil\scten Numerical Integration\hfil\vrule\cr
\noalign{\hrule}
quad  & adaptive 2-panel Simpson's Rule \cr
quad8 & adaptive 8-panel Newton-Cotes Rule \cr
trapz & trapezoidal method \cr
\noalign{\hrule}
}}$$
\bigskip
%%%%%%%%%  Differential Equation Solution  %%%%%%%%
$$
\vbox{\offinterlineskip
\halign{
\strut\vrule \quad\bften # \quad\hfil & # \quad\hfil \vrule \cr
\noalign{\hrule}
\multispan2\strut\vrule\hfil\scten Differential Equation Solution\hfil\vrule\cr
\noalign{\hrule}
ode23 & 2nd/3rd order Runge-Kutta method\cr
ode23p& solve via {\bften ode23}, displaying plot \cr
ode45 & 4th/5th order Runge-Kutta-Fehlberg method\cr
\noalign{\hrule}
}}$$
\bigskip
%%%%%%%%%  Nonlinear Equations and Optimization  %%%%%%%
$$
\vbox{\offinterlineskip
\halign{
\strut\vrule \quad\bften # \quad\hfil & # \quad\hfil \vrule \cr
\noalign{\hrule}
\multispan2\strut\vrule\hfil\scten Nonlinear Equations and 
                                   Optimization \hfil\vrule\cr
\noalign{\hrule}
fmin  & minimize function of one variable\cr
fmins & minimize function of several variables\cr
fsolve & solution to a system of nonlinear equations\cr
       & (find zeros of a function of several variables)\cr
fzero  & find zero of function of one variable\cr
fplot  & plot graph of a function \cr
\noalign{\hrule}
}}$$

\newpage
%%%%%%%%%%%%%%%%%  Two Dimensional Graphs  %%%%%%%%%%%%%%%%%
$$
\vbox{\offinterlineskip
\halign{
\strut\vrule \quad\bften # \quad\hfil & # \quad\hfil \vrule \cr
\noalign{\hrule}
\multispan2\strut\vrule\hfil\scten Two Dimensional Graphs \hfil\vrule\cr
\noalign{\hrule}
plot   & linear plot \cr
loglog & log-log scale plot \cr
semilogx& semilog scale plot \cr
semilogy& semilog scale plot \cr
fill   & draw filled 2-D polygons \cr
polar  & polar coordinate plot \cr
bar    & bar graph \cr
stairs & stairstep plot \cr
errorbar& error bar plot \cr
hist   & histogram plot \cr
rose   & angle histogram plot \cr
compass& compass plot \cr
feather& feather plot \cr
fplot  & plot function \cr
\noalign{\hrule}
}}$$

%%%%%%%%%%  Graph Annotation  %%%%%%%%%%%%%%%%
$$
\vbox{\offinterlineskip
\halign{
\strut\vrule \quad\bften # \quad\hfil & # \quad\hfil \vrule \cr
\noalign{\hrule}
\multispan2\strut\vrule\hfil\scten Graph Annotation \hfil\vrule\cr
\noalign{\hrule}
title  & graph title\cr
xlabel & x-axis label\cr
ylabel & y-axis label\cr
zlabel & z-axis label for 3-D plots \cr
grid   & grid lines\cr
text   & text annotation \cr
gtext  & mouse placement of text\cr
ginput & graphical input from mouse\cr
\noalign{\hrule}
}}$$

%%%%%%%%%%  Figure Window/Axis Creation and Control  %%%%%%%%%%%%
$$
\vbox{\offinterlineskip
\halign{
\strut\vrule \quad\bften # \quad\hfil & # \quad\hfil \vrule \cr
\noalign{\hrule}
\multispan2\strut\vrule\hfil\scten Figure Window/Axis Creation
         and Control\hfil\vrule\cr
\noalign{\hrule}
figure & create figure (graph window) \cr
gcf    & get handle to current figure \cr
clf    & clear current figure \cr
close  & close figure \cr
hold   & hold current graph \cr
ishold & return hold status \cr
subplot& create axes in tiled positions \cr
axes   & create axes in arbitrary positions \cr
gca    & get handle to to current axes \cr
axis   & control axis scaling and appearance \cr
caxis  & control pseudocolor axis scaling \cr
whitebg& change default background color to white \cr
cinvert& invert black/white objects \cr
\noalign{\hrule}
}}$$

%%%%%%%%%%  Graph Hardcopy and Storage  %%%%%%%%%%%%
$$
\vbox{\offinterlineskip
\halign{
\strut\vrule \quad\bften # \quad\hfil & # \quad\hfil \vrule \cr
\noalign{\hrule}
\multispan2\strut\vrule\hfil\scten Graph Hardcopy and Storage\hfil\vrule\cr
\noalign{\hrule}
print  & print graph or save graph to file \cr
printopt& configure local printer defaults \cr
orient & set paper orientation \cr
\noalign{\hrule}
}}$$

%%%%%%%%%%  Three Dimensional Graphs  %%%%%%%%%%%%%%%%
$$
\vbox{\offinterlineskip
\halign{
\strut\vrule \quad\bften # \quad\hfil & # \quad\hfil \vrule \cr
\noalign{\hrule}
\multispan2\strut\vrule\hfil\scten Three Dimensional Graphs \hfil\vrule\cr
\noalign{\hrule}
mesh   & 3-D mesh surface \cr
meshc  & combination mesh/contour plot \cr
meshz  & 3-D mesh with zero plane \cr
surf   & 3-D shaded surface \cr
surfc  & combination surface/contour plot \cr
surf\/l& 3-D shaded surface with lighting \cr
plot3  & plot lines and points in 3-D space \cr
fill3  & draw filled 3-D polygons in 3-D space \cr
contour& contour plot \cr
contour3& 3-D contour plot \cr
clabel & contour plot elevation labels \cr
contourc& contour plot computation (used by {\tt contour}) \cr
pcolor & pseudocolor (checkerboard) plot \cr
quiver & quiver plot \cr
image  & display image \cr
waterfall& waterfall plot \cr
slice  & volumetric visualization plot \cr
\noalign{\hrule}
}}$$

%%%%%%%%%%  3-D Graph Appearance  %%%%%%%%%%%%%%%%
$$
\vbox{\offinterlineskip
\halign{
\strut\vrule \quad\bften # \quad\hfil & # \quad\hfil \vrule \cr
\noalign{\hrule}
\multispan2\strut\vrule\hfil\scten 3-D Graph Appearance \hfil\vrule\cr
\noalign{\hrule}
view   & 3-D graph viewpoint specification \cr
viewmtx & view transformation matrices \cr
hidden & mesh hidden line removal mode \cr
shading& color shading mode \cr
axis   & axis scaling and apearance \cr
caxis  & pseudocolor axis scaling \cr
specular& specular reflectance \cr
diffuse& diffuse reflectance \cr
surfnorm& surface normals \cr
colormap& color lookup table (see below) \cr
brighten& brighten or darken color map \cr
spinmap& spin color map \cr
rgbplot& plot colormap \cr
hsv2rgb& hsv to rgb color map conversion \cr
rgb2hsv& rgb to hsv color map conversion \cr
\noalign{\hrule}
}}$$

%%%%%%%%%%  Color Maps  %%%%%%%%%%%
$$
\vbox{\offinterlineskip
\halign{
\strut\vrule \quad\bften # \quad\hfil & # \quad\hfil \vrule \cr
\noalign{\hrule}
\multispan2\strut\vrule\hfil\scten Color Maps \hfil\vrule\cr
\noalign{\hrule}
hsv    & hue-saturation-value (default)\cr
jet    & variant of {\tt hsv} \cr
gray   & linear gray-scale \cr
hot    & black-red-yellow-white \cr
cool   & shades of cyan and magenta \cr
bone   & gray-scale with tinge of blue \cr
copper & linear copper tone \cr
pink   & pastel shades of pink \cr
flag   & alternating red, white, blue, and black \cr
\noalign{\hrule}
}}$$

%%%%%%%%%%  3-D Objects  %%%%%%%%%%%
$$
\vbox{\offinterlineskip
\halign{
\strut\vrule \quad\bften # \quad\hfil & # \quad\hfil \vrule \cr
\noalign{\hrule}
\multispan2\strut\vrule\hfil\scten 3-D Objects \hfil\vrule\cr
\noalign{\hrule}
sphere  & generate sphere \cr
cylinder& generate cylinder \cr
peaks   & generate demo surface \cr
\noalign{\hrule}
}}$$

%%%%%%%%%%  Movies and Animation  %%%%%%%%%%%
$$
\vbox{\offinterlineskip
\halign{
\strut\vrule \quad\bften # \quad\hfil & # \quad\hfil \vrule \cr
\noalign{\hrule}
\multispan2\strut\vrule\hfil\scten Movies and Animation \hfil\vrule\cr
\noalign{\hrule}
moviein   & initialize movie frame memory \cr
getframe  & get movie frame \cr
movie     & play recorded movie frames \cr
\noalign{\hrule}
}}$$

%%%%%%%%%%  Handle Graphics Objects  %%%%%%%%%%%
$$
\vbox{\offinterlineskip
\halign{
\strut\vrule \quad\bften # \quad\hfil & # \quad\hfil \vrule \cr
\noalign{\hrule}
\multispan2\strut\vrule\hfil\scten Handle Graphics Objects \hfil\vrule\cr
\noalign{\hrule}
figure   & create figure window \cr
axes     & create axes \cr
line     & create line \cr
text     & create text \cr
patch    & create patch \cr
surface  & create surface \cr
image    & create image \cr
uicontrol& create user interface control \cr
uimenu   & create user interface menu \cr
\noalign{\hrule}
}}$$

%%%%%%%%%%  Handle Graphics Operations  %%%%%%%%%%%
$$
\vbox{\offinterlineskip
\halign{
\strut\vrule \quad\bften # \quad\hfil & # \quad\hfil \vrule \cr
\noalign{\hrule}
\multispan2\strut\vrule\hfil\scten Handle Graphics Operations \hfil\vrule\cr
\noalign{\hrule}
set     & set object properties \cr
get     & get object properties \cr
reset   & reset object properties \cr
delete  & delete object \cr
drawnow & flush pending graphics events \cr
\noalign{\hrule}
}}$$

%%%%%%%%%%  Sparse Matrix Functions  %%%%%%%%%%%%
$$
\vbox{\offinterlineskip
\halign{
\strut\vrule \quad\bften # \quad\hfil & # \quad\hfil \vrule \cr
\noalign{\hrule}
\multispan2\strut\vrule\hfil\scten Sparse Matrix Functions \hfil\vrule\cr
\noalign{\hrule}
spdiags & sparse matrix formed from diagonals \cr
speye   & sparse identity matrix \cr
sprandn & sparse random matrix \cr
spones  & replace nonzero entries with ones \cr
sprandsym& sparse symmetric random matrix \cr
spfun   & apply function to nonzero entries \cr
&\cr
sparse  & create sparse matrix; convert full matrix to sparse \cr
full    & convert sparse matrix to full matrix \cr
find    & find indices of nonzero entries \cr
spconvert& convert from sparse matrix external format \cr
&\cr
issparse& true if matrix is sparse \cr
nnz     & number of nonzero entries \cr
nonzeros& nonzero entries \cr
nzmax   & amount of storage allocated for nonzero entries \cr
spalloc & allocate memory for nonzero entries \cr
&\cr
spy     & visualize sparsity structure \cr
gplot   & plot graph, as in ``graph theory'' \cr
&\cr
colmmd  & column minimum degree \cr
colperm & order columns based on nonzero count \cr
dmperm  & Dulmage-Mendelsohn decomposition \cr
randperm& random permutation vector \cr
symmmd  & symmetric minimum degree \cr
symrcm  & reverse Cuthill-McKee ordering \cr
&\cr
condest & estimate 1-norm condition \cr
normest & estimate 2-norm  \cr
sprank  & structural rank \cr
&\cr
spaugment& form least squares augmented system \cr
spparms & set parameters for sparse matrix routines \cr
symbfact& symbolic factorization analysis \cr
sparsefun& sparse auxillary functions and parameters \cr
\noalign{\hrule}
}}$$

\bye

%%%%%%%%%%  Low-Level File I/O  Functions  %%%%%%%%%%%%
$$
\vbox{\offinterlineskip
\halign{
\strut\vrule \quad\bften # \quad\hfil & # \quad\hfil \vrule \cr
\noalign{\hrule}
\multispan2\strut\vrule\hfil\scten Low-level I/O Functions \hfil\vrule\cr
\noalign{\hrule}
fclose  & close file \cr
fopen   & open file \cr
fread   & read binary data from file \cr
fwrite  & write binary data to file \cr
fgetl   & readline from file, discard newline character \cr
fgets   & readline from file, keep newline character \cr
fprintf & write formatted data to file \cr
fscanf  & read formatted data from file \cr
sprintf & write formatted data to string \cr
sscanf  & read string under format control \cr
ferror  & inquire file I/O error status \cr
frewind & rewind file \cr
fseek   & set file position indicator \cr
ftell   & get file position indicator \cr
\noalign{\hrule}
}}$$

\bye
