You are on page 1of 22

A

MATLAB Quick Reference


Introduction . . . . . . . . . . . . . . . . . . . . . 2
General Purpose Commands . . . . . . . . . . . . . 3
Operators and Special Characters . . . . . . . . . . . 4
Logical Functions . . . . . . . . . . . . . . . . . . 5
Language Constructs and Debugging . . . . . . . . . 5
Elementary Matrices and Matrix Manipulation . . . . . 6
Specialized Matrices . . . . . . . . . . . . . . . . . 7
Elementary Math Functions . . . . . . . . . . . . . . 7
Specialized Math Functions . . . . . . . . . . . . . . 8
Coordinate System Conversion . . . . . . . . . . . . 9
Matrix Functions - Numerical Linear Algebra . . . . . . 9
Data Analysis and Fourier Transform Functions . . . .10
Polynomial and Interpolation Functions . . . . . . . .11
Function Functions - Nonlinear Numerical Methods . . .12
Sparse Matrix Functions . . . . . . . . . . . . . . .12
Sound Processing Functions . . . . . . . . . . . . .13
Character String Functions . . . . . . . . . . . . . .14
Low-Level File I/O Functions . . . . . . . . . . . . .14
Bitwise Functions . . . . . . . . . . . . . . . . . .15
Structure Functions . . . . . . . . . . . . . . . . .15
Object Functions . . . . . . . . . . . . . . . . . . .16
Cell Array Functions . . . . . . . . . . . . . . . . .16
Multidimensional Array Functions . . . . . . . . . . .16
Plotting and Data Visualization . . . . . . . . . . . .16
Graphical User Interface Creation . . . . . . . . . . .20
MATLAB Quick Reference

Introduction
This appendix lists the MATLAB functions as they are grouped in the Help
Desk by subject. Each table contains the function names and brief descriptions.
For complete information about any of these functions, refer to the Help Desk
and either:

• Select the function from the MATLAB Functions list (By Subject or
By Index), or
• Type the function name in the Go to MATLAB function field and click Go.

Note If you are viewing this book from the Help Desk, you can click on any
function name and jump directly to the corresponding MATLAB function
page.

2
General Purpose Commands

General Purpose Commands Managing Commands and Functions


(Continued)
This set of functions lets you start and stop
ver Display version information for
MATLAB, work with files and the operating MATLAB, Simulink, and
system, control the command window, and manage toolboxes
the environment, variables, and the workspace.
version MATLAB version number
web Point Web browser at file or Web
Managing Commands and Functions
site
what Directory listing of M-files,
addpath Add directories to MATLAB’s
MAT-files, and MEX-files
search path
whatsnew Display README files for
doc Display HTML documentation
MATLAB and toolboxes
in Web browser
which Locate functions and files
docopt Display location of help file
directory for UNIX platforms
Managing Variables and the Workspace
help Online help for MATLAB
functions and M-files clear Remove items from memory
helpdesk Display Help Desk page in Web disp Display text or array
browser, giving access to length Length of vector
extensive help load Retrieve variables from disk
helpwin Display Help Window, providing mlock Prevent M-file clearing
access to help for all commands
munlock Allow M-file clearing
lasterr Last error message
openvar Open workspace variable in
lastwarn Last warning message Array Editor for graphical
lookfor Keyword search through all help editing
entries pack Consolidate workspace memory
partialpath Partial pathname save Save workspace variables on
path Control MATLAB’s directory disk
search path saveas Save figure or model using
pathtool Start Path Browser, a GUI for specified format
viewing and modifying size Array dimensions
MATLAB’s path
who, whos List directory of variables in
profile Start the M-file profiler, a utility memory
for debugging and optimizing
code
workspace Display the Workspace Browser,
a GUI for managing the
profreport Generate a profile report workspace
rmpath Remove directories from
MATLAB’s search path
type List file

3
MATLAB Quick Reference

Controlling the Command Window Starting and Quitting MATLAB


clc Clear command window matlabrc MATLAB startup M-file
echo Echo M-files during execution quit Terminate MATLAB
format Control the output display startup MATLAB startup M-file
format
home Move the cursor to the home Operators and Special Characters
position
more Control paged output for the These are the actual operators you use to enter and
command window manipulate data, for example, matrix
multiplication, array multiplication, and line
continuation.
Working with Files and the Operating
Environment
Operators and Special Characters
cd Change working directory
+ Plus
copyfile Copy file
- Minus
delete Delete files and graphics objects
* Matrix multiplication
diary Save session in a disk file
.* Array multiplication
dir Directory listing
^ Matrix power
edit Edit an M-file
.^ Array power
fileparts Filename parts
kron Kronecker tensor product
fullfile Build full filename from parts
\ Backslash or left division
inmem Functions in memory
/ Slash or right division
ls List directory on UNIX
./ and .\ Array division, right and left
matlabroot Root directory of MATLAB
installation : Colon
mkdir Make directory ( ) Parentheses
open Open files based on extension [ ] Brackets
pwd Display current directory {} Curly braces
tempdir Return the name of the system’s . Decimal point
temporary directory ... Continuation
tempname Unique name for temporary file , Comma
! Execute operating system ; Semicolon
command % Comment
! Exclamation point
' Transpose and quote
.' Nonconjugated transpose
= Assignment

4
Logical Functions

Operators and Special Characters (Continued)


== Equality MATLAB as a Programming Language
< > Relational operators
builtin Execute builtin function from
overloaded method
& Logical and
eval Interpret strings containing
| Logical or MATLAB expressions
~ Logical not evalc Evaluate MATLAB expression
xor Logical exclusive or with capture
evalin Evaluate expression in
Logical Functions workspace
This set of functions performs logical operations feval Function evaluation
such as checking if a file or variable exists and function Function M-files
testing if all elements in an array are nonzero. global Define global variables
“Operators and Special Characters” contains other nargchk Check number of input
operators that perform logical operations. arguments
persistent Define persistent variable
Logical Functions script Script M-files
all Test to determine if all elements
are nonzero
Control Flow
any Test for any nonzeros
break Terminate execution of for loop
exist Check if a variable or file exists or while loop
find Find indices and values of case Case switch
nonzero elements
catch Begin catch block
is* Detect state
else Conditionally execute
isa Detect an object of a given class statements
logical Convert numeric values to elseif Conditionally execute
logical statements
mislocked True if M-file cannot be cleared end Terminate for, while, switch,
try, and if statements or
Language Constructs and Debugging indicate last
error Display error messages
These functions let you work with MATLAB as a
for Repeat statements a specific
programming language. For example, you can
number of times
control program flow, define global variables,
perform interactive input, and debug your code. if Conditionally execute
statements
otherwise Default part of switch
statement
return Return to the invoking function

5
MATLAB Quick Reference

Control Flow (Continued) Debugging (Continued)


switch Switch among several cases dbstack Display function call stack
based on expression dbstatus List all breakpoints
try Begin try block dbstep Execute one or more lines from a
warning Display warning message breakpoint
while Repeat statements an indefinite dbstop Set breakpoints in an M-file
number of times function
dbtype List M-file with line numbers
Interactive Input dbup Change local workspace context
input Request user input
keyboard Invoke the keyboard in an M-file Elementary Matrices and Matrix
menu Generate a menu of choices for Manipulation
user input
Using these functions you can manipulate
pause Halt execution temporarily matrices, and access time, date, special variables,
and constants, functions.
Object-Oriented Programming
class Create object or return class of Elementary Matrices and Arrays
object blkdiag Construct a block diagonal
double Convert to double precision matrix from input arguments
inferiorto Inferior class relationship eye Identity matrix
inline Construct an inline object linspace Generate linearly spaced vectors
int8, int16, int32 Convert to signed integer logspace Generate logarithmically spaced
isa Detect an object of a given class vectors
loadobj Extends the load function for ones Create an array of all ones
user objects rand Uniformly distributed random
saveobj Save filter for objects numbers and arrays
single Convert to single precision randn Normally distributed random
numbers and arrays
superiorto Superior class relationship
zeros Create an array of all zeros
uint8, uint16, Convert to unsigned integer
uint32 : (colon) Regularly spaced vector

Debugging Special Variables and Constants


dbclear Clear breakpoints ans The most recent answer
dbcont Resume execution computer Identify the computer on which
dbdown Change local workspace context MATLAB is running
dbmex Enable MEX-file debugging
eps Floating-point relative accuracy
flops Count floating-point operations
dbquit Quit debug mode
i Imaginary unit

6
Specialized Matrices

Special Variables and Constants (Continued) Matrix Manipulation (Continued)


Inf Infinity rot90 Rotate matrix 90 degrees
inputname Input argument name tril Lower triangular part of a
j Imaginary unit matrix
NaN Not-a-Number triu Upper triangular part of a
matrix
nargin, nargout Number of function arguments
: (colon) Index into array, rearrange
pi Ratio of a circle’s circumference
array
to its diameter,
realmax Largest positive floating-point Specialized Matrices
number
realmin Smallest positive floating-point These functions let you work with matrices such as
number Hadamard, Hankel, Hilbert, and magic squares.
varargin, Pass or return variable numbers
varargout of arguments Specialized Matrices
compan Companion matrix
Time and Dates gallery Test matrices
calendar Calendar hadamard Hadamard matrix
clock Current time as a date vector hankel Hankel matrix
cputime Elapsed CPU time hilb Hilbert matrix
date Current date string invhilb Inverse of the Hilbert matrix
datenum Serial date number magic Magic square
datestr Date string format pascal Pascal matrix
datevec Date components toeplitz Toeplitz matrix
eomday End of month wilkinson Wilkinson’s eigenvalue test
etime Elapsed time matrix
now Current date and time
tic, toc Stopwatch timer Elementary Math Functions
weekday Day of the week These are many of the standard mathematical
functions such as trigonometric, hyperbolic,
Matrix Manipulation logarithmic, and complex number manipulation.
cat Concatenate arrays
diag Diagonal matrices and diagonals Elementary Math Functions
of a matrix abs Absolute value and complex
fliplr Flip matrices left-right magnitude
flipud Flip matrices up-down acos, acosh Inverse cosine and inverse
hyperbolic cosine
repmat Replicate and tile an array
reshape Reshape array

7
MATLAB Quick Reference

Elementary Math Functions (Continued) Elementary Math Functions (Continued)


acot, acoth Inverse cotangent and inverse real Real part of complex number
hyperbolic cotangent rem Remainder after division
acsc, acsch Inverse cosecant and inverse round Round to nearest integer
hyperbolic cosecant
sec, sech Secant and hyperbolic secant
angle Phase angle
sign Signum function
asec, asech Inverse secant and inverse
sin, sinh Sine and hyperbolic sine
hyperbolic secant
sqrt Square root
asin, asinh Inverse sine and inverse
hyperbolic sine tan, tanh Tangent and hyperbolic tangent
atan, atanh Inverse tangent and inverse
hyperbolic tangent Specialized Math Functions
atan2 Four-quadrant inverse tangent This set of functions includes Bessel, elliptic,
ceil Round toward infinity gamma, factorial, and others.
complex Construct complex data from
real and imaginary components Specialized Math Functions
conj Complex conjugate airy Airy functions
cos, cosh Cosine and hyperbolic cosine besselh Bessel functions of the third
cot, coth Cotangent and hyperbolic kind (Hankel functions)
cotangent besseli, besselk Modified Bessel functions
csc, csch Cosecant and hyperbolic besselj, bessely Bessel functions
cosecant beta, betainc, beta, betainc, betaln
exp Exponential betaln
fix Round towards zero ellipj Jacobi elliptic functions
floor Round towards minus infinity ellipke Complete elliptic integrals of the
gcd Greatest common divisor first and second kind
imag Imaginary part of a complex erf, erfc, erfcx, Error functions
erfinv
number
expint Exponential integral
lcm Least common multiple
factorial Factorial function
log Natural logarithm
log2 Base 2 logarithm and dissect
gamma, gammainc, Gamma functions
gammaln
floating-point numbers into
exponent and legendre Associated Legendre functions
log10 Common (base 10) logarithm pow2 Base 2 power and scale
floating-point numbers
mod Modulus (signed remainder
after division) rat, rats Rational fraction approximation
nchoosek Binomial coefficient or all
combinations

8
Coordinate System Conversion

Coordinate System Conversion


Linear Equations
Using these functions you can transform chol Cholesky factorization
Cartesian coordinates to polar, cylindrical, or
inv Matrix inverse
spherical, and vice versa.
lscov Least squares solution in the
presence of known covariance
Coordinate System Conversion
lu LU matrix factorization
cart2pol Transform Cartesian
coordinates to polar or lsqnonneg Nonnegative least squares
cylindrical pinv Moore-Penrose pseudoinverse of
cart2sph Transform Cartesian a matrix
coordinates to spherical qr Orthogonal-triangular
pol2cart Transform polar or cylindrical decomposition
coordinates to Cartesian
sph2cart Transform spherical coordinates Eigenvalues and Singular Values
to Cartesian balance Improve accuracy of computed
eigenvalues
Matrix Functions - Numerical Linear cdf2rdf Convert complex diagonal form
Algebra to real block diagonal form
eig Eigenvalues and eigenvectors
These functions let you perform matrix analysis
including matrix determinant, rank, reduced row gsvd Generalized singular value
echelon form, eigenvalues, and inverses. decomposition
hess Hessenberg form of a matrix
Matrix Analysis poly Polynomial with specified roots
cond Condition number with respect qz QZ factorization for generalized
to inversion eigenvalues
condeig Condition number with respect rsf2csf Convert real Schur form to
to eigenvalues complex Schur form
det Matrix determinant schur Schur decomposition
norm Vector and matrix norms svd Singular value decomposition
null Null space of a matrix
orth Range space of a matrix Matrix Functions
rank Rank of a matrix expm Matrix exponential
rcond Matrix reciprocal condition funm Evaluate functions of a matrix
number estimate logm Matrix logarithm
rref, rrefmovie Reduced row echelon form sqrtm Matrix square root
subspace Angle between two subspaces
trace Sum of diagonal elements

9
MATLAB Quick Reference

Basic Operations (Continued)


Low Level Functions sort Sort elements in ascending
qrdelete Delete column from QR order
factorization sortrows Sort rows in ascending order
qrinsert Insert column in QR std Standard deviation
factorization
sum Sum of array elements

Data Analysis and Fourier Transform trapz Trapezoidal numerical


integration
Functions
tsearch Search for enclosing Delaunay
Using the data analysis functions, you can find triangle
permutations, prime numbers, mean, median, var Variance
variance, correlation, and perform convolutions voronoi Voronoi diagram
and other standard array manipulations. A set of
vector functions lets you operate on vectors to find Finite Differences
cross product, union, and other standard vector
del2 Discrete Laplacian
manipulations. The Fourier transform functions
let you perform discrete Fourier transformations in diff Differences and approximate
derivatives
one or more dimensions and their inverses.
gradient Numerical gradient
Basic Operations
convhull Convex hull Correlation
cumprod Cumulative product corrcoef Correlation coefficients
cumsum Cumulative sum cov Covariance matrix
cumtrapz Cumulative trapezoidal
numerical integration Filtering and Convolution
delaunay Delaunay triangulation conv Convolution and polynomial
multiplication
dsearch Search for nearest point
conv2 Two-dimensional convolution
factor Prime factors
deconv Deconvolution and polynomial
inpolygon Detect points inside a polygonal
division
region
filter Filter data with an infinite
max Maximum elements of an array
impulse response (IIR) or finite
mean Average or mean value of arrays impulse response
median Median value of arrays filter2 Two-dimensional digital
min Minimum elements of an array filtering
perms All possible permutations
polyarea Area of polygon
primes Generate list of prime numbers
prod Product of array elements

10
Polynomial and Interpolation Functions

evaluate. The data interpolation functions let you


Fourier Transforms perform interpolation in one, two, three, and
abs Absolute value and complex higher dimensions.
magnitude
angle Phase angle Polynomials
cplxpair Sort complex numbers into conv Convolution and polynomial
complex conjugate pairs multiplication
fft One-dimensional fast Fourier deconv Deconvolution and polynomial
transform division
fft2 Two-dimensional fast Fourier poly Polynomial with specified roots
transform polyder Polynomial derivative
fftshift Shift DC component of fast polyeig Polynomial eigenvalue problem
Fourier transform to center of polyfit Polynomial curve fitting
spectrum
polyval Polynomial evaluation
ifft Inverse one-dimensional fast
polyvalm Matrix polynomial evaluation
Fourier transform
residue Convert between partial fraction
ifft2 Inverse two-dimensional fast
expansion and polynomial
Fourier transform
coefficients
ifftn Inverse multidimensional fast
roots Polynomial roots
Fourier transform
ifftshift Inverse FFT shift
Data Interpolation
nextpow2 Next power of two
griddata Data gridding
unwrap Correct phase angles
interp1 One-dimensional data
interpolation (table lookup)
Vector Functions
interp2 Two-dimensional data
cross Vector cross product interpolation (table lookup)
intersect Set intersection of two vectors interp3 Three-dimensional data
ismember Detect members of a set interpolation (table lookup)
setdiff Return the set difference of two interpft One-dimensional interpolation
vector using the FFT method
setxor Set exclusive or of two vectors interpn Multidimensional data
union Set union of two vectors interpolation (table lookup)
unique Unique elements of a vector meshgrid Generate X and Y matrices for
three-dimensional plots
Polynomial and Interpolation ndgrid Generate arrays for
Functions multidimensional functions and
interpolation
These functions let you operate on polynomials spline Cubic spline interpolation
such as multiply, divide, find derivatives, and

11
MATLAB Quick Reference

Function Functions - Nonlinear Elementary Sparse Matrices (Continued)


Numerical Methods sprand Sparse uniformly distributed
random matrix
Using these functions you can solve differential
equations, perform numerical evaluation of sprandn Sparse normally distributed
random matrix
integrals, and optimize functions.
sprandsym Sparse symmetric random
matrix
Function Functions - Nonlinear Numerical
Methods
Full to Sparse Conversion
dblquad Numerical double integration
find Find indices and values of
fminbnd Minimize a function of one
nonzero elements
variable
full Convert sparse matrix to full
fminsearch Minimize a function of several
matrix
variables
sparse Create sparse matrix
fzero Zero of a function of one variable
spconvert Import matrix from sparse
ode45, ode23, Solve differential equations
matrix external format
ode113, ode15s,
ode23s, ode23t,
ode23tb Working with Nonzero Entries of Sparse
odefile Define a differential equation Matrices
problem for ODE solvers nnz Number of nonzero matrix
odeget Extract properties from options elements
structure created with odeset nonzeros Nonzero matrix elements
odeset Create or alter options structure nzmax Amount of storage allocated for
for input to ODE solvers nonzero matrix elements
quad, quad8 Numerical evaluation of spalloc Allocate space for sparse matrix
integrals spfun Apply function to nonzero sparse
vectorize Vectorize expression matrix elements
spones Replace nonzero sparse matrix
Sparse Matrix Functions elements with ones

These functions allow you to operate on a special


Visualizing Sparse Matrices
type of matrix, sparse. Using these functions you
can convert full to sparse, visualize, and operate on spy Visualize sparsity pattern
these matrices.
Reordering Algorithms
Elementary Sparse Matrices colmmd Sparse column minimum degree
spdiags Extract and create sparse band permutation
and diagonal matrices colperm Sparse column permutation
speye Sparse identity matrix based on nonzero count

12
Sound Processing Functions

Reordering Algorithms (Continued)


dmperm Dulmage-Mendelsohn Sparse Eigenvalues and Singular Values
decomposition eigs Find eigenvalues and
randperm Random permutation eigenvectors
symmmd Sparse symmetric minimum
svds Find singular values
degree ordering
symrcm Sparse reverse Cuthill-McKee Miscellaneous
ordering spparms Set parameters for sparse
matrix routines
Norm, Condition Number, and Rank
condest 1-norm matrix condition number Sound Processing Functions
estimate
The sound processing functions let you convert
normest 2-norm estimate
signals, and read and write .au and .wav sound
files.
Sparse Systems of Linear Equations
bicg BiConjugate Gradients method General Sound Functions
bicgstab BiConjugate Gradients lin2mu Convert linear audio signal to
Stabilized method mu-law
cgs Conjugate Gradients Squared mu2lin Convert mu-law audio signal to
method linear
cholinc Sparse Incomplete Cholesky and sound Convert vector into sound
Cholesky-Infinity factorizations soundsc Scale data and play as sound
cholupdate Rank 1 update to Cholesky
factorization
SPARCstation-Specific Sound Functions
gmres Generalized Minimum Residual
method (with restarts)
auread Read NeXT/SUN (.au) sound file
auwrite Write NeXT/SUN (.au) sound
luinc Incomplete LU matrix
file
factorizations
pcg Preconditioned Conjugate
Gradients method .WAV Sound Functions
qmr Quasi-Minimal Residual method wavread Read Microsoft WAVE (.wav)
sound file
qr Orthogonal-triangular
decomposition wavwrite Write Microsoft WAVE (.wav)
sound file
qrdelete Delete column from QR
factorization
qrinsert Insert column in QR
factorization
qrupdate Rank 1 update to QR
factorization

13
MATLAB Quick Reference

Character String Functions


String to Number Conversion
This set of functions lets you manipulate strings char Create character array (string)
such as comparison, concatenation, search, and
int2str Integer to string conversion
conversion.
mat2str Convert a matrix into a string
General num2str Number to string conversion
abs Absolute value and complex sprintf Write formatted data to a string
magnitude sscanf Read string under format
eval Interpret strings containing control
MATLAB expressions str2double Convert string to
real Real part of complex number double-precision value
strings MATLAB string handling str2num String to number conversion

String Manipulation Radix Conversion


deblank Strip trailing blanks from the bin2dec Binary to decimal number
end of a string conversion
findstr Find one string within another dec2bin Decimal to binary number
conversion
lower Convert string to lower case
dec2hex Decimal to hexadecimal number
strcat String concatenation
conversion
strcmp Compare strings
hex2dec IEEE hexadecimal to decimal
strcmpi Compare strings ignoring case number conversion
strjust Justify a character array hex2num Hexadecimal to double number
strmatch Find possible matches for a conversion
string
strncmp Compare the first n characters Low-Level File I/O Functions
of two strings
strrep String search and replace The low-level file I/O functions allow you to open
and close files, read and write formatted and
strtok First token in string
unformatted data, operate on files, and perform
strvcat Vertical concatenation of strings other specialized file I/O such as reading and
symvar Determine symbolic variables in writing images and spreadsheets.
an expression
texlabel Produce the TeX format from a File Opening and Closing
character string fclose Close one or more open files
upper Convert string to upper case fopen Open a file or obtain information
about open files

14
Bitwise Functions

Specialized File I/O (Continued)


Unformatted I/O wk1read Read a Lotus123 WK1
fread Read binary data from file spreadsheet file into a matrix
fwrite Write binary data to a file wk1write Write a matrix to a Lotus123
WK1 spreadsheet file
Formatted I/O
fgetl Return the next line of a file as a
Bitwise Functions
string without line terminator(s) These functions let you operate at the bit level
fgets Return the next line of a file as a such as shifting and complementing.
string with line terminator(s)
fprintf Write formatted data to file Bitwise Functions
fscanf Read formatted data from file bitand Bit-wise AND
bitcmp Complement bits
File Positioning bitor Bit-wise OR
feof Test for end-of-file bitmax Maximum floating-point integer
ferror Query MATLAB about errors in bitset Set bit
file input or output
bitshift Bit-wise shift
frewind Rewind an open file
bitget Get bit
fseek Set file position indicator
bitxor Bit-wise XOR
ftell Get file position indicator
Structure Functions
String Conversion
sprintf Write formatted data to a string Structures are arrays whose elements can hold
sscanf Read string under format any MATLAB data type such as text, numeric
control arrays, or other structures. You access structure
elements by name. Use the structure functions to
create and operate on this array type.
Specialized File I/O
dlmread Read an ASCII delimited file
Structure Functions
into a matrix
deal Deal inputs to outputs
dlmwrite Write a matrix to an ASCII
delimited file fieldnames Field names of a structure
hdf HDF interface getfield Get field of structure array
imfinfo Return information about a rmfield Remove structure fields
graphics file setfield Set field of structure array
imread Read image from graphics file struct Create structure array
imwrite Write an image to a graphics file struct2cell Structure to cell array
textread Read formatted data from text conversion
file

15
MATLAB Quick Reference

Object Functions
Multidimensional Array Functions
Using the object functions you can create objects, cat Concatenate arrays
detect objects of a given class, and return the class
flipdim Flip array along a specified
of an object.
dimension
ind2sub Subscripts from linear index
Object Functions
ipermute Inverse permute the dimensions
class Create object or return class of
of a multidimensional array
object
ndgrid Generate arrays for
isa Detect an object of a given class
multidimensional functions and
interpolation
Cell Array Functions ndims Number of array dimensions
Cell arrays are arrays comprised of cells, which can permute Rearrange the dimensions of a
hold any MATLAB data type such as text, numeric multidimensional array
arrays, or other cell arrays. Unlike structures, you reshape Reshape array
access these cells by number. Use the cell array shiftdim Shift dimensions
functions to create and operate on these arrays. squeeze Remove singleton dimensions
sub2ind Single index from subscripts
Cell Array Functions
cell Create cell array Plotting and Data Visualization
cellfun Apply a function to each element
in a cell array This extensive set of functions gives you the ability
cellstr Create cell array of strings from to create basic graphs such as bar, pie, polar, and
character array three-dimensional plots, and advanced graphs
cell2struct Cell array to structure array such as surface, mesh, contour, and volume
conversion visualization plots. In addition, you can use these
celldisp Display cell array contents functions to control lighting, color, view, and many
other fine manipulations.
cellplot Graphically display the
structure of cell arrays
Basic Plots and Graphs
num2cell Convert a numeric array into a
cell array bar Vertical bar chart
barh Horizontal bar chart
Multidimensional Array Functions hist Plot histograms
hold Hold current graph
These functions provide a mechanism for working
loglog Plot using log-log scales
with arrays of dimension greater than 2.
pie Pie plot
plot Plot vectors or matrices.
polar Polar coordinate plot
semilogx Semi-log scale plot

16
Plotting and Data Visualization

Basic Plots and Graphs (Continued) Plot Annotation and Grids (Continued)
semilogy Semi-log scale plot ylabel Y-axis labels for 2-D and 3-D
subplot Create axes in tiled positions plots
zlabel Z-axis labels for 3-D plots
Three-Dimensional Plotting
bar3 Vertical 3-D bar chart Surface, Mesh, and Contour Plots
bar3h Horizontal 3-D bar chart contour Contour (level curves) plot
comet3 Three-dimensional comet plot contourc Contour computation
cylinder Generate cylinder contourf Filled contour plot
fill3 Draw filled 3-D polygons in hidden Mesh hidden line removal mode
3-space meshc Combination mesh/contourplot
plot3 Plot lines and points in 3-D mesh 3-D mesh with reference plane
space peaks A sample function of two
quiver3 Three-dimensional quiver (or variables
velocity) plot surf 3-D shaded surface graph
slice Volumetric slice plot surface Create surface low-level objects
sphere Generate sphere surfc Combination surf/contourplot
stem3 Plot discrete surface data surfl 3-D shaded surface with lighting
waterfall Waterfall plot trimesh Triangular mesh plot
trisurf Triangular surface plot
Plot Annotation and Grids
clabel Add contour labels to a contour Volume Visualization
plot
coneplot Plot velocity vectors as cones in
datetick Date formatted tick labels 3-D vector field
grid Grid lines for 2-D and 3-D plots contourslice Draw contours in volume slice
gtext Place text on a 2-D graph using plane
a mouse isocaps Compute isosurface end-cap
legend Graph legend for lines and geometry
patches isonormals Compute normals of isosurface
plotedit Start plot edit mode to edit and vertices
annotate plots isosurface Extract isosurface data from
plotyy Plot graphs with Y tick labels on volume data
the left and right reducepatch Reduce the number of patch
title Titles for 2-D and 3-D plots faces
xlabel X-axis labels for 2-D and 3-D reducevolume Reduce number of elements in
plots volume data set
shrinkfaces Reduce the size of patch faces
smooth3 Smooth 3-D data

17
MATLAB Quick Reference

Volume Visualization (Continued) Specialized Plotting (Continued)


stream2 Compute 2-D stream line data ezsurfc Easy to use combination surface/
stream3 Compute 3-D stream line data contour plotter
streamline Draw stream lines from 2- or feather Feather plot
3-D vector data fill Draw filled 2-D polygons
surf2patch Convert surface data to patch fplot Plot a function
data inpolygon True for points inside a
subvolume Extract subset of volume data polygonal region
set pareto Pareto char
pcolor Pseudocolor (checkerboard) plot
Domain Generation
pie3 Three-dimensional pie plot
griddata Data gridding and surface
plotmatrix Scatter plot matrix
fitting
polyarea Area of polygon
meshgrid Generation of X and Y arrays for
3-D plots quiver Quiver (or velocity) plot
ribbon Ribbon plot
Specialized Plotting rose Plot rose or angle histogram
area Area plot scatter Scatter plot
box Axis box for 2-D and 3-D plots scatter3 Three-dimensional scatter plot
comet Comet plot stairs Stairstep graph
compass Compass plot stem Plot discrete sequence data
convhull Convex hull tsearch Search for enclosing Delaunay
delaunay Delaunay triangulation triangle
dsearch Search Delaunay triangulation voronoi Voronoi diagram
for nearest point
errorbar Plot graph with error bars View Control
ezcontour Easy to use contour plotter camdolly Move camera position and target
ezcontourf Easy to use filled contour plotter camlookat View specific objects
ezmesh Easy to use 3-D mesh plotter camorbit Orbit about camera target
ezmeshc Easy to use combination mesh/ campan Rotate camera target about
contour plotter camera position
ezplot Easy to use function plotter campos Set or get camera position
ezplot3 Easy to use 3-D parametric camproj Set or get projection type
curve plotter camroll Rotate camera about viewing
ezpolar Easy to use polar coordinate axis
plotter camtarget Set or get camera target
ezsurf Easy to use 3-D colored surface camup Set or get camera up-vector
plotter camva Set or get camera view angle

18
Plotting and Data Visualization

View Control (Continued) Color Operations (Continued)


camzoom Zoom camera in or out surfnorm Three-dimensional surface
daspect Set or get data aspect ratio normals
pbaspect Set or get plot box aspect ratio whitebg Change axes background color
for plots
view Three-dimensional graph
viewpoint specification.
Colormaps
viewmtx Generate view transformation
matrices autumn Shades of red and yellow color
map
xlim Set or get the current x-axis
limits bone Gray-scale with a tinge of blue
color map
ylim Set or get the current y-axis
limits contrast Gray color map to enhance
image contrast
zlim Set or get the current z-axis
limits cool Shades of cyan and magenta
color map
Lighting copper Linear copper-tone color map
camlight Create or position a light flag Alternating red, white, blue, and
black color map
lightangle Spherical position of a light
gray Linear gray-scale color map
lighting Lighting mode
hot Black-red-yellow-white color
material Material reflectance mode
map
hsv Hue-saturation-value (HSV)
Color Operations color map
brighten Brighten or darken color map jet Variant of HSV
caxis Pseudocolor axis scaling lines Line color colormap
colorbar Display color bar (color scale) prism Colormap of prism colors
colordef Set up color defaults spring Shades of magenta and yellow
colormap Set the color look-up table color map
graymon Graphics figure defaults set for summer Shades of green and yellow
grayscale monitor colormap
hsv2rgb Hue-saturation-value to winter Shades of blue and green color
red-green-blue conversion map
rgb2hsv RGB to HSV conversion
rgbplot Plot color map Printing
shading Color shading mode orient Hardcopy paper orientation
spinmap Spin the colormap print Print graph or save graph to file
printopt Configure local printer defaults
saveas Save figure to graphic file

19
MATLAB Quick Reference

Handle Graphics, Figure Windows (Continued)


Handle Graphics, General newplot Graphics M-file preamble for
copyobj Make a copy of a graphics object NextPlot property
and its children refresh Refresh figure
findobj Find objects with specified saveas Save figure or model to desired
property values output format
gcbo Return object whose callback is
currently executing Handle Graphics, Axes
gco Return handle of current object axis Plot axis scaling and appearance
get Get object properties cla Clear axes
ishandle True for graphics objects gca Get current axes handle
rotate Rotate objects about specified
origin and direction
Object Manipulation
set Set object properties reset Reset axis or figure
rotate3d Interactively rotate the view of a
Handle Graphics, Object Creation 3-D plot
axes Create axes object selectmoveresize Interactively select, move, or
figure Create figure (graph) windows resize objects
image Create image (2-D matrix)
light Create light object (illuminates Interactive User Input
Patch and Surface) ginput Graphical input from a mouse or
line Create line object (3-D polylines) cursor
patch Create patch object (polygons) zoom Zoom in and out on a 2-D plot
rectangle Create rectangle object (2-D
rectangle) Region of Interest
surface Create surface (quadrilaterals) dragrect Drag XOR rectangles with
text Create text object (character mouse
strings) drawnow Complete any pending drawing
uicontextmenu Create context menu (pop-up rbbox Rubberband box
associated with object)
Graphical User Interface Creation
Handle Graphics, Figure Windows
The graphical user interface functions let you build
capture Screen capture of the current
figure your own interfaces for your applications.
clc Clear figure window
Dialog Boxes
clf Clear figure
dialog Create a dialog box
close Close specified window
errordlg Create error dialog box
gcf Get current figure handle

20
Graphical User Interface Creation

Dialog Boxes (Continued) Other Functions (Continued)


helpdlg Display help dialog box uiwait Used with uiresume, controls
inputdlg Create input dialog box program execution
listdlg Create list selection dialog box waitbar Display wait bar
msgbox Create message dialog box waitforbuttonpress Wait for key/buttonpress over
figure
pagedlg Display page layout dialog box
printdlg Display print dialog box
questdlg Create question dialog box
uigetfile Display dialog box to retrieve
name of file for reading
uiputfile Display dialog box to retrieve
name of file for writing
uisetcolor Interactively set a ColorSpec
using a dialog box
uisetfont Interactively set a font using a
dialog box
warndlg Create warning dialog box

User Interface Objects


menu Generate a menu of choices for
user input
uicontextmenu Create context menu
uicontrol Create user interface control
uimenu Create user interface menu

Other Functions
dragrect Drag rectangles with mouse
gcbo Return handle of object whose
callback is executing
rbbox Create rubberband box for area
selection
selectmoveresize Select, move, resize, or copy axes
and uicontrol graphics objects
textwrap Return wrapped string matrix
for given uicontrol
uiresume Used with uiwait, controls
program execution

21
MATLAB Quick Reference

22

You might also like