5_MATLAB_Function_vol_1_(A

5_MATLAB_Function_vol_1_(A
MATLAB
®
The Language of Technical Computing
Computation
Visualization
Programming
MATLAB Function Reference
Volume 1: A - E
Version 6
How to Contact The MathWorks:
www.mathworks.com
comp.soft-sys.matlab
Web
Newsgroup
[email protected]
Technical support
Product enhancement suggestions
Bug reports
Documentation error reports
Order status, license renewals, passcodes
Sales, pricing, and general information
508-647-7000
Phone
508-647-7001
Fax
The MathWorks, Inc.
3 Apple Hill Drive
Natick, MA 01760-2098
Mail
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
For contact information about worldwide offices, see the MathWorks Web site.
MATLAB Function Reference Volume 1: A - E
 COPYRIGHT 1984 - 2002 by The MathWorks, Inc.
The software described in this document is furnished under a license agreement. The software may be used
or copied only under the terms of the license agreement. No part of this manual may be photocopied or reproduced in any form without prior written consent from The MathWorks, Inc.
FEDERAL ACQUISITION: This provision applies to all acquisitions of the Program and Documentation by
or for the federal government of the United States. By accepting delivery of the Program, the government
hereby agrees that this software qualifies as "commercial" computer software within the meaning of FAR
Part 12.212, DFARS Part 227.7202-1, DFARS Part 227.7202-3, DFARS Part 252.227-7013, and DFARS Part
252.227-7014. The terms and conditions of The MathWorks, Inc. Software License Agreement shall pertain
to the government’s use and disclosure of the Program and Documentation, and shall supersede any
conflicting contractual terms or conditions. If this license fails to meet the government’s minimum needs or
is inconsistent in any respect with federal procurement law, the government agrees to return the Program
and Documentation, unused, to MathWorks.
MATLAB, Simulink, Stateflow, Handle Graphics, and Real-Time Workshop are registered trademarks, and
TargetBox is a trademark of The MathWorks, Inc.
Other product or brand names are trademarks or registered trademarks of their respective holders.
Printing History: December 1996
June 1997
October 1997
January 1999
June 1999
June 2001
July 2002
First printing
Online only
Online only
Online only
Second printing
Online only
Online only
For MATLAB 5
Revised for 5.1
Revised for 5.2
Revised for Release 11
For Release 11
Revised for 6.1
Revised for 6.5 (Release 13)
Contents
Functions – By Category
1
Development Environment . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Starting and Quitting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Command Window . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Getting Help . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Workspace, File, and Search Path . . . . . . . . . . . . . . . . . . . . . . .
Programming Tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
System . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Performance Improvement Tools and Techniques . . . . . . . . . .
1-2
1-2
1-2
1-3
1-3
1-4
1-5
1-5
Mathematics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-6
Arrays and Matrices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-7
Linear Algebra . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-9
Elementary Math . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-11
Data Analysis and Fourier Transforms . . . . . . . . . . . . . . . . . . 1-13
Polynomials . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-14
Interpolation and Computational Geometry . . . . . . . . . . . . . . 1-15
Coordinate System Conversion . . . . . . . . . . . . . . . . . . . . . . . . . 1-16
Nonlinear Numerical Methods . . . . . . . . . . . . . . . . . . . . . . . . . 1-16
Specialized Math . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-18
Sparse Matrices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-18
Math Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-20
Programming and Data Types . . . . . . . . . . . . . . . . . . . . . . . .
Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Operators and Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Programming in MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1-21
1-21
1-25
1-27
1-29
File I/O . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Filename Construction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Opening, Loading, Saving Files . . . . . . . . . . . . . . . . . . . . . . . .
Low-Level File I/O . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Text Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
XML Documents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1-34
1-34
1-34
1-35
1-35
1-35
i
Spreadsheets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Scientific Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Audio and Audio/Video . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Images . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1-35
1-36
1-36
1-37
Graphics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Basic Plots and Graphs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Annotating Plots . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Specialized Plotting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Bit-Mapped Images . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Printing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Handle Graphics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1-38
1-38
1-38
1-39
1-41
1-41
1-42
3-D Visualization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Surface and Mesh Plots . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
View Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Lighting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Transparency . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Volume Visualization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1-44
1-44
1-45
1-46
1-47
1-47
Creating Graphical User Interfaces . . . . . . . . . . . . . . . . . . . .
Predefined Dialog Boxes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Deploying User Interfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Developing User Interfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . .
User Interface Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Finding Objects from Callbacks . . . . . . . . . . . . . . . . . . . . . . . .
GUI Utility Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Controlling Program Execution . . . . . . . . . . . . . . . . . . . . . . . . .
1-48
1-48
1-49
1-49
1-49
1-49
1-49
1-50
Functions – Alphabetical List
2
Index
ii
Contents
1
Functions – By Category
The MATLAB Function Reference contains descriptions of all MATLAB commands and functions.
Select a category from the following table to see a list of related functions.
Development Environment
Startup, Command Window, help, editing and debugging, other
general functions
Mathematics
Arrays and matrices, linear algebra, data analysis, other areas of
mathematics
Programming and Data
Types
Function/expression evaluation, program control, function handles,
object oriented programming, error handling, operators, data types,
dates and times, timers
File I/O
General and low-level file I/O, plus specific file formats, like audio,
spreadsheet, HDF, images
Graphics
Line plots, annotating graphs, specialized plots, images, printing,
Handle Graphics
3-D Visualization
Surface and mesh plots, view control, lighting and transparency,
volume visualization.
Creating Graphical User
Interface
GUIDE, programming graphical user interfaces.
External Interfaces
Java, COM, Serial Port functions.
See Simulink, Stateflow, Real-Time Workshop, and the individual toolboxes for lists of their functions
1
Functions – By Category
Development Environment
General functions for working in MATLAB, including functions for startup,
Command Window, help, and editing and debugging.
“Starting and Quitting”
Startup and shutdown options
“Command Window”
Controlling Command Window
“Getting Help”
Finding information
“Workspace, File, and
Search Path”
File, search path, variable management
“Programming Tools”
Editing and debugging, source control, Notebook
“System”
Identifying current computer, license, product
version, and more
“Performance
Improvement Tools and
Techniques”
Improving and assessing performance, e.g.,
profiling and memory use
Starting and Quitting
exit
finish
matlab
matlabrc
quit
startup
Terminate MATLAB (same as quit)
MATLAB termination M-file
Start MATLAB (UNIX systems only)
MATLAB startup M-file for single user systems or
administrators
Terminate MATLAB
MATLAB startup M-file for user-defined options
Command Window
clc
diary
dos
format
home
more
notebook
system
unix
1-2
Clear Command Window
Save session to file
Execute DOS command and return result
Control display format for output
Move cursor to upper left corner of Command Window
Control paged output for Command Window
Open M-book in Microsoft Word (Windows only)
Execute operating system command and return result
Execute UNIX command and return result
Development Environment
Getting Help
doc
demo
docopt
help
helpbrowser
helpwin
info
lookfor
support
web
whatsnew
Display online documentation in MATLAB Help browser
Access product demos via Help browser
Location of help file directory for UNIX platforms
Display help for MATLAB functions in Command Window
Display Help browser for access to extensive online help
Display M-file help, with access to M-file help for all functions
Display information about The MathWorks or products
Search for specified keyword in all help entries
Open MathWorks Technical Support Web page
Point Help browser or Web browser to file or Web site
Display information about MATLAB and toolbox releases
Workspace, File, and Search Path
• “Workspace”
• “File”
• “Search Path”
Workspace
assignin
clear
evalin
exist
openvar
pack
which
who, whos
workspace
Assign value to workspace variable
Remove items from workspace, freeing up system memory
Execute string containing MATLAB expression in a workspace
Check if variable or file exists
Open workspace variable in Array Editor for graphical editing
Consolidate workspace memory
Locate functions and files
List variables in the workspace
Display Workspace browser, a tool for managing the workspace
File
cd
copyfile
delete
dir
exist
fileattrib
filebrowser
lookfor
ls
Change working directory
Copy file or directory
Delete files or graphics objects
Display directory listing
Check if a variable or file exists
Set or get attributes of file or directory
Display Current Directory browser, a tool for viewing files
Search for specified keyword in all help entries
List directory on UNIX
1-3
1
Functions – By Category
matlabroot
mkdir
movefile
pwd
rehash
rmdir
type
what
which
Return root directory of MATLAB installation
Make new directory
Move file or directory
Display current directory
Refresh function and file system caches
Remove directory
List file
List MATLAB specific files in current directory
Locate functions and files
See also “File I/O” functions.
Search Path
addpath
genpath
partialpath
path
path2rc
pathtool
rmpath
Add directories to MATLAB search path
Generate path string
Partial pathname
View or change the MATLAB directory search path
Save current MATLAB search path to pathdef.m file
Open Set Path dialog box to view and change MATLAB path
Remove directories from MATLAB search path
Programming Tools
• “Editing and Debugging”
• “Source Control”
• “Notebook”
Editing and Debugging
dbclear
dbcont
dbdown
dbquit
dbstack
dbstatus
dbstep
dbstop
dbtype
dbup
edit
keyboard
1-4
Clear breakpoints
Resume execution
Change local workspace context
Quit debug mode
Display function call stack
List all breakpoints
Execute one or more lines from current breakpoint
Set breakpoints in M-file function
List M-file with line numbers
Change local workspace context
Edit or create M-file
Invoke the keyboard in an M-file
Development Environment
Source Control
checkin
Check file into source control system
checkout
Check file out of source control system
cmopts
Get name of source control system
customverctrl Allow custom source control system
undocheckout Undo previous checkout from source control system
verctrl
Version control operations on PC platforms
Notebook
notebook
Open M-book in Microsoft Word (Windows only)
System
computer
javachk
license
prefdir
usejava
ver
version
Identify information about computer on which MATLAB is
running
Generate error message based on Java feature support
Show license number for MATLAB
Return directory containing preferences, history, and .ini files
Determine if a Java feature is supported in MATLAB
Display version information for MathWorks products
Get MATLAB version number
Performance Improvement Tools and Techniques
memory
pack
profile
profreport
rehash
sparse
zeros
Help for memory limitations
Consolidate workspace memory
Optimize performance of M-file code
Generate profile report
Refresh function and file system caches
Create sparse matrix
Create array of all zeros
1-5
1
Functions – By Category
Mathematics
Functions for working with arrays and matrices, linear algebra, data analysis,
and other areas of mathematics.
1-6
“Arrays and Matrices”
Basic array operators and operations, creation of
elementary and specialized arrays and matrices
“Linear Algebra”
Matrix analysis, linear equations, eigenvalues,
singular values, logarithms, exponentials,
factorization
“Elementary Math”
Trigonometry, exponentials and logarithms,
complex values, rounding, remainders, discrete
math
“Data Analysis and
Fourier Transforms”
Descriptive statistics, finite differences, correlation,
filtering and convolution, fourier transforms
“Polynomials”
Multiplication, division, evaluation, roots,
derivatives, integration, eigenvalue problem, curve
fitting, partial fraction expansion
“Interpolation and
Computational
Geometry”
Interpolation, Delaunay triangulation and
tessellation, convex hulls, Voronoi diagrams,
domain generation
“Coordinate System
Conversion”
Conversions between Cartesian and polar or
spherical coordinates
“Nonlinear Numerical
Methods”
Differential equations, optimization, integration
“Specialized Math”
Airy, Bessel, Jacobi, Legendre, beta, elliptic, error,
exponential integral, gamma functions
“Sparse Matrices”
Elementary sparse matrices, operations, reordering
algorithms, linear algebra, iterative methods, tree
operations
“Math Constants”
Pi, imaginary unit, infinity, Not-a-Number, largest
and smallest positive floating point numbers,
floating point relative accuracy
Mathematics
Arrays and Matrices
• “Basic Information”
• “Operators”
• “Operations and Manipulation”
• “Elementary Matrices and Arrays”
• “Specialized Matrices”
Basic Information
disp
display
isempty
isequal
islogical
isnumeric
issparse
length
ndims
numel
size
Display array
Display array
True for empty matrix
True if arrays are identical
True for logical array
True for numeric arrays
True for sparse matrix
Length of vector
Number of dimensions
Number of elements
Size of matrix
Operators
+
+
*
^
\
/
'
.'
.*
.^
.\
./
Addition
Unary plus
Subtraction
Unary minus
Matrix multiplication
Matrix power
Backslash or left matrix divide
Slash or right matrix divide
Transpose
Nonconjugated transpose
Array multiplication (element-wise)
Array power (element-wise)
Left array divide (element-wise)
Right array divide (element-wise)
Operations and Manipulation
: (colon)
blkdiag
Index into array, rearrange array
Block diagonal concatenation
1-7
1
Functions – By Category
cat
cross
cumprod
cumsum
diag
dot
end
find
fliplr
flipud
flipdim
horzcat
ind2sub
ipermute
kron
max
min
permute
prod
repmat
reshape
rot90
sort
sortrows
sum
sqrtm
sub2ind
tril
triu
vertcat
Concatenate arrays
Vector cross product
Cumulative product
Cumulative sum
Diagonal matrices and diagonals of matrix
Vector dot product
Last index
Find indices of nonzero elements
Flip matrices left-right
Flip matrices up-down
Flip matrix along specified dimension
Horizontal concatenation
Multiple subscripts from linear index
Inverse permute dimensions of multidimensional array
Kronecker tensor product
Maximum elements of array
Minimum elements of array
Rearrange dimensions of multidimensional array
Product of array elements
Replicate and tile array
Reshape array
Rotate matrix 90 degrees
Sort elements in ascending order
Sort rows in ascending order
Sum of array elements
Matrix square root
Linear index from multiple subscripts
Lower triangular part of matrix
Upper triangular part of matrix
Vertical concatenation
See also “Linear Algebra” for other matrix operations.
See also “Elementary Math” for other array operations.
Elementary Matrices and Arrays
: (colon)
blkdiag
diag
eye
freqspace
linspace
logspace
1-8
Regularly spaced vector
Construct block diagonal matrix from input arguments
Diagonal matrices and diagonals of matrix
Identity matrix
Frequency spacing for frequency response
Generate linearly spaced vectors
Generate logarithmically spaced vectors
Mathematics
meshgrid
ndgrid
ones
rand
randn
repmat
zeros
Generate X and Y matrices for three-dimensional plots
Arrays for multidimensional functions and interpolation
Create array of all ones
Uniformly distributed random numbers and arrays
Normally distributed random numbers and arrays
Replicate and tile array
Create array of all zeros
Specialized Matrices
compan
gallery
hadamard
hankel
hilb
invhilb
magic
pascal
rosser
toeplitz
vander
wilkinson
Companion matrix
Test matrices
Hadamard matrix
Hankel matrix
Hilbert matrix
Inverse of Hilbert matrix
Magic square
Pascal matrix
Classic symmetric eigenvalue test problem
Toeplitz matrix
Vandermonde matrix
Wilkinson’s eigenvalue test matrix
Linear Algebra
• “Matrix Analysis”
• “Linear Equations”
• “Eigenvalues and Singular Values”
• “Matrix Logarithms and Exponentials”
• “Factorization”
Matrix Analysis
cond
condeig
det
norm
normest
null
orth
rank
rcond
Condition number with respect to inversion
Condition number with respect to eigenvalues
Determinant
Matrix or vector norm
Estimate matrix 2-norm
Null space
Orthogonalization
Matrix rank
Matrix reciprocal condition number estimate
1-9
1
Functions – By Category
rref
subspace
trace
Reduced row echelon form
Angle between two subspaces
Sum of diagonal elements
Linear Equations
\ and /
chol
cholinc
cond
condest
funm
inv
lscov
lsqnonneg
lu
luinc
pinv
qr
rcond
Linear equation solution
Cholesky factorization
Incomplete Cholesky factorization
Condition number with respect to inversion
1-norm condition number estimate
Evaluate general matrix function
Matrix inverse
Least squares solution in presence of known covariance
Nonnegative least squares
LU matrix factorization
Incomplete LU factorization
Moore-Penrose pseudoinverse of matrix
Orthogonal-triangular decomposition
Matrix reciprocal condition number estimate
Eigenvalues and Singular Values
balance
cdf2rdf
condeig
eig
eigs
gsvd
hess
poly
polyeig
qz
rsf2csf
schur
svd
svds
Improve accuracy of computed eigenvalues
Convert complex diagonal form to real block diagonal form
Condition number with respect to eigenvalues
Eigenvalues and eigenvectors
Eigenvalues and eigenvectors of sparse matrix
Generalized singular value decomposition
Hessenberg form of matrix
Polynomial with specified roots
Polynomial eigenvalue problem
QZ factorization for generalized eigenvalues
Convert real Schur form to complex Schur form
Schur decomposition
Singular value decomposition
Singular values and vectors of sparse matrix
Matrix Logarithms and Exponentials
expm
logm
sqrtm
1-10
Matrix exponential
Matrix logarithm
Matrix square root
Mathematics
Factorization
balance
cdf2rdf
chol
cholinc
cholupdate
lu
luinc
planerot
qr
qrdelete
qrinsert
qrupdate
qz
rsf2csf
Diagonal scaling to improve eigenvalue accuracy
Complex diagonal form to real block diagonal form
Cholesky factorization
Incomplete Cholesky factorization
Rank 1 update to Cholesky factorization
LU matrix factorization
Incomplete LU factorization
Givens plane rotation
Orthogonal-triangular decomposition
Delete column or row from QR factorization
Insert column or row into QR factorization
Rank 1 update to QR factorization
QZ factorization for generalized eigenvalues
Real block diagonal form to complex diagonal form
Elementary Math
• “Trigonometric”
• “Exponential”
• “Complex”
• “Rounding and Remainder”
• “Discrete Math (e.g., Prime Factors)”
Trigonometric
acos
acosh
acot
acoth
acsc
acsch
asec
asech
asin
asinh
atan
atanh
atan2
cos
cosh
cot
coth
Inverse cosine
Inverse hyperbolic cosine
Inverse cotangent
Inverse hyperbolic cotangent
Inverse cosecant
Inverse hyperbolic cosecant
Inverse secant
Inverse hyperbolic secant
Inverse sine
Inverse hyperbolic sine
Inverse tangent
Inverse hyperbolic tangent
Four-quadrant inverse tangent
Cosine
Hyperbolic cosine
Cotangent
Hyperbolic cotangent
1-11
1
Functions – By Category
csc
csch
sec
sech
sin
sinh
tan
tanh
Cosecant
Hyperbolic cosecant
Secant
Hyperbolic secant
Sine
Hyperbolic sine
Tangent
Hyperbolic tangent
Exponential
exp
log
log2
log10
nextpow2
pow2
reallog
realpow
realsqrt
sqrt
Exponential
Natural logarithm
Base 2 logarithm and dissect floating-point numbers into
exponent and mantissa
Common (base 10) logarithm
Next higher power of 2
Base 2 power and scale floating-point number
Natural logarithm for nonnegative real arrays
Array power for real-only output
Square root for nonnegative real arrays
Square root
Complex
abs
angle
complex
conj
cplxpair
i
imag
isreal
j
real
unwrap
Absolute value
Phase angle
Construct complex data from real and imaginary parts
Complex conjugate
Sort numbers into complex conjugate pairs
Imaginary unit
Complex imaginary part
True for real array
Imaginary unit
Complex real part
Unwrap phase angle
Rounding and Remainder
fix
floor
ceil
round
mod
rem
sign
1-12
Round towards zero
Round towards minus infinity
Round towards plus infinity
Round towards nearest integer
Modulus after division
Remainder after division
Signum
Mathematics
Discrete Math (e.g., Prime Factors)
factor
factorial
gcd
isprime
lcm
nchoosek
perms
primes
rat, rats
Prime factors
Factorial function
Greatest common divisor
True for prime numbers
Least common multiple
All combinations of N elements taken K at a time
All possible permutations
Generate list of prime numbers
Rational fraction approximation
Data Analysis and Fourier Transforms
• “Basic Operations”
• “Finite Differences”
• “Correlation”
• “Filtering and Convolution”
• “Fourier Transforms”
Basic Operations
cumprod
cumsum
cumtrapz
max
mean
median
min
prod
sort
sortrows
std
sum
trapz
var
Cumulative product
Cumulative sum
Cumulative trapezoidal numerical integration
Maximum elements of array
Average or mean value of arrays
Median value of arrays
Minimum elements of array
Product of array elements
Sort elements in ascending order
Sort rows in ascending order
Standard deviation
Sum of array elements
Trapezoidal numerical integration
Variance
Finite Differences
del2
diff
gradient
Discrete Laplacian
Differences and approximate derivatives
Numerical gradient
1-13
1
Functions – By Category
Correlation
corrcoef
cov
subspace
Correlation coefficients
Covariance matrix
Angle between two subspaces
Filtering and Convolution
conv
conv2
convn
deconv
detrend
filter
filter2
Convolution and polynomial multiplication
Two-dimensional convolution
N-dimensional convolution
Deconvolution and polynomial division
Linear trend removal
Filter data with infinite impulse response (IIR) or finite
impulse response (FIR) filter
Two-dimensional digital filtering
Fourier Transforms
abs
angle
fft
fft2
fftn
fftshift
ifft
ifft2
ifftn
ifftshift
nextpow2
unwrap
Absolute value and complex magnitude
Phase angle
One-dimensional discrete Fourier transform
Two-dimensional discrete Fourier transform
N-dimensional discrete Fourier Transform
Shift DC component of discrete Fourier transform to center of
spectrum
Inverse one-dimensional discrete Fourier transform
Inverse two-dimensional discrete Fourier transform
Inverse multidimensional discrete Fourier transform
Inverse fast Fourier transform shift
Next power of two
Correct phase angles
Polynomials
conv
deconv
poly
polyder
polyeig
polyfit
polyint
polyval
polyvalm
residue
1-14
Convolution and polynomial multiplication
Deconvolution and polynomial division
Polynomial with specified roots
Polynomial derivative
Polynomial eigenvalue problem
Polynomial curve fitting
Analytic polynomial integration
Polynomial evaluation
Matrix polynomial evaluation
Convert between partial fraction expansion and polynomial
Mathematics
roots
coefficients
Polynomial roots
Interpolation and Computational Geometry
• “Interpolation”
• “Delaunay Triangulation and Tessellation”
• “Convex Hull”
• “Voronoi Diagrams”
• “Domain Generation”
Interpolation
dsearch
dsearchn
griddata
griddata3
griddatan
interp1
interp2
interp3
interpft
interpn
meshgrid
mkpp
ndgrid
pchip
ppval
spline
tsearchn
unmkpp
Search for nearest point
Multidimensional closest point search
Data gridding
Data gridding and hypersurface fitting for three-dimensional
data
Data gridding and hypersurface fitting (dimension >= 2)
One-dimensional data interpolation (table lookup)
Two-dimensional data interpolation (table lookup)
Three-dimensional data interpolation (table lookup)
One-dimensional interpolation using fast Fourier transform
method
Multidimensional data interpolation (table lookup)
Generate X and Y matrices for three-dimensional plots
Make piecewise polynomial
Generate arrays for multidimensional functions and
interpolation
Piecewise Cubic Hermite Interpolating Polynomial (PCHIP)
Piecewise polynomial evaluation
Cubic spline data interpolation
Multidimensional closest simplex search
Piecewise polynomial details
Delaunay Triangulation and Tessellation
delaunay
delaunay3
delaunayn
dsearch
dsearchn
Delaunay triangulation
Three-dimensional Delaunay tessellation
Multidimensional Delaunay tessellation
Search for nearest point
Multidimensional closest point search
1-15
1
Functions – By Category
tetramesh
trimesh
triplot
trisurf
tsearch
tsearchn
Tetrahedron mesh plot
Triangular mesh plot
Two-dimensional triangular plot
Triangular surface plot
Search for enclosing Delaunay triangle
Multidimensional closest simplex search
Convex Hull
convhull
convhulln
patch
plot
trisurf
Convex hull
Multidimensional convex hull
Create patch graphics object
Linear two-dimensional plot
Triangular surface plot
Voronoi Diagrams
dsearch
patch
plot
voronoi
voronoin
Search for nearest point
Create patch graphics object
Linear two-dimensional plot
Voronoi diagram
Multidimensional Voronoi diagrams
Domain Generation
meshgrid
ndgrid
Generate X and Y matrices for three-dimensional plots
Generate arrays for multidimensional functions and
interpolation
Coordinate System Conversion
Cartesian
cart2sph
cart2pol
pol2cart
sph2cart
Transform Cartesian to spherical coordinates
Transform Cartesian to polar coordinates
Transform polar to Cartesian coordinates
Transform spherical to Cartesian coordinates
Nonlinear Numerical Methods
• “Ordinary Differential Equations (IVP)”
• “Delay Differential Equations”
• “Boundary Value Problems”
1-16
Mathematics
• “Partial Differential Equations”
• “Optimization”
• “Numerical Integration (Quadrature)”
Ordinary Differential Equations (IVP)
deval
ode113
ode15s
ode23
ode23s
ode23t
ode23tb
ode45
odeget
odeset
Evaluate solution of differential equation problem
Solve non-stiff differential equations, variable order method
Solve stiff ODEs and DAEs Index 1, variable order method
Solve non-stiff differential equations, low order method
Solve stiff differential equations, low order method
Solve moderately stiff ODEs and DAEs Index 1, trapezoidal
rule
Solve stiff differential equations, low order method
Solve non-stiff differential equations, medium order method
Get ODE options parameters
Create/alter ODE options structure
Delay Differential Equations
dde23
ddeget
ddeset
Solve delay differential equations with constant delays
Get DDE options parameters
Create/alter DDE options structure
Boundary Value Problems
bvp4c
bvpget
bvpset
deval
Solve two-point boundary value problems for ODEs by
collocation
Get BVP options parameters
Create/alter BVP options structure
Evaluate solution of differential equation problem
Partial Differential Equations
pdepe
pdeval
Solve initial-boundary value problems for parabolic-elliptic
PDEs
Evaluates by interpolation solution computed by pdepe
Optimization
fminbnd
fminsearch
fzero
lsqnonneg
Scalar bounded nonlinear function minimization
Multidimensional unconstrained nonlinear minimization, by
Nelder-Mead direct search method
Scalar nonlinear zero finding
Linear least squares with nonnegativity constraints
1-17
1
Functions – By Category
optimset
optimget
Create or alter optimization options structure
Get optimization parameters from options structure
Numerical Integration (Quadrature)
quad
quadl
dblquad
triplequad
Numerically evaluate integral, adaptive Simpson quadrature
(low order)
Numerically evaluate integral, adaptive Lobatto quadrature
(high order)
Numerically evaluate double integral
Numerically evaluate triple integral
Specialized Math
airy
besselh
besseli
besselj
besselk
bessely
beta
betainc
betaln
ellipj
ellipke
erf
erfc
erfcinv
erfcx
erfinv
expint
gamma
gammainc
gammaln
legendre
psi
Airy functions
Bessel functions of third kind (Hankel functions)
Modified Bessel function of first kind
Bessel function of first kind
Modified Bessel function of second kind
Bessel function of second kind
Beta function
Incomplete beta function
Logarithm of beta function
Jacobi elliptic functions
Complete elliptic integrals of first and second kind
Error function
Complementary error function
Inverse complementary error function
Scaled complementary error function
Inverse error function
Exponential integral
Gamma function
Incomplete gamma function
Logarithm of gamma function
Associated Legendre functions
Psi (polygamma) function
Sparse Matrices
• “Elementary Sparse Matrices”
• “Full to Sparse Conversion”
• “Working with Sparse Matrices”
1-18
Mathematics
• “Reordering Algorithms”
• “Linear Algebra”
• “Linear Equations (Iterative Methods)”
• “Tree Operations”
Elementary Sparse Matrices
spdiags
speye
sprand
sprandn
sprandsym
Sparse matrix formed from diagonals
Sparse identity matrix
Sparse uniformly distributed random matrix
Sparse normally distributed random matrix
Sparse random symmetric matrix
Full to Sparse Conversion
find
full
sparse
spconvert
Find indices of nonzero elements
Convert sparse matrix to full matrix
Create sparse matrix
Import from sparse matrix external format
Working with Sparse Matrices
issparse
nnz
nonzeros
nzmax
spalloc
spfun
spones
spparms
spy
True for sparse matrix
Number of nonzero matrix elements
Nonzero matrix elements
Amount of storage allocated for nonzero matrix elements
Allocate space for sparse matrix
Apply function to nonzero matrix elements
Replace nonzero sparse matrix elements with ones
Set parameters for sparse matrix routines
Visualize sparsity pattern
Reordering Algorithms
colamd
colmmd
colperm
dmperm
randperm
symamd
symmmd
symrcm
Column approximate minimum degree permutation
Column minimum degree permutation
Column permutation
Dulmage-Mendelsohn permutation
Random permutation
Symmetric approximate minimum degree permutation
Symmetric minimum degree permutation
Symmetric reverse Cuthill-McKee permutation
1-19
1
Functions – By Category
Linear Algebra
cholinc
condest
eigs
luinc
normest
sprank
svds
Incomplete Cholesky factorization
1-norm condition number estimate
Eigenvalues and eigenvectors of sparse matrix
Incomplete LU factorization
Estimate matrix 2-norm
Structural rank
Singular values and vectors of sparse matrix
Linear Equations (Iterative Methods)
bicg
bicgstab
cgs
gmres
lsqr
minres
pcg
qmr
spaugment
symmlq
BiConjugate Gradients method
BiConjugate Gradients Stabilized method
Conjugate Gradients Squared method
Generalized Minimum Residual method
LSQR implementation of Conjugate Gradients on Normal
Equations
Minimum Residual method
Preconditioned Conjugate Gradients method
Quasi-Minimal Residual method
Form least squares augmented system
Symmetric LQ method
Tree Operations
etree
etreeplot
gplot
symbfact
treelayout
treeplot
Elimination tree
Plot elimination tree
Plot graph, as in “graph theory”
Symbolic factorization analysis
Lay out tree or forest
Plot picture of tree
Math Constants
eps
i
Inf
j
NaN
pi
realmax
realmin
1-20
Floating-point relative accuracy
Imaginary unit
Infinity, ∞
Imaginary unit
Not-a-Number
Ratio of a circle’s circumference to its diameter, π
Largest positive floating-point number
Smallest positive floating-point number
Programming and Data Types
Programming and Data Types
Functions to store and operate on data at either the MATLAB command line or
in programs and scripts. Functions to write, manage, and execute MATLAB
programs.
“Data Types”
Numeric, character, structures, cell arrays,
and data type conversion
“Arrays”
Basic array operations and manipulation
“Operators and Operations”
Special characters and arithmetic, bit-wise,
relational, logical, set, date and time
operations
“Programming in MATLAB”
M-files, function/expression evaluation,
program control, function handles, object
oriented programming, error handling
Data Types
• “Numeric”
• “Characters and Strings”
• “Structures”
• “Cell Arrays”
• “Data Type Conversion”
• “Determine Data Type”
Numeric
[ ]
Array constructor
cat
Concatenate arrays
class
Return object’s class name (e.g., numeric)
find
Find indices and values of nonzero array elements
ipermute
Inverse permute dimensions of multidimensional array
isa
Detect object of given class (e.g., numeric)
isequal
Determine if arrays are numerically equal
isequalwithequalnansTest for equality, treating NaNs as equal
isnumeric
Determine if item is numeric array
isreal
Determine if all array elements are real numbers
permute
Rearrange dimensions of multidimensional array
1-21
1
Functions – By Category
reshape
squeeze
zeros
Reshape array
Remove singleton dimensions from array
Create array of all zeros
Characters and Strings
Description of Strings in MATLAB
strings
Describes MATLAB string handling
Creating and Manipulating Strings
blanks
char
cellstr
datestr
deblank
lower
sprintf
sscanf
strcat
strjust
strread
strrep
strvcat
upper
Create string of blanks
Create character array (string)
Create cell array of strings from character array
Convert to date string format
Strip trailing blanks from the end of string
Convert string to lower case
Write formatted data to string
Read string under format control
String concatenation
Justify character array
Read formatted data from string
String search and replace
Vertical concatenation of strings
Convert string to upper case
Comparing and Searching Strings
class
findstr
isa
iscellstr
ischar
isletter
isspace
regexp
regexpi
regexprep
strcmp
strcmpi
strfind
strmatch
strncmp
1-22
Return object’s class name (e.g., char)
Find string within another, longer string
Detect object of given class (e.g., char)
Determine if item is cell array of strings
Determine if item is character array
Detect array elements that are letters of the alphabet
Detect elements that are ASCII white spaces
Match regular expression
Match regular expression, ignoring case
Replace string using regular expression
Compare strings
Compare strings, ignoring case
Find one string within another
Find possible matches for string
Compare first n characters of strings
Programming and Data Types
strncmpi
strtok
Compare first n characters of strings, ignoring case
First token in string
Evaluating String Expressions
eval
evalc
evalin
Execute string containing MATLAB expression
Evaluate MATLAB expression with capture
Execute string containing MATLAB expression in workspace
Structures
cell2struct
class
deal
fieldnames
isa
isequal
isfield
isstruct
orderfields
rmfield
struct
struct2cell
Cell array to structure array conversion
Return object’s class name (e.g., struct)
Deal inputs to outputs
Field names of structure
Detect object of given class (e.g., struct)
Determine if arrays are numerically equal
Determine if item is structure array field
Determine if item is structure array
Order fields of a structure array
Remove structure fields
Create structure array
Structure to cell array conversion
Cell Arrays
{ }
cell
cellfun
cellstr
cell2mat
cell2struct
celldisp
cellplot
class
deal
isa
iscell
iscellstr
isequal
mat2cell
num2cell
struct2cell
Construct cell array
Construct cell array
Apply function to each element in cell array
Create cell array of strings from character array
Convert cell array of matrices into single matrix
Cell array to structure array conversion
Display cell array contents
Graphically display structure of cell arrays
Return object’s class name (e.g., cell)
Deal inputs to outputs
Detect object of given class (e.g., cell)
Determine if item is cell array
Determine if item is cell array of strings
Determine if arrays are numerically equal
Divide matrix up into cell array of matrices
Convert numeric array into cell array
Structure to cell array conversion
1-23
1
Functions – By Category
Data Type Conversion
Numeric
double
int8
int16
int32
int64
single
uint8
uint16
uint32
uint64
Convert to double-precision
Convert to signed 8-bit integer
Convert to signed 16-bit integer
Convert to signed 32-bit integer
Convert to signed 64-bit integer
Convert to single-precision
Convert to unsigned 8-bit integer
Convert to unsigned 16-bit integer
Convert to unsigned 32-bit integer
Convert to unsigned 64-bit integer
String to Numeric
base2dec
bin2dec
hex2dec
hex2num
str2double
str2num
Convert base N number string to decimal number
Convert binary number string to decimal number
Convert hexadecimal number string to decimal number
Convert hexadecimal number string to double number
Convert string to double-precision number
Convert string to number
Numeric to String
char
dec2base
dec2bin
dec2hex
int2str
mat2str
num2str
Convert to character array (string)
Convert decimal to base N number in string
Convert decimal to binary number in string
Convert decimal to hexadecimal number in string
Convert integer to string
Convert a matrix to string
Convert number to string
Other Conversions
cell2mat
cell2struct
datestr
func2str
logical
mat2cell
num2cell
str2func
struct2cell
1-24
Convert cell array of matrices into single matrix
Convert cell array to structure array
Convert serial date number to string
Convert function handle to function name string
Convert numeric to logical array
Divide matrix up into cell array of matrices
Convert a numeric array to cell array
Convert function name string to function handle
Convert structure to cell array
Programming and Data Types
Determine Data Type
is*
isa
iscell
iscellstr
ischar
isfield
isjava
islogical
isnumeric
isobject
isstruct
Detect state
Detect object of given MATLAB class or Java class
Determine if item is cell array
Determine if item is cell array of strings
Determine if item is character array
Determine if item is character array
Determine if item is Java object
Determine if item is logical array
Determine if item is numeric array
Determine if item is MATLAB OOPs object
Determine if item is MATLAB structure array
Arrays
• “Array Operations”
• “Basic Array Information”
• “Array Manipulation”
• “Elementary Arrays”
Array Operations
[ ]
,
;
:
end
+
.*
./
.\
.^
.'
Array constructor
Array row element separator
Array column element separator
Specify range of array elements
Indicate last index of array
Addition or unary plus
Subtraction or unary minus
Array multiplication
Array right division
Array left division
Array power
Array (nonconjugated) transpose
Basic Array Information
disp
Display text or array
display
Overloaded method to display text or array
isempty
Determine if array is empty
isequal
Determine if arrays are numerically equal
isequalwithequalnansTest for equality, treating NaNs as equal
1-25
1
Functions – By Category
isnumeric
islogical
length
ndims
numel
size
Determine if item is numeric array
Determine if item is logical array
Length of vector
Number of array dimensions
Number of elements in matrix or cell array
Array dimensions
Array Manipulation
:
blkdiag
cat
circshift
find
fliplr
flipud
flipdim
horzcat
ind2sub
ipermute
permute
repmat
reshape
rot90
shiftdim
sort
sortrows
squeeze
sub2ind
vertcat
Specify range of array elements
Construct block diagonal matrix from input arguments
Concatenate arrays
Shift array circularly
Find indices and values of nonzero elements
Flip matrices left-right
Flip matrices up-down
Flip array along specified dimension
Horizontal concatenation
Subscripts from linear index
Inverse permute dimensions of multidimensional array
Rearrange dimensions of multidimensional array
Replicate and tile array
Reshape array
Rotate matrix 90 degrees
Shift dimensions
Sort elements in ascending order
Sort rows in ascending order
Remove singleton dimensions
Single index from subscripts
Horizontal concatenation
Elementary Arrays
:
blkdiag
eye
linspace
logspace
meshgrid
ndgrid
ones
rand
randn
zeros
1-26
Regularly spaced vector
Construct block diagonal matrix from input arguments
Identity matrix
Generate linearly spaced vectors
Generate logarithmically spaced vectors
Generate X and Y matrices for three-dimensional plots
Generate arrays for multidimensional functions and
interpolation
Create array of all ones
Uniformly distributed random numbers and arrays
Normally distributed random numbers and arrays
Create array of all zeros
Programming and Data Types
Operators and Operations
• “Special Characters”
• “Arithmetic Operations”
• “Bit-wise Operations”
• “Relational Operations”
• “Logical Operations”
• “Set Operations”
• “Date and Time Operations”
Special Characters
:
( )
[ ]
{ }
.
...
,
;
%
!
=
Specify range of array elements
Pass function arguments, or prioritize operations
Construct array
Construct cell array
Decimal point, or structure field separator
Continue statement to next line
Array row element separator
Array column element separator
Insert comment line into code
Command to operating system
Assignment
Arithmetic Operations
+
.
=
*
/
\
^
'
.*
./
.\
.^
.'
Plus
Minus
Decimal point
Assignment
Matrix multiplication
Matrix right division
Matrix left division
Matrix power
Matrix transpose
Array multiplication (element-wise)
Array right division (element-wise)
Array left division (element-wise)
Array power (element-wise)
Array transpose
1-27
1
Functions – By Category
Bit-wise Operations
bitand
bitcmp
bitor
bitmax
bitset
bitshift
bitget
bitxor
Bit-wise AND
Bit-wise complement
Bit-wise OR
Maximum floating-point integer
Set bit at specified position
Bit-wise shift
Get bit at specified position
Bit-wise XOR
Relational Operations
<
<=
>
>=
==
~=
Less than
Less than or equal to
Greater than
Greater than or equal to
Equal to
Not equal to
Logical Operations
&&
||
&
|
~
all
any
false
find
is*
isa
iskeyword
isvarname
logical
true
xor
Logical AND
Logical OR
Logical AND for arrays
Logical OR for arrays
Logical NOT
Test to determine if all elements are nonzero
Test for any nonzero elements
False array
Find indices and values of nonzero elements
Detect state
Detect object of given class
Determine if string is MATLAB keyword
Determine if string is valid variable name
Convert numeric values to logical
True array
Logical EXCLUSIVE OR
Set Operations
intersect
ismember
setdiff
issorted
1-28
Set intersection of two vectors
Detect members of set
Return set difference of two vectors
Determine if set elements are in sorted order
Programming and Data Types
setxor
union
unique
Set exclusive or of two vectors
Set union of two vectors
Unique elements of vector
Date and Time Operations
calendar
clock
cputime
date
datenum
datestr
datevec
eomday
etime
now
tic, toc
weekday
Calendar for specified month
Current time as date vector
Elapsed CPU time
Current date string
Serial date number
Convert serial date number to string
Date components
End of month
Elapsed time
Current date and time
Stopwatch timer
Day of the week
Programming in MATLAB
• “M-File Functions and Scripts”
• “Evaluation of Expressions and Functions”
• “Timer Functions”
• “Variables and Functions in Memory”
• “Control Flow”
• “Function Handles”
• “Object-Oriented Programming”
• “Error Handling”
• “MEX Programming”
M-File Functions and Scripts
( )
%
...
depfun
depdir
function
input
Pass function arguments
Insert comment line into code
Continue statement to next line
List dependent functions of M-file or P-file
List dependent directories of M-file or P-file
Function M-files
Request user input
1-29
1
Functions – By Category
inputname
Input argument name
mfilename
Name of currently running M-file
namelengthmax Return maximum identifier length
nargin
Number of function input arguments
nargout
Number of function output arguments
nargchk
Check number of input arguments
nargoutchk
Validate number of output arguments
pcode
Create preparsed pseudocode file (P-file)
script
Describes script M-file
varargin
Accept variable number of arguments
varargout
Return variable number of arguments
Evaluation of Expressions and Functions
builtin
cellfun
eval
evalc
evalin
feval
iskeyword
isvarname
pause
run
script
symvar
tic, toc
Execute builtin function from overloaded method
Apply function to each element in cell array
Interpret strings containing MATLAB expressions
Evaluate MATLAB expression with capture
Evaluate expression in workspace
Evaluate function
Determine if item is MATLAB keyword
Determine if item is valid variable name
Halt execution temporarily
Run script that is not on current path
Describes script M-file
Determine symbolic variables in expression
Stopwatch timer
Timer Functions
delete
disp
get
isvalid
set
start
startat
stop
timer
timerfind
wait
Delete timer object from memory
Display information about timer object
Retrieve information about timer object properties
Determine if timer object is valid
Display or set timer object properties
Start a timer
Start a timer at a specific timer
Stop a timer
Create a timer object
Return an array of all timer object in memory
Block command line until timer completes
Variables and Functions in Memory
assignin
1-30
Assign value to workspace variable
Programming and Data Types
global
Define global variables
inmem
Return names of functions in memory
isglobal
Determine if item is global variable
mislocked
True if M-file cannot be cleared
mlock
Prevent clearing M-file from memory
munlock
Allow clearing M-file from memory
namelengthmax Return maximum identifier length
pack
Consolidate workspace memory
persistent
Define persistent variable
rehash
Refresh function and file system caches
Control Flow
break
case
catch
continue
else
elseif
end
error
for
if
otherwise
return
switch
try
while
Terminate execution of for loop or while loop
Case switch
Begin catch block
Pass control to next iteration of for or while loop
Conditionally execute statements
Conditionally execute statements
Terminate conditional statements, or indicate last index
Display error messages
Repeat statements specific number of times
Conditionally execute statements
Default part of switch statement
Return to invoking function
Switch among several cases based on expression
Begin try block
Repeat statements indefinite number of times
Function Handles
class
Return object’s class name (e.g. function_handle)
feval
Evaluate function
function_handle
functions
func2str
isa
isequal
str2func
Describes function handle data type
Return information about function handle
Constructs function name string from function handle
Detect object of given class (e.g. function_handle)
Determine if function handles are equal
Constructs function handle from function name string
1-31
1
Functions – By Category
Object-Oriented Programming
MATLAB Classes and Objects
class
fieldnames
inferiorto
isa
isobject
loadobj
methods
methodsview
saveobj
subsasgn
subsindex
subsref
substruct
superiorto
Create object or return class of object
List public fields belonging to object,
Establish inferior class relationship
Detect object of given class
Determine if item is MATLAB OOPs object
User-defined extension of load function for user objects
Display method names
Displays information on all methods implemented by class
User-defined extension of save function for user objects
Overloaded method for A(I)=B, A{I}=B, and A.field=B
Overloaded method for X(A)
Overloaded method for A(I), A{I} and A.field
Create structure argument for subsasgn or subsref
Establish superior class relationship
Java Classes and Objects
cell
class
clear
depfun
exist
fieldnames
im2java
import
inmem
isa
isjava
javaArray
javaMethod
javaObject
methods
methodsview
which
Convert Java array object to cell array
Return class name of Java object
Clear Java packages import list
List Java classes used by M-file
Detect if item is Java class
List public fields belonging to object
Convert image to instance of Java image object
Add package or class to current Java import list
List names of Java classes loaded into memory
Detect object of given class
Determine whether object is Java object
Constructs Java array
Invokes Java method
Constructs Java object
Display methods belonging to class
Display information on all methods implemented by class
Display package and class name for method
Error Handling
catch
error
ferror
1-32
Begin catch block of try/catch statement
Display error message
Query MATLAB about errors in file input or output
Programming and Data Types
lasterr
lasterror
lastwarn
rethrow
try
warning
Return last error message generated by MATLAB
Last error message and related information
Return last warning message issued by MATLAB
Reissue error
Begin try block of try/catch statement
Display warning message
MEX Programming
dbmex
inmem
mex
mexext
Enable MEX-file debugging
Return names of currently loaded MEX-files
Compile MEX-function from C or Fortran source code
Return MEX-filename extension
1-33
1
Functions – By Category
File I/O
Functions to read and write data to files of different format types.
“Filename Construction”
Get path, directory, filename
information; construct filenames
“Opening, Loading, Saving Files”
Open files; transfer data between files
and MATLAB workspace
“Low-Level File I/O”
Low-level operations that use a file
identifier (e.g., fopen, fseek, fread)
“Text Files”
Delimited or formatted I/O to text files
“XML Documents”
Documents written in Extensible
Markup Language
“Spreadsheets”
Excel and Lotus 123 files
“Scientific Data”
CDF, FITS, HDF formats
“Audio and Audio/Video”
General audio functions; SparcStation,
Wave, AVI files
“Images”
Graphics files
To see a listing of file formats that are readable from MATLAB, go to file
formats.
Filename Construction
fileparts
filesep
fullfile
tempdir
tempname
Return parts of filename
Return directory separator for this platform
Build full filename from parts
Return name of system's temporary directory
Return unique string for use as temporary filename
Opening, Loading, Saving Files
importdata
load
open
save
winopen
1-34
Load data from various types of files
Load all or specific data from MAT or ASCII file
Open files of various types using appropriate editor or program
Save all or specific data to MAT or ASCII file
Open file in appropriate application (Windows only)
File I/O
Low-Level File I/O
fclose
feof
ferror
fgetl
fgets
fopen
fprintf
fread
frewind
fscanf
fseek
ftell
fwrite
Close one or more open files
Test for end-of-file
Query MATLAB about errors in file input or output
Return next line of file as string without line terminator(s)
Return next line of file as string with line terminator(s)
Open file or obtain information about open files
Write formatted data to file
Read binary data from file
Rewind open file
Read formatted data from file
Set file position indicator
Get file position indicator
Write binary data to file
Text Files
csvread
csvwrite
dlmread
dlmwrite
textread
Read numeric data from text file, using comma delimiter
Write numeric data to text file, using comma delimiter
Read numeric data from text file, specifying your own delimiter
Write numeric data to text file, specifying your own delimiter
Read data from text file, specifying format for each value
XML Documents
xmlread
xmlwrite
xslt
Parse XML document
Serialize XML Document Object Model node
Transform XML document using XSLT engine
Spreadsheets
Microsoft Excel Functions
xlsfinfo
xlsread
Determine if file contains Microsoft Excel (.xls) spreadsheet
Read Microsoft Excel spreadsheet file (.xls)
Lotus123 Functions
wk1read
wk1write
Read Lotus123 WK1 spreadsheet file into matrix
Write matrix to Lotus123 WK1 spreadsheet file
1-35
1
Functions – By Category
Scientific Data
Common Data Format (CDF)
cdfinfo
cdfread
Return information about CDF file
Read CDF file
Flexible Image Transport System
fitsinfo
fitsread
Return information about FITS file
Read FITS file
Hierarchical Data Format (HDF)
hdf
hdfinfo
hdfread
Interface to HDF files
Return information about HDF or HDF-EOS file
Read HDF file
Audio and Audio/Video
General
audioplayer Create audio player object
audiorecorder Perform real-time audio capture
beep
Produce beep sound
lin2mu
Convert linear audio signal to mu-law
mu2lin
Convert mu-law audio signal to linear
sound
Convert vector into sound
soundsc
Scale data and play as sound
SPARCstation-Specific Sound Functions
auread
auwrite
Read NeXT/SUN (.au) sound file
Write NeXT/SUN (.au) sound file
Microsoft WAVE Sound Functions
wavplay
wavread
wavrecord
wavwrite
1-36
Play sound on PC-based audio output device
Read Microsoft WAVE (.wav) sound file
Record sound using PC-based audio input device
Write Microsoft WAVE (.wav) sound file
File I/O
Audio Video Interleaved (AVI) Functions
addframe
avifile
aviinfo
aviread
close
movie2avi
Add frame to AVI file
Create new AVI file
Return information about AVI file
Read AVI file
Close AVI file
Create AVI movie from MATLAB movie
Images
im2java
imfinfo
imread
imwrite
Convert image to instance of Java image object
Return information about graphics file
Read image from graphics file
Write image to graphics file
1-37
1
Functions – By Category
Graphics
2-D graphs, specialized plots (e.g., pie charts, histograms, and contour plots),
function plotters, and Handle Graphics functions.
Basic Plots and Graphs
Linear line plots, log and semilog plots
Annotating Plots
Titles, axes labels, legends, mathematical
symbols
Specialized Plotting
Bar graphs, histograms, pie charts, contour plots,
function plotters
Bit-Mapped Images
Display image object, read and write graphics file,
convert to movie frames
Printing
Printing and exporting figures to standard
formats
Handle Graphics
Creating graphics objects, setting properties,
finding handles
Basic Plots and Graphs
box
errorbar
hold
LineSpec
loglog
polar
plot
plot3
plotyy
semilogx
semilogy
subplot
Axis box for 2-D and 3-D plots
Plot graph with error bars
Hold current graph
Line specification syntax
Plot using log-log scales
Polar coordinate plot
Plot vectors or matrices.
Plot lines and points in 3-D space
Plot graphs with Y tick labels on the left and right
Semi-log scale plot
Semi-log scale plot
Create axes in tiled positions
Annotating Plots
clabel
datetick
gtext
legend
texlabel
1-38
Add contour labels to contour plot
Date formatted tick labels
Place text on 2-D graph using mouse
Graph legend for lines and patches
Produce the TeX format from character string
Graphics
title
xlabel
ylabel
zlabel
Titles for 2-D and 3-D plots
X-axis labels for 2-D and 3-D plots
Y-axis labels for 2-D and 3-D plots
Z-axis labels for 3-D plots
Specialized Plotting
• “Area, Bar, and Pie Plots”
• “Contour Plots”
• “Direction and Velocity Plots”
• “Discrete Data Plots”
• “Function Plots”
• “Histograms”
• “Polygons and Surfaces”
• “Scatter Plots”
• “Animation”
Area, Bar, and Pie Plots
area
bar
barh
bar3
bar3h
pareto
pie
pie3
Area plot
Vertical bar chart
Horizontal bar chart
Vertical 3-D bar chart
Horizontal 3-D bar chart
Pareto char
Pie plot
3-D pie plot
Contour Plots
contour
contour3
contourc
contourf
ezcontour
ezcontourf
Contour (level curves) plot
3-D contour plot
Contour computation
Filled contour plot
Easy to use contour plotter
Easy to use filled contour plotter
Direction and Velocity Plots
comet
comet3
Comet plot
3-D comet plot
1-39
1
Functions – By Category
compass
feather
quiver
quiver3
Compass plot
Feather plot
Quiver (or velocity) plot
3-D quiver (or velocity) plot
Discrete Data Plots
stem
stem3
stairs
Plot discrete sequence data
Plot discrete surface data
Stairstep graph
Function Plots
ezcontour
ezcontourf
ezmesh
ezmeshc
ezplot
ezplot3
ezpolar
ezsurf
ezsurfc
fplot
Easy to use contour plotter
Easy to use filled contour plotter
Easy to use 3-D mesh plotter
Easy to use combination mesh/contour plotter
Easy to use function plotter
Easy to use 3-D parametric curve plotter
Easy to use polar coordinate plotter
Easy to use 3-D colored surface plotter
Easy to use combination surface/contour plotter
Plot a function
Histograms
hist
histc
rose
Plot histograms
Histogram count
Plot rose or angle histogram
Polygons and Surfaces
convhull
cylinder
delaunay
dsearch
ellipsoid
fill
fill3
inpolygon
pcolor
polyarea
ribbon
slice
sphere
1-40
Convex hull
Generate cylinder
Delaunay triangulation
Search Delaunay triangulation for nearest point
Generate ellipsoid
Draw filled 2-D polygons
Draw filled 3-D polygons in 3-space
True for points inside a polygonal region
Pseudocolor (checkerboard) plot
Area of polygon
Ribbon plot
Volumetric slice plot
Generate sphere
Graphics
tsearch
voronoi
waterfall
Search for enclosing Delaunay triangle
Voronoi diagram
Waterfall plot
Scatter Plots
plotmatrix
scatter
scatter3
Scatter plot matrix
Scatter plot
3-D scatter plot
Animation
frame2im
getframe
im2frame
movie
noanimate
Convert movie frame to indexed image
Capture movie frame
Convert image to movie frame
Play recorded movie frames
Change EraseMode of all objects to normal
Bit-Mapped Images
frame2im
image
imagesc
imfinfo
imformats
im2frame
im2java
imread
imwrite
ind2rgb
Convert movie frame to indexed image
Display image object
Scale data and display image object
Information about graphics file
Manage file format registry
Convert image to movie frame
Convert image to instance of Java image object
Read image from graphics file
Write image to graphics file
Convert indexed image to RGB image
Printing
frameedit
orient
pagesetupdlg
print
printdlg
printopt
printpreview
saveas
Edit print frame for Simulink and Stateflow diagram
Hardcopy paper orientation
Page position dialog box
Print graph or save graph to file
Print dialog box
Configure local printer defaults
Preview figure to be printed
Save figure to graphic file
1-41
1
Functions – By Category
Handle Graphics
• Finding and Identifying Graphics Objects
• Object Creation Functions
• Figure Windows
• Axes Operations
Finding and Identifying Graphics Objects
allchild
copyobj
delete
findall
figflag
findfigs
findobj
gca
gcbo
gcbf
gco
get
ishandle
set
Find all children of specified objects
Make copy of graphics object and its children
Delete files or graphics objects
Find all graphics objects (including hidden handles)
Test if figure is on screen
Display off-screen visible figure windows
Find objects with specified property values
Get current Axes handle
Return object whose callback is currently executing
Return handle of figure containing callback object
Return handle of current object
Get object properties
True if value is valid object handle
Set object properties
Object Creation Functions
axes
Create axes object
figure
Create figure (graph) windows
image
Create image (2-D matrix)
light
Create light object (illuminates Patch and Surface)
line
Create line object (3-D polylines)
patch
Create patch object (polygons)
rectangle
Create rectangle object (2-D rectangle)
rootobject
List of root properties
surface
Create surface (quadrilaterals)
text
Create text object (character strings)
uicontextmenu Create context menu (popup associated with object)
Figure Windows
capture
clc
clf
1-42
Screen capture of the current figure
Clear figure window
Clear figure
Graphics
close
closereq
drawnow
figflag
gcf
hgload
hgsave
newplot
opengl
refresh
saveas
Close specified window
Default close request function
Complete any pending drawing
Test if figure is on screen
Get current figure handle
Load graphics object hierarchy from a FIG-file
Save graphics object hierarchy to a FIG-file
Graphics M-file preamble for NextPlot property
Change automatic selection mode of OpenGL rendering
Refresh figure
Save figure or model to desired output format
Axes Operations
axis
box
cla
gca
grid
ishold
Plot axis scaling and appearance
Display axes border
Clear Axes
Get current Axes handle
Grid lines for 2-D and 3-D plots
Get the current hold state
1-43
1
Functions – By Category
3-D Visualization
Create and manipulate graphics that display 2-D matrix and 3-D volume data,
controlling the view, lighting and transparency.
Surface and Mesh Plots
Plot matrices, visualize functions of two variables,
specify colormap
View Control
Control the camera viewpoint, zooming, rotation,
aspect ratio, set axis limits
Lighting
Add and control scene lighting
Transparency
Specify and control object transparency
Volume Visualization
Visualize gridded volume data
Surface and Mesh Plots
• Creating Surfaces and Meshes
• Domain Generation
• Color Operations
• Colormaps
Creating Surfaces and Meshes
hidden
meshc
mesh
peaks
surf
surface
surfc
surfl
tetramesh
trimesh
triplot
trisurf
Mesh hidden line removal mode
Combination mesh/contourplot
3-D mesh with reference plane
A sample function of two variables
3-D shaded surface graph
Create surface low-level objects
Combination surf/contourplot
3-D shaded surface with lighting
Tetrahedron mesh plot
Triangular mesh plot
2-D triangular plot
Triangular surface plot
Domain Generation
griddata
meshgrid
1-44
Data gridding and surface fitting
Generation of X and Y arrays for 3-D plots
3-D Visualization
Color Operations
brighten
Brighten or darken color map
caxis
Pseudocolor axis scaling
colormapeditorStart colormap editor
colorbar
Display color bar (color scale)
colordef
Set up color defaults
colormap
Set the color look-up table (list of colormaps)
ColorSpec
Ways to specify color
graymon
Graphics figure defaults set for grayscale monitor
hsv2rgb
Hue-saturation-value to red-green-blue conversion
rgb2hsv
RGB to HSVconversion
rgbplot
Plot color map
shading
Color shading mode
spinmap
Spin the colormap
surfnorm
3-D surface normals
whitebg
Change axes background color for plots
Colormaps
autumn
bone
contrast
cool
copper
flag
gray
hot
hsv
jet
lines
prism
spring
summer
winter
Shades of red and yellow color map
Gray-scale with a tinge of blue color map
Gray color map to enhance image contrast
Shades of cyan and magenta color map
Linear copper-tone color map
Alternating red, white, blue, and black color map
Linear gray-scale color map
Black-red-yellow-white color map
Hue-saturation-value (HSV) color map
Variant of HSV
Line color colormap
Colormap of prism colors
Shades of magenta and yellow color map
Shades of green and yellow colormap
Shades of blue and green color map
View Control
• Controlling the Camera Viewpoint
• Setting the Aspect Ratio and Axis Limits
• Object Manipulation
• Selecting Region of Interest
1-45
1
Functions – By Category
Controlling the Camera Viewpoint
camdolly
camlookat
camorbit
campan
campos
camproj
camroll
camtarget
camup
camva
camzoom
view
viewmtx
Move camera position and target
View specific objects
Orbit about camera target
Rotate camera target about camera position
Set or get camera position
Set or get projection type
Rotate camera about viewing axis
Set or get camera target
Set or get camera up-vector
Set or get camera view angle
Zoom camera in or out
3-D graph viewpoint specification.
Generate view transformation matrices
Setting the Aspect Ratio and Axis Limits
daspect
pbaspect
xlim
ylim
zlim
Set or get data aspect ratio
Set or get plot box aspect ratio
Set or get the current x-axis limits
Set or get the current y-axis limits
Set or get the current z-axis limits
Object Manipulation
reset
Reset axis or figure
rotate
Rotate objects about specified origin and direction
rotate3d
Interactively rotate the view of a 3-D plot
selectmoveresizeInteractively select, move, or resize objects
zoom
Zoom in and out on a 2-D plot
Selecting Region of Interest
dragrect
rbbox
Drag XOR rectangles with mouse
Rubberband box
Lighting
camlight
light
lightangle
lighting
material
1-46
Cerate or position Light
Light object creation function
Position light in sphereical coordinates
Lighting mode
Material reflectance mode
3-D Visualization
Transparency
alpha
alphamap
alim
Set or query transparency properties for objects in current axes
Specify the figure alphamap
Set or query the axes alpha limits
Volume Visualization
coneplot
Plot velocity vectors as cones in 3-D vector field
contourslice Draw contours in volume slice plane
curl
Compute curl and angular velocity of vector field
divergence
Compute divergence of vector field
flow
Generate scalar volume data
interpstreamspeedInterpolate streamline vertices from vector-field
magnitudes
isocaps
Compute isosurface end-cap geometry
isocolors
Compute colors of isosurface vertices
isonormals
Compute normals of isosurface vertices
isosurface
Extract isosurface data from volume data
reducepatch Reduce number of patch faces
reducevolume Reduce number of elements in volume data set
shrinkfaces Reduce size of patch faces
slice
Draw slice planes in volume
smooth3
Smooth 3-D data
stream2
Compute 2-D stream line data
stream3
Compute 3-D stream line data
streamline
Draw stream lines from 2- or 3-D vector data
streamparticlesDraws stream particles from vector volume data
streamribbon Draws stream ribbons from vector volume data
streamslice Draws well-spaced stream lines from vector volume data
streamtube
Draws stream tubes from vector volume data
surf2patch
Convert surface data to patch data
subvolume
Extract subset of volume data set
volumebounds Return coordinate and color limits for volume (scalar and
vector)
1-47
1
Functions – By Category
Creating Graphical User Interfaces
Predefined dialog boxes and functions to control GUI programs.
Predefined Dialog Boxes
Dialog boxes for error, user input, waiting, etc.
Deploying User
Interfaces
Launching GUIs, creating the handles structure
Developing User
Interfaces
Starting GUIDE, managing application data,
getting user input
User Interface Objects
Creating GUI components
Finding Objects from
Callbacks
Finding object handles from within callbacks
functions
GUI Utility Functions
Moving objects, text wrapping
Controlling Program
Execution
Wait and resume based on user input
Predefined Dialog Boxes
dialog
errordlg
helpdlg
inputdlg
listdlg
msgbox
pagedlg
printdlg
questdlg
uigetdir
uigetfile
uiputfile
uisetcolor
uisetfont
waitbar
warndlg
1-48
Create dialog box
Create error dialog box
Display help dialog box
Create input dialog box
Create list selection dialog box
Create message dialog box
Display page layout dialog box
Display print dialog box
Create question dialog box
Display dialog box to retrieve name of directory
Display dialog box to retrieve name of file for reading
Display dialog box to retrieve name of file for writing
Set ColorSpec using dialog box
Set font using dialog box
Display wait bar
Create warning dialog box
Creating Graphical User Interfaces
Deploying User Interfaces
guidata
guihandles
movegui
openfig
Store or retrieve application data
Create a structure of handles
Move GUI figure onscreen
Open or raise GUI figure
Developing User Interfaces
guide
inspect
Open GUI Layout Editor
Display Property Inspector
Working with Application Data
getappdata
isappdata
rmappdata
setappdata
Get value of application data
True if application data exists
Remove application data
Specify application data
Interactive User Input
ginput
Graphical input from a mouse or cursor
waitfor
Wait for conditions before resuming execution
waitforbuttonpressWait for key/buttonpress over figure
User Interface Objects
menu
Generate menu of choices for user input
uicontextmenu Create context menu
uicontrol
Create user interface control
uimenu
Create user interface menu
Finding Objects from Callbacks
findall
findfigs
findobj
gcbf
gcbo
Find all graphics objects
Display off-screen visible figure windows
Find specific graphics object
Return handle of figure containing callback object
Return handle of object whose callback is executing
GUI Utility Functions
selectmoveresizeSelect, move, resize, or copy axes and uicontrol graphics
textwrap
objects
Return wrapped string matrix for given uicontrol
1-49
1
Functions – By Category
Controlling Program Execution
uiresume
uiwait
1-50
Resumes program execution halted with uiwait
Halts program execution, restart with uiresume
2
Functions – Alphabetical
List
2
Functions – Alphabetical List
Arithmetic Operators + - * / \ ^ ' . . . . . . . . . . . . . . . . . . . . . . .
Relational Operators < > <= >= == ~= . . . . . . . . . . . . . .
Logical Operators, Element-wise & | ~ . . . . . . . . . . . . . . . . . .
Logical Operators, Short-circuit && || . . . . . . . . . . . . . . . . . .
Special Characters [ ] ( ) {} = ' . ... , ; % ! . . . . . . . . . . . . . . . . . .
Colon : . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
abs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
acos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
acosh . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
acot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
acoth . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
acsc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
acsch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
actxcontrol . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
actxserver . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
addframe . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
addpath . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
addproperty (COM) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
airy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
alim . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
all . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
allchild . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
alpha . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
alphamap . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
angle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
ans . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
any . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
area . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
asec . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
asech . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
asin . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
asinh . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
assignin . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
atan . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
atan2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
atanh . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
audiodevinfo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2-2
2-11
2-19
2-20
2-22
2-24
2-27
2-29
2-30
2-32
2-34
2-36
2-38
2-40
2-42
2-46
2-48
2-50
2-52
2-53
2-55
2-56
2-58
2-59
2-62
2-64
2-65
2-66
2-68
2-70
2-72
2-74
2-76
2-78
2-80
2-82
2-84
2-86
audioplayer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-88
audiorecorder . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-92
auread . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-97
auwrite . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-98
avifile . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-99
aviinfo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-102
aviread . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-104
axes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-105
Axes Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-117
axis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-138
balance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-144
bar, barh . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-147
bar3, bar3h . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-151
base2dec . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-155
beep . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-156
besselh . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-157
besseli . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-161
besselk . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-164
besselj . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-167
bessely . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-170
beta . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-173
betainc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-175
betaln . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-176
bicg . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-177
bicgstab . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-184
bin2dec . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-189
bitand . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-190
bitcmp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-191
bitget . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-192
bitmax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-193
bitor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-194
bitset . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-195
bitshift . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-196
bitxor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-197
blanks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-198
blkdiag . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-199
box . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-200
2-3
2
Functions – Alphabetical List
break . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
brighten . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
builtin . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
bvp4c . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
bvpget . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
bvpinit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
bvpset . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
bvpval . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
calendar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
camdolly . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
camlight . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
camlookat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
camorbit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
campan . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
campos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
camproj . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
camroll . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
camtarget . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
camup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
camva . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
camzoom . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
capture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
cart2pol . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
cart2sph . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
case . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
cat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
catch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
caxis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
cd . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
cdf2rdf . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
cdfepoch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
cdfinfo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
cdfread . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
cdfwrite . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
ceil . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
cell . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
cell2mat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2-4
2-201
2-202
2-204
2-205
2-212
2-213
2-215
2-218
2-219
2-220
2-222
2-224
2-226
2-228
2-229
2-231
2-232
2-233
2-235
2-237
2-239
2-240
2-241
2-242
2-243
2-244
2-245
2-246
2-250
2-251
2-253
2-254
2-258
2-260
2-263
2-264
2-266
cell2struct . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
celldisp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
cellfun . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
cellplot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
cellstr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
cgs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
char . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
checkin . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
checkout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
chol . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
cholinc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
cholupdate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
circshift . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
cla . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
clabel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
clc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
clear . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
clear (serial) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
clf . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
clipboard . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
clock . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
close . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
close . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
closereq . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
cmopts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
colamd . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
colmmd . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
colorbar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
colordef . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
colormap . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
colormapeditor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
ColorSpec . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
colperm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
comet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
comet3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
compan . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2-268
2-269
2-270
2-272
2-273
2-274
2-278
2-280
2-282
2-285
2-287
2-294
2-297
2-298
2-299
2-301
2-303
2-304
2-308
2-309
2-310
2-311
2-312
2-314
2-315
2-316
2-317
2-319
2-322
2-324
2-326
2-330
2-346
2-348
2-349
2-350
2-351
2-5
2
Functions – Alphabetical List
compass . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
complex . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
computer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
cond . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
condeig . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
condest . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
coneplot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
conj . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
continue . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
contour . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
contour3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
contourc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
contourf . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
contourslice . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
contrast . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
conv . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
conv2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
convhull . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
convhulln . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
convn . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
copyfile . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
copyobj . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
corrcoef . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
cos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
cosh . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
cot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
coth . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
cov . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
cplxpair . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
cputime . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
cross . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
csc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
csch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
csvread . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
csvwrite . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
cumprod . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
cumsum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2-6
2-352
2-354
2-356
2-357
2-358
2-359
2-360
2-365
2-366
2-367
2-371
2-373
2-375
2-377
2-380
2-381
2-382
2-386
2-388
2-390
2-391
2-393
2-395
2-398
2-400
2-402
2-404
2-406
2-407
2-408
2-409
2-410
2-412
2-414
2-416
2-417
2-418
cumtrapz . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
curl . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
customverctrl . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
cylinder . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
daspect . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
date . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
datenum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
datestr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
datetick . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
datevec . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
dbclear . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
dbcont . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
dbdown . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
dblquad . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
dbmex . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
dbquit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
dbstack . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
dbstatus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
dbstep . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
dbstop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
dbtype . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
dbup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
dde23 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
ddeadv . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
ddeexec . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
ddeget . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
ddeinit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
ddepoke . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
ddereq . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
ddeset . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
ddeterm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
ddeunadv . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
deal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
deblank . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
dec2base . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
dec2bin . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
dec2hex . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2-419
2-421
2-424
2-425
2-428
2-431
2-432
2-434
2-437
2-440
2-442
2-444
2-445
2-446
2-448
2-449
2-450
2-451
2-452
2-453
2-457
2-458
2-459
2-463
2-465
2-466
2-467
2-468
2-470
2-472
2-475
2-476
2-477
2-479
2-480
2-481
2-482
2-7
2
Functions – Alphabetical List
deconv . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
del2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
delaunay . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
delaunay3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
delaunayn . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
delete . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
delete (COM) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
delete (serial) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
delete (timer) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
deleteproperty (COM) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
demo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
depdir . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
depfun . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
det . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
detrend . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
deval . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
diag . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
dialog . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
diary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
diff . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
dir . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
disp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
disp (serial) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
disp (timer) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
display . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
divergence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
dlmread . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
dlmwrite . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
dmperm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
doc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
docopt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
docroot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
dos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
dot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
double . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
dragrect . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
drawnow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2-8
2-483
2-484
2-487
2-492
2-495
2-498
2-499
2-501
2-502
2-503
2-504
2-507
2-508
2-512
2-513
2-515
2-517
2-519
2-520
2-521
2-523
2-525
2-526
2-527
2-529
2-531
2-533
2-534
2-535
2-536
2-537
2-538
2-539
2-541
2-542
2-543
2-544
dsearch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
dsearchn . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
echo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
edit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
eig . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
eigs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
ellipj . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
ellipke . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
ellipsoid . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
else . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
elseif . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
end . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
eomday . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
eps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
erf, erfc, erfcx, erfinv, erfcinv . . . . . . . . . . . . . . . . . . . . . . . . .
error . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
errorbar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
errordlg . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
etime . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
etree . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
etreeplot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
eval . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
evalc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
evalin . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
eventlisteners (COM) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
events (COM) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
exist . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
exit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
exp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
expint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
expm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
eye . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
ezcontour . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
ezcontourf . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
ezmesh . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
ezmeshc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
ezplot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2-545
2-546
2-547
2-548
2-550
2-554
2-562
2-564
2-566
2-567
2-568
2-570
2-572
2-573
2-574
2-576
2-578
2-580
2-582
2-583
2-584
2-585
2-587
2-588
2-590
2-592
2-594
2-596
2-597
2-598
2-599
2-601
2-602
2-605
2-608
2-610
2-612
2-9
2
Functions – Alphabetical List
ezplot3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
ezpolar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
ezsurf . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
ezsurfc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2-10
2-614
2-616
2-618
2-621
Arithmetic Operators + - * / \ ^ '
Purpose
Syntax
Description
2Arithmetic Operators + - * / \ ^ '
Matrix and array arithmetic
A+B
A-B
A∗B
A/B
A\B
A^B
A'
A.∗B
A./B
A.\B
A.^B
A.'
MATLAB has two different types of arithmetic operations. Matrix arithmetic
operations are defined by the rules of linear algebra. Array arithmetic
operations are carried out element-by-element, and can be used with
multidimensional arrays. The period character (.) distinguishes the array
operations from the matrix operations. However, since the matrix and array
operations are the same for addition and subtraction, the character pairs .+
and .- are not used.
+
Addition or unary plus. A+B adds A and B. A and B must have the same
size, unless one is a scalar. A scalar can be added to a matrix of any size.
-
Subtraction or unary minus. A-B subtracts B from A. A and B must have
the same size, unless one is a scalar. A scalar can be subtracted from a
matrix of any size.
*
Matrix multiplication. C = A∗B is the linear algebraic product of the
matrices A and B. More precisely,
n
C ( i, j ) =
∑
A ( i, k )B ( k, j )
k=1
For nonscalar A and B, the number of columns of A must equal the
number of rows of B. A scalar can multiply a matrix of any size.
.∗
Array multiplication. A.∗B is the element-by-element product of the
arrays A and B. A and B must have the same size, unless one of them is a
scalar.
/
Slash or matrix right division. B/A is roughly the same as B∗inv(A).
More precisely, B/A = (A'\B')'. See \.
2-11
Arithmetic Operators + - * / \ ^ '
./
Array right division. A./B is the matrix with elements A(i,j)/B(i,j).
A and B must have the same size, unless one of them is a scalar.
\
Backslash or matrix left division. If A is a square matrix, A\B is roughly
the same as inv(A)∗B, except it is computed in a different way. If A is
an n-by-n matrix and B is a column vector with n components, or a
matrix with several such columns, then X = A\B is the solution to the
equation AX = B computed by Gaussian elimination (see “Algorithm” on
page 2-15 for details). A warning message prints if A is badly scaled or
nearly singular.
If A is an m-by-n matrix with m ~= n and B is a column vector with m
components, or a matrix with several such columns, then X = A\B is the
solution in the least squares sense to the under- or overdetermined
system of equations AX = B. The effective rank, k, of A, is determined
from the QR decomposition with pivoting (see “Algorithm” for details).
A solution X is computed which has at most k nonzero components per
column. If k < n, this is usually not the same solution as pinv(A)∗B,
which is the least squares solution with the smallest norm, X .
.\
Array left division. A.\B is the matrix with elements B(i,j)/A(i,j). A
and B must have the same size, unless one of them is a scalar.
^
Matrix power. X^p is X to the power p, if p is a scalar. If p is an integer,
the power is computed by repeated squaring. If the integer is negative,
X is inverted first. For other values of p, the calculation involves
eigenvalues and eigenvectors, such that if [V,D] = eig(X), then
X^p = V∗D.^p/V.
If x is a scalar and P is a matrix, x^P is x raised to the matrix power P
using eigenvalues and eigenvectors. X^P, where X and P are both
matrices, is an error.
2-12
.^
Array power. A.^B is the matrix with elements A(i,j) to the B(i,j)
power. A and B must have the same size, unless one of them is a scalar.
'
Matrix transpose. A' is the linear algebraic transpose of A. For complex
matrices, this is the complex conjugate transpose.
.'
Array transpose. A.' is the array transpose of A. For complex matrices,
this does not involve conjugation.
Arithmetic Operators + - * / \ ^ '
Remarks
Examples
The arithmetic operators have M-file function equivalents, as shown:
Binary addition
A+B
plus(A,B)
Unary plus
+A
uplus(A)
Binary subtraction
A-B
minus(A,B)
Unary minus
-A
uminus(A)
Matrix multiplication
A*B
mtimes(A,B)
Array-wise multiplication
A.*B
times(A,B)
Matrix right division
A/B
mrdivide(A,B)
Array-wise right division
A./B
rdivide(A,B)
Matrix left division
A\B
mldivide(A,B)
Array-wise left division
A.\B
ldivide(A,B)
Matrix power
A^B
mpower(A,B)
Array-wise power
A.^B
power(A,B)
Complex transpose
A'
ctranspose(A)
Matrix transpose
A.'
transpose(A)
Here are two vectors, and the results of various matrix and array operations on
them, printed with format rat.
Matrix Operations
Array Operations
x
1
2
3
x'
1
x+y
5
7
9
2
3
y
4
5
6
y'
4
x-y
5
6
-3
-3
-3
2-13
Arithmetic Operators + - * / \ ^ '
Matrix Operations
2-14
Array Operations
x + 2
3
4
5
x-2
-1
0
1
x ∗ y
Error
x.∗y
4
10
18
x'∗y
32
x'.∗y
Error
x∗y'
4
8
12
x.∗y'
Error
x∗2
2
4
6
x.∗2
2
4
6
x\y
16/7
x.\y
4
5/2
2
2\x
1/2
1
3/2
2./x
2
1
2/3
x/y
0
0
0
x./y
1/4
2/5
1/2
x/2
1/2
1
3/2
x./2
1/2
1
3/2
x^y
Error
x.^y
1
32
729
x^2
Error
x.^2
1
4
9
5
10
15
0
0
0
6
12
18
1/6
1/3
1/2
Arithmetic Operators + - * / \ ^ '
Matrix Operations
Algorithm
Array Operations
2^x
Error
2.^x
(x+i∗y)'
1 - 4i
2 - 5i
3 - 6i
(x+i∗y).'
1 + 4i
2 + 5i
3 + 6i
2
4
8
The specific algorithm used for solving the simultaneous linear equations
denoted by X = A\B and X = B/A depends upon the structure of the coefficient
matrix A. To determine the structure of A and select the appropriate algorithm,
MATLAB follows this precedence:
1 If A is sparse, square, and banded, then banded solvers are used. Band
density is (# nonzeros in the band)/(# nonzeros in a full band).
Band density = 1.0 if there are no zeros on any of the three diagonals.
- If A is real and tridiagonal, i.e., band density = 1.0, and B is real with only
one column, X is computed quickly using Gaussian elimination without
pivoting.
- If the tridiagonal solver detects a need for pivoting, or if A or B is not real,
or if B has more than one column, but A is banded with band density
greater than the spparms parameter 'bandden' (default = 0.5), then X is
computed using LAPACK.
2 If A is an upper or lower triangular matrix, then X is computed quickly
with a backsubstitution algorithm for upper triangular matrices, or a
forward substitution algorithm for lower triangular martrices. The check for
triangularity is done for full matrices by testing for zero elements and for
sparse matrices by accessing the sparse data structure.
3 If A is a permutation of a triangular matrix, then X is computed with a
permuted backsubstitution algorithm.
4 If A is symmetric, or Hermitian, and has positive diagonal elements,
then a Cholesky factorization is attempted (see chol). If A is found to be
positive definite, the Cholesky factorization attempt is successful and
requires less than half the time of a general factorization. Nonpositive
definite matrices are usually detected almost immediately, so this check
also requires little time. If successful, the Cholesky factorization is
2-15
Arithmetic Operators + - * / \ ^ '
A = R'∗R
where R is upper triangular. The solution X is computed by solving two
triangular systems,
X = R\(R'\B)
If A is sparse, a symmetric minimum degree preordering is applied (see
symmmd and spparms). The algorithm is:
perm = symmmd(A);
R = chol(A(perm,perm));
Y = R'\B(perm);
X(perm,:) = R\Y;
%
%
%
%
Symmetric minimum degree reordering
Cholesky factorization
Lower triangular solve
Upper triangular solve
5 If A is Hessenberg, but not sparse, it is reduced to an upper triangular
matrix and that system is solved via substitution.
6 If A is square, and does not satisfy criteria 1 through 5, then a general
triangular factorization is computed by Gaussian elimination with partial
pivoting (see lu). This results in
A = L∗U
where L is a permutation of a lower triangular matrix and U is an upper
triangular matrix. Then X is computed by solving two permuted triangular
systems.
X = U\(L\B)
If A is sparse, then UMFPACK is used to compute X. The computations
result in
P*A*Q = L*U
where P is a row permutaion matrix and Q is a column reordering matrix.
Then X = Q*(U\L\(P*B)).
7 If A is not square, then Householder reflections are used to compute an
orthogonal-triangular factorization.
A∗P = Q∗R
where P is a permutation, Q is orthogonal and R is upper triangular (see qr).
The least squares solution X is computed with
2-16
Arithmetic Operators + - * / \ ^ '
X = P∗(R\(Q'∗B))
If A is sparse, then MATLAB computes a least squares solution using the
sparse qr factorization of A.
Note For sparse matrices, to see information about choice of algorithm and
storage allocation, set the spparms parameter 'spumoni' = 1.
Note Backslash is not implemented for sparse matrices A that are complex
but not square.
MATLAB uses LAPACK routines to compute these matrix factorizations:
Matrix
Real
Complex
Sparse square banded with band
density > 'bandden'.
DGBTRF, DGBTRS
ZGBTRF,
ZGBTRS
Full square, symmetric (Hermitian)
positive definite
DLANGE, DPOTRF,
DPOTRS, DPOCON
ZLANGE, ZPOTRF,
ZPOTRS ZPOCON
Full square, general case
DLANGE, DGESV,
DGECON
ZLANGE, ZGESV,
ZGECON
Full non-square
DGEQP3, DORMQR,
DTRTRS
ZGEQP3, ZORMQR,
ZTRTRS
For other cases (sparse, triangular and Hessenberg) MATLAB does not use
LAPACK.
Diagnostics
• From matrix division, if a square A is singular:
Warning: Matrix is singular to working precision.
• From element-wise division, if the divisor has zero elements:
2-17
Arithmetic Operators + - * / \ ^ '
Warning: Divide by zero.
Matrix division and element-wise division may produce NaNs or Infs where
appropriate.
• If the inverse was found, but is not reliable:
Warning: Matrix is close to singular or badly scaled.
Results may be inaccurate. RCOND = xxx
• From matrix division, if a nonsquare A is rank deficient:
Warning: Rank deficient, rank = xxx tol = xxx
See Also
chol, det, inv, lu, orth, permute, ipermute, qr, rref
References
[1] Anderson, E., Z. Bai, C. Bischof, S. Blackford, J. Demmel, J. Dongarra,
J. Du Croz, A. Greenbaum, S. Hammarling, A. McKenney, and D. Sorensen,
LAPACK User’s Guide
(http://www.netlib.org/lapack/lug/lapack_lug.html), Third Edition,
SIAM, Philadelphia, 1999.
[2] Davis, T.A., UMFPACK Version 4.0 User Guide
(http://www.cise.ufl.edu/research/sparse/umfpack/v4.0/UserGuide.pdf),
Dept. of Computer and Information Science and Engineering, Univ. of Florida,
Gainesville, FL, 2002.
2-18
Relational Operators <
Purpose
2Relational Operators <
> <=
> <=
>= == ~=
>= == ~=
Relational operations
Syntax
A
A
A
A
A
A
Description
The relational operators are <, >, <=, >=, ==, and ~=. Relational operators
perform element-by-element comparisons between two arrays. They return a
logical array of the same size, with elements set to true (1) where the relation
is true, and elements set to false (0) where it is not.
< B
> B
<= B
>= B
== B
~= B
The operators <, >, <=, and >= use only the real part of their operands for the
comparison. The operators == and ~= test real and imaginary parts.
To test if two strings are equivalent, use strcmp, which allows vectors of
dissimilar length to be compared.
Examples
If one of the operands is a scalar and the other a matrix, the scalar expands to
the size of the matrix. For example, the two pairs of statements:
X = 5; X >= [1 2 3; 4 5 6; 7 8 10]
X = 5∗ones(3,3); X >= [1 2 3; 4 5 6; 7 8 10]
produce the same result:
ans =
1
1
0
See Also
1
1
0
1
0
0
all, any, find, strcmp
The logical operators &, |, ~
2-19
Logical Operators, Element-wise & | ~
Purpose
2Logical Operators, Element-wise & | ~
Element-wise logical operations on arrays
Syntax
A & B
A | B
~A
Description
The symbols &, |, and ~ are the logical array operators AND, OR, and NOT. They
work element-by-element on arrays, with 0 representing logical false (F), and
anything nonzero representing logical true (T). The logical operators return a
logical array with elements set to true (1) or false (0), as appropriate.
The & operator does a logical AND, the | operator does a logical OR, and ~A
complements the elements of A. The function xor(A,B) implements the
exclusive OR operation. The truth table for these operators and functions is
shown below.
Inputs
A
B
and
A & B
or
A | B
not
~A
xor
xor(A,B)
0
0
0
0
1
0
0
1
0
1
1
1
1
0
0
1
0
1
1
1
1
1
0
0
The precedence for the logical operators with respect to each other is
2-20
Operator
Operation
Priority
~
NOT
Highest
&
Element-wise AND
|
Element-wise OR
&&
Short-circuit AND
||
Short-circuit OR
Lowest
Logical Operators, Element-wise & | ~
Remarks
MATLAB always gives the & operator precedence over the | operator. Although
MATLAB typically evaluates expressions from left to right, the expression
a|b&c is evaluated as a|(b&c). It is a good idea to use parentheses to explicitly
specify the intended precedence of statements containing combinations of &
and |.
These logical operators have M-file function equivalents, as shown.
Examples
Logical Operation
Equivalent Function
A & B
and(A,B)
A | B
or(A,B)
~A
not(A)
This example shows the logical OR of the elements in the vector u with the
corresponding elements in the vector v:
u = [0 0 1 1 0 1];
v = [0 1 1 0 0 1];
u | v
ans =
0
See Also
1
1
1
0
1
all, any, find, logical, xor, true, false
Logical Operators, Short-circuit: &&, ||
Relational Operators: <, <=, >, >=, ==, ~=
2-21
Logical Operators, Short-circuit && ||
Purpose
2Logical Operators, Short-circuit && ||
Logical operations, with short-circuiting capability
Syntax
A && B
A || B
Description
The symbols && and || are the logical AND and OR operators used to evaluate
logical expressions. Use && and || in the evaluation of compound expressions
of the form
expression_1 && expression_2
where expression_1 and expression_2 each evaluate to a scalar, logical
result.
The && and || operators support short-circuiting. This means that the second
operand is evaluated only when the result is not fully determined by the first
operand. See “Short-circuit Operators” in the MATLAB documentation for a
discussion on short-circuiting with && and ||.
Note Always use the && and || operators when short-circuiting is required.
Using the element-wise operators (& and |) for short-circuiting may yield
unexpected results.
Examples
In the following statement, it doesn’t make sense to evaluate the relation on
the right if the divisor, b, is zero. The test on the left is put in to avoid
generating a warning under these circumstances:
x = (b ~= 0) && (a/b > 18.5)
By definition, if any operands of an AND expression are false, the entire
expression must be false. So, if (b ~= 0) evaluates to false, MATLAB
assumes the entire expression to be false and terminates its evaluation of the
expression early. This avoids the warning that would be generated if MATLAB
were to evaluate the operand on the right.
2-22
Logical Operators, Short-circuit && ||
See Also
all, any, find, logical, xor, true, false
Logical operators, Element-wise: &, |, ~
Relational Operators: <, <=, >, >=, ==, ~=
2-23
Special Characters [ ] ( ) {} = ' . ... , ; % !
Purpose
Syntax
2Special Characters [ ] ( ) {} = ' . ... , ; % !
Special characters
[ ] ( ) {} = ' . ... , ; % !
Description
2-24
[ ]
Brackets are used to form vectors and matrices. [6.9 9.64 sqrt(-1)]
is a vector with three elements separated by blanks. [6.9, 9.64, i]
is the same thing. [1+j 2-j 3] and [1 +j 2 -j 3] are not the same.
The first has three elements, the second has five.
[11 12 13; 21 22 23] is a 2-by-3 matrix. The semicolon ends the
first row.
Vectors and matrices can be used inside [ ] brackets. [A B;C] is
allowed if the number of rows of A equals the number of rows of B and
the number of columns of A plus the number of columns of B equals the
number of columns of C. This rule generalizes in a hopefully obvious
way to allow fairly complicated constructions.
A = [ ] stores an empty matrix in A. A(m,:) = [ ] deletes row m of A.
A(:,n) = [ ] deletes column n of A. A(n) = [ ] reshapes A into a
column vector and deletes the third element.
[A1,A2,A3...] = function assigns function output to multiple
variables.
For the use of [ and ] on the left of an “=” in multiple assignment
statements, see lu, eig, svd, and so on.
{ }
Curly braces are used in cell array assignment statements. For
example,
A(2,1) = {[1 2 3; 4 5 6]}, or A{2,2} = ('str'). See help paren
for more information about { }.
Special Characters [ ] ( ) {} = ' . ... , ; % !
( )
Parentheses are used to indicate precedence in arithmetic expressions
in the usual way. They are used to enclose arguments of functions in
the usual way. They are also used to enclose subscripts of vectors and
matrices in a manner somewhat more general than usual. If X and V
are vectors, then X(V) is [X(V(1)), X(V(2)), ..., X(V(n))]. The
components of V must be integers to be used as subscripts. An error
occurs if any such subscript is less than 1 or greater than the size of X.
Some examples are
• X(3) is the third element of X.
• X([1 2 3]) is the first three elements of X.
See help paren for more information about ( ).
If X has n components, X(n:–1:1) reverses them. The same indirect
subscripting works in matrices. If V has m components and W has n
components, then A(V,W) is the m-by-n matrix formed from the
elements of A whose subscripts are the elements of V and W. For
example, A([1,5],:) = A([5,1],:) interchanges rows 1 and 5 of A.
=
Used in assignment statements. B = A stores the elements of A in B.
== is the relational equals operator. See the Relational Operators
page.
'
Matrix transpose. X' is the complex conjugate transpose of X. X.' is
the nonconjugate transpose.
Quotation mark. 'any text' is a vector whose components are the
ASCII codes for the characters. A quotation mark within the text is
indicated by two quotation marks.
.
Decimal point. 314/100, 3.14 and .314e1 are all the same.
Element-by-element operations. These are obtained using .∗ , .^ , ./,
or .\. See the Arithmetic Operators page.
.
Field access. A.(field) and A(i).field, when A is a structure, access
the contents of field.
..
Parent directory. See cd.
...
Continuation. Three or more points at the end of a line indicate
continuation.
2-25
Special Characters [ ] ( ) {} = ' . ... , ; % !
Remarks
See Also
,
Comma. Used to separate matrix subscripts and function arguments.
Used to separate statements in multistatement lines. For
multi-statement lines, the comma can be replaced by a semicolon to
suppress printing.
;
Semicolon. Used inside brackets to end rows. Used after an expression
or statement to suppress printing or to separate statements.
%
Percent. The percent symbol denotes a comment; it indicates a logical
end of line. Any following text is ignored. MATLAB displays the first
contiguous comment lines in a M-file in response to a help command.
!
Exclamation point. Indicates that the rest of the input line is issued
as a command to the operating system. On the PC, adding & to the end
of the ! command line, as in !dir &, causes the output to appear in a
separate window.
Some uses of special characters have M-file function equivalents, as shown:
Horizontal concatenation
[A,B,C...]
horzcat(A,B,C...)
Vertical concatenation
[A;B;C...]
vertcat(A,B,C...)
Subscript reference
A(i,j,k...)
subsref(A,S). See help
subsref.
Subscript assignment
A(i,j,k...)= B
subsasgn(A,S,B). See help
subsasgn.
The arithmetic operators +, –, *, /, \, ^, '
The relational operators <, <=, >, >=, ==, ~=
The logical operators &, |, ~
2-26
Colon :
Purpose
2Colon :
Description
The colon is one of the most useful operators in MATLAB. It can create vectors,
subscript arrays, and specify for iterations.
Create vectors, array subscripting, and for loop iterations
The colon operator uses the following rules to create regularly spaced vectors:
j:k
is the same as [j,j+1,...,k]
j:k
is empty if j > k
j:i:k
is the same as [j,j+i,j+2i, ...,k]
j:i:k
is empty if i > 0 and j > k or if i < 0 and j < k
where i,j, and k are all scalars.
Below are the definitions that govern the use of the colon to pick out selected
rows, columns, and elements of vectors, matrices, and higher-dimensional
arrays:
A(:,j)
is the j-th column of A
A(i,:)
is the i-th row of A
A(:,:)
is the equivalent two-dimensional array. For matrices this is
the same as A.
A(j:k)
is A(j), A(j+1),...,A(k)
A(:,j:k)
is A(:,j), A(:,j+1),...,A(:,k)
A(:,:,k)
is the kth page of three-dimensional array A.
A(i,j,k,:)
is a vector in four-dimensional array A. The vector includes
A(i,j,k,1), A(i,j,k,2), A(i,j,k,3), and so on.
A(:)
is all the elements of A, regarded as a single column. On the
left side of an assignment statement, A(:) fills A, preserving
its shape from before. In this case, the right side must contain
the same number of elements as A.
2-27
Colon :
Examples
Using the colon with integers,
D = 1:4
results in
D =
1
2
3
4
Using two colons to create a vector with arbitrary real increments between the
elements,
E = 0:.1:.5
results in
E =
0
0.1000
0.2000
0.3000
0.4000
0.5000
The command
A(:,:,2) = pascal(3)
generates a three-dimensional array whose first page is all zeros.
See Also
2-28
A(:,:,1) =
0
0
0
0
0
0
0
0
0
A(:,:,2) =
1
1
1
2
1
3
1
3
6
for, linspace, logspace, reshape
abs
Purpose
2abs
Absolute value and complex magnitude
Syntax
Y = abs(X)
Description
abs(X) returns an array Y such that each element of Y is the absolute value of
the corresponding element of X.
If X is complex, abs(X) returns the complex modulus (magnitude), which is the
same as
sqrt(real(X).^2 + imag(X).^2)
Examples
abs(-5)
ans =
5
abs(3+4i)
ans =
5
See Also
angle, sign, unwrap
2-29
acos
Purpose
2acos
Inverse cosine
Syntax
Y = acos(X)
Description
Y = acos(X) returns the inverse cosine (arccosine) for each element of X. For
real elements of X in the domain [ – 1, 1 ] , acos(X) is real and in the range
[ 0, π ] . For real elements of X outside the domain [ – 1, 1 ] , acos(X) is complex.
The acos function operates element-wise on arrays. The function’s domains
and ranges include complex values. All angles are in radians.
Examples
Graph the inverse cosine function over the domain – 1 ≤ x ≤ 1 .
x = -1:.05:1;
plot(x,acos(x)), grid on
3.5
3
2.5
2
1.5
1
0.5
0
−1
Definition
0
0.5
The inverse cosine can be defined as
–1
cos ( z)
2-30
−0.5
1
--2 2
= – i log z + i ( 1 – z )
1
acos
Algorithm
acos uses FDLIBM, which was developed at SunSoft, a Sun Microsystems, Inc.
business, by Kwok C. Ng, and others. For information about FDLIBM, see
http://www.netlib.org.
See Also
acosh, cos
2-31
acosh
Purpose
2acosh
Inverse hyperbolic cosine
Syntax
Y = acosh(X)
Description
Y = acosh(X) returns the inverse hyperbolic cosine for each element of X.
The acosh function operates element-wise on arrays. The function’s domains
and ranges include complex values. All angles are in radians.
Examples
Graph the inverse hyperbolic cosine function over the domain 1 ≤ x ≤ π .
x = 1:pi/40:pi;
plot(x,acosh(x)), grid on
2
1.8
1.6
1.4
1.2
1
0.8
0.6
0.4
0.2
0
1
Definition
1.5
2
2.5
3.5
The hyperbolic inverse cosine can be defined as
–1
2
cosh ( z ) = log z + ( z – 1 )
Algorithm
3
1
--2
acosh uses FDLIBM, which was developed at SunSoft, a Sun Microsystems,
Inc. business, by Kwok C. Ng, and others. For information about FDLIBM, see
http://www.netlib.org.
2-32
acosh
See Also
acos, cosh
2-33
acot
Purpose
2acot
Inverse cotangent
Syntax
Y = acot(X)
Description
Y = acot(X) returns the inverse cotangent (arccotangent) for each element of X.
The acot function operates element-wise on arrays. The function’s domains
and ranges include complex values. All angles are in radians.
Examples
Graph the inverse cotangent over the domains – 2π ≤ x < 0 and 0 < x ≤ 2π .
x1 = -2*pi:pi/30:-0.1;
x2 = 0.1:pi/30:2*pi;
plot(x1,acot(x1),x2,acot(x2)), grid on
1.5
1
0.5
0
−0.5
−1
−1.5
−8
Definition
−6
−4
−2
0
2
4
6
8
The inverse cotangent can be defined as
1
cot– 1 ( z ) = tan– 1  --- 
 z
Algorithm
acot uses FDLIBM, which was developed at SunSoft, a Sun Microsystems, Inc.
business, by Kwok C. Ng, and others. For information about FDLIBM, see
http://www.netlib.org.
2-34
acot
See Also
cot, acoth
2-35
acoth
Purpose
2acoth
Inverse hyperbolic cotangent
Syntax
Y = acoth(X)
Description
Y = acoth(X) returns the inverse hyperbolic cotangent for each element of X.
The acoth function operates element-wise on arrays. The function’s domains
and ranges include complex values. All angles are in radians.
Examples
Graph the inverse hyperbolic cotangent over the domains – 30 ≤ x < – 1 and
1 < x ≤ 30 .
x1 = -30:0.1:-1.1;
x2 = 1.1:0.1:30;
plot(x1,acoth(x1),x2,acoth(x2)), grid on
2
1.5
1
0.5
0
−0.5
−1
−1.5
−2
−30
Definition
−20
−10
10
20
30
The hyperbolic inverse cotangent can be defined as
1
coth– 1 ( z ) = tanh– 1  --- 
 z
2-36
0
acoth
Algorithm
acoth uses FDLIBM, which was developed at SunSoft, a Sun Microsystems,
Inc. business, by Kwok C. Ng, and others. For information about FDLIBM, see
http://www.netlib.org.
See Also
acot, coth
2-37
acsc
Purpose
2acsc
Inverse cosecant
Syntax
Y = acsc(X)
Description
Y = acsc(X) returns the inverse cosecant (arccosecant) for each element of X.
The acsc function operates element-wise on arrays. The function’s domains
and ranges include complex values. All angles are in radians.
Examples
Graph the inverse cosecant over the domains – 10 ≤ x < – 1 and 1 < x ≤ 10 .
x1 = -10:0.01:-1.01;
x2 = 1.01:0.01:10;
plot(x1,acsc(x1),x2,acsc(x2)), grid on
1.5
1
0.5
0
−0.5
−1
−1.5
−10
Definition
−5
0
5
10
The inverse cosecant can be defined as
1
csc– 1 ( z ) = sin– 1  --- 
 z
Algorithm
acsc uses FDLIBM, which was developed at SunSoft, a Sun Microsystems, Inc.
business, by Kwok C. Ng, and others. For information about FDLIBM, see
http://www.netlib.org.
2-38
acsc
See Also
csc, acsch
2-39
acsch
Purpose
2acsch
Inverse cosecant and inverse hyperbolic cosecant
Syntax
Y = acsch(X)
Description
Y = acsch(X) returns the inverse hyperbolic cosecant for each element of X.
The acsch function operates element-wise on arrays. The function’s domains
and ranges include complex values. All angles are in radians.
Examples
Graph the inverse hyperbolic cosecant over the domains – 20 ≤ x ≤ – 1 and
1 ≤ x ≤ 20 .
x1 = -20:0.01:-1;
x2 = 1:0.01:20;
plot(x1,acsch(x1),x2,acsch(x2)), grid on
1
0.8
0.6
0.4
0.2
0
−0.2
−0.4
−0.6
−0.8
−1
−20
Definition
−15
−10
−5
5
10
15
The hyperbolic inverse cosecant can be defined as
1
csch– 1 ( z ) = sinh– 1  --- 
z
2-40
0
20
acsch
Algorithm
acsc uses FDLIBM, which was developed at SunSoft, a Sun Microsystems, Inc.
business, by Kwok C. Ng, and others. For information about FDLIBM, see
http://www.netlib.org.
See Also
acsc, csch
2-41
actxcontrol
Purpose
2actxcontrol
Create a COM control in a figure window
Syntax
h = actxcontrol (progid [, position [, fig_handle ...
[, callback | {event1 eventhandler1; event2 eventhandler2; ...}
[, filename]]]])
Arguments
progid
String that is the name of the control to create. The control vendor provides this
string.
position
Position vector containing the x and y location and the xsize and ysize of the
control, expressed in pixel units as [x y xsize ysize]. Defaults to [20 20 60
60].
fig_handle
Handle Graphics handle of the figure window in which the control is to be
created. If the control should be invisible, use the handle of an invisible figure
window. Defaults to gcf.
callback
Name of an M-function that accepts a variable number of arguments. This
function will be called whenever the control triggers an event. Each argument
is converted to a MATLAB string. See the section, “Writing Event Handlers” in
the External Interfaces documentation for more information on handling
control events.
event
Triggered event specified by either number or name.
eventhandler
Name of an M-function that accepts a variable number of arguments. This
function will be called whenever the control triggers the event associated with
it. See “Writing Event Handlers” in the External Interfaces documentation for
more information on handling control events.
filename
The name of a file to which a previously created control has been saved. When
you specify filename, MATLAB creates a new control using the position,
handle, and event/eventhandler arguments, and then initializes the control
from the specified file. The progid argument in actxcontrol must match the
progid of the saved control.
2-42
actxcontrol
Description
Create a COM control at a particular location within a figure window. If the
parent figure window is invisible, the control will be invisible. The returned
COM object represents the default interface for the control. This interface must
be released through a call to release when it is no longer needed to free the
memory and resources used by the interface. Note that releasing the interface
does not delete the control itself (use the delete command to delete the
control.)
The strings specified in the callback, event, and eventhandler arguments are
not case sensitive.
Note There are two ways to handle events. You can create a single handler
(callback) for all events, or you can specify a cell array that contains pairs of
events and event handlers. In the cell array format, specify events by name in
a quoted string. There is no limit to the number of pairs that can be specified
in the cell array. Although using the single callback method may be easier in
some cases, using the cell array technique creates more efficient code that
results in better performance.
For an example callback event handler, see the file sampev.m in the
toolbox\matlab\winfun\comcli directory.
Examples
Basic Control Methods
Create a control that runs Microsoft’s Calendar application:
f = figure('pos',[300 300 500 500]);
cal = actxcontrol('mscal.calendar', [0 0 500 500], f)
cal =
COM.mscal.calendar
Call the get method on cal to list all properties of the Calendar:
get(cal)
BackColor:
Day:
DayFont:
Value:
.
2.1475e+009
23
[1x1 Interface.mscal.calendar.DayFont]
'8/20/2001'
2-43
actxcontrol
.
Read just one property to record today’s date:
date = get(cal, 'Value')
date =
8/23/2001
Set the Day property to a new value:
set(cal, 'Day', 5);
date = get(cal, 'Value')
date =
8/5/2001
Calling invoke with no arguments lists all available methods:
meth = invoke(cal)
meth =
NextDay:
NextMonth:
NextWeek:
NextYear:
.
.
'HRESULT
'HRESULT
'HRESULT
'HRESULT
NextDay(handle)'
NextMonth(handle)'
NextWeek(handle)'
NextYear(handle)'
Invoke the NextWeek method to advance the current date by one week:
NextWeek(cal);
date = get(cal, 'Value')
date =
8/12/2001
Call events to list all Calendar events that can be triggered:
events(cal)
ans =
Click = void Click()
DblClick = void DblClick()
KeyDown = void KeyDown(int16 KeyCode, int16 Shift)
KeyPress = void KeyPress(int16 KeyAscii)
KeyUp = void KeyUp(int16 KeyCode, int16 Shift)
BeforeUpdate = void BeforeUpdate(int16 Cancel)
AfterUpdate = void AfterUpdate()
2-44
actxcontrol
NewMonth = void NewMonth()
NewYear = void NewYear()
Set Up Event Handling
See the section, Sample Event Handlers in the External Interfaces
documentation for examples of event handler functions and how to register
them with MATLAB.
See Also
actxserver, release, delete, save, load
2-45
actxserver
Purpose
2actxserver
Create a COM Automation server and return a COM object for the server’s
default interface
Syntax
h = actxserver (progid [, machinename])
Arguments
progid
This is a string that is the name of the control to instantiate. This string is
provided by the control or server vendor and should be obtained from the
vendor’s documentation. For example, the progid for MATLAB is
matlab.application.
machinename
This is the name of a remote machine on which the server is to be run. This
argument is optional and is used only in environments that support
Distributed Component Object Model (DCOM) — see “Using MATLAB As a
DCOM Server Client” in the External Interfaces documentation. This can be
an IP address or a DNS name.
Description
Create a COM Automation server and return a COM object that represents the
server’s default interface. Local/Remote servers differ from controls in that
they are run in a separate address space (and possibly on a separate machine)
and are not part of the MATLAB process. Additionally, any user interface that
they display will be in a separate window and will not be attached to the
MATLAB process. Examples of local servers are Microsoft Excel and Microsoft
Word. There is currently no support for events generated from automation
servers.
Examples
Launch Microsoft Excel and make the main frame window visible:
e = actxserver ('Excel.Application')
e =
COM.excel.application
set(e, 'Visible', 1);
2-46
actxserver
Call the get method on the excel object to list all properties of the application:
get(e)
ans =
Application: [1x1 Interface.excel.application.Application]
Creator: 'xlCreatorCode'
Parent: [1x1 Interface.Excel.Application.Parent]
Workbooks: [1x1 Interface.excel.application.Workbooks]
UsableHeight: 666.7500
.
.
Create an interface:
eWorkbooks = get(e, 'Workbooks')
eWorkbooks =
Interface.excel.application.Workbooks
List all methods for that interface by calling invoke with just the handle
argument:
invoke(eWorkbooks)
ans =
Add: 'handle Add(handle, [Optional]Variant)'
Close: 'void Close(handle)'
Item: 'handle Item(handle, Variant)'
Open: 'handle Open(handle, string, [Optional]Variant)'
OpenText: 'void OpenText(handle, string, [Optional]Variant)'
Invoke the Add method on workbooks to add a new workbook, also creating a
new interface:
w = Add(eWorkbooks)
w =
Interface.Excel.Application.Workbooks.Add
Quit the application and delete the object:
Quit(e);
delete(e);
See Also
actxcontrol, release, delete, save, load
2-47
addframe
Purpose
2addframe
Add a frame to an Audio Video Interleaved (AVI) file.
Syntax
aviobj
aviobj
aviobj
aviobj
Description
aviobj = addframe(aviobj,frame) appends the data in frame to the AVI file
identified by aviobj, which was created by a previous call to avifile. frame
can be either an indexed image (m-by-n) or a truecolor image (m-by-n-by-3) of
double or uint8 precision. If frame is not the first frame added to the AVI file,
=
=
=
=
addframe(aviobj,frame)
addframe(aviobj,frame1,frame2,frame3,...)
addframe(aviobj,mov)
addframe(aviobj,h)
it must be consistent with the dimensions of the previous frames.
addframe returns a handle to the updated AVI file object, aviobj. For example,
addframe updates the TotalFrames property of the AVI file object each time it
adds a frame to the AVI file.
aviobj = addframe(aviobj,frame1,frame2,frame3,...) adds multiple
frames to an AVI file.
aviobj = addframe(aviobj,mov) appends the frame(s) contained in the
MATLAB movie, mov, to the AVI file, aviobj. MATLAB movies that store
frames as indexed images use the colormap in the first frame as the colormap
for the AVI file, unless the colormap has been previously set.
aviobj = addframe(aviobj,h) captures a frame from the figure or axis handle
h, and appends this frame to the AVI file. addframe renders the figure into an
offscreen array before appending it to the AVI file. This ensures that the figure
is written correctly to the AVI file even if the figure is obscured on the screen
by another window or screen saver.
Note If an animation uses XOR graphics, you must use getframe to capture
the graphics into a frame of a MATLAB movie. You can then add the frame to
an AVI movie using the addframe syntax, aviobj = addframe(aviobj,mov).
See the example for an illustration.
Example
2-48
This example calls addframe to add frames to the AVI file object, aviobj.
addframe
fig=figure;
set(fig,'DoubleBuffer','on');
set(gca,'xlim',[-80 80],'ylim',[-80 80],...
'nextplot','replace','Visible','off')
aviobj = avifile('example.avi')
x = -pi:.1:pi;
radius = 0:length(x);
for i=1:length(x)
h = patch(sin(x)*radius(i),cos(x)*radius(i),...
[abs(cos(x(i))) 0 0]);
set(h,'EraseMode','xor');
frame = getframe(gca);
aviobj = addframe(aviobj,frame);
end
aviobj = close(aviobj);
See Also
avifile, close, movie2avi
2-49
addpath
Purpose
2addpath
Graphical
Interface
As an alternative to the addpath function, use the Set Path dialog box. To open
it, select Set Path from the File menu in the MATLAB desktop.
Syntax
addpath('directory')
addpath('dir','dir2','dir3' ...)
addpath('dir','dir2','dir3' ...'-flag')
addpath dir1 dir2 dir3 ... -flag
Description
addpath('directory') prepends the specified directory to the current
Add directories to MATLAB search path
MATLAB search path, that is, it adds them to the top of the path. Use the full
pathname for directory.
addpath('dir','dir2','dir3' ...) prepends all the specified directories to
the path. Use the full pathname for each dir.
addpath('dir','dir2','dir3' ...'-flag') either prepends or appends the
specified directories to the path depending on the value of flag.
flag Argument
Result
0 or begin
Prepend specified directories
1 or end
Append specified directories (add to bottom/end)
addpath dir1 dir2 dir3 ... -flag is the unquoted form of the syntax.
Examples
For the current path, viewed by typing path,
MATLABPATH
c:\matlab\toolbox\general
c:\matlab\toolbox\ops
c:\matlab\toolbox\strfun
you can add c:/matlab/mymfiles to the front of the path by typing
addpath('c:/matlab/mymfiles')
2-50
addpath
Verify that the files were added to the path by typing
path
and MATLAB returns
MATLABPATH
c:\matlab\mymfiles
c:\matlab\toolbox\general
c:\matlab\toolbox\ops
c:\matlab\toolbox\strfun
See Also
path, pathtool, genpath, rehash, rmpath
2-51
addproperty (COM)
Purpose
2addproperty (COM)
Add custom property to COM object
Syntax
addproperty(h, 'propertyname')
Arguments
h
Handle for a COM object previously returned from actxcontrol, actxserver,
get, or invoke.
propertyname
A string specifying the name of the custom property to add to the object or
interface.
Description
Add a custom property, propertyname, to the object or interface, h. You can
assign a value to that property using set.
Examples
Create an mwsamp control and add a new property named Position to it. Assign
an array value to the property:
f = figure('pos', [100 200 200 200]);
h = actxcontrol('mwsamp.mwsampctrl.2', [0 0 200 200], f);
get(h)
Label: 'Label'
Radius: 20
addproperty(h, 'Position');
set(h, 'Position', [200 120]);
get(h)
Label: 'Label'
Radius: 20
Position: [200 120]
get(h, 'Position')
ans =
200
120
See Also
2-52
deleteproperty, get, set, inspect
airy
Purpose
2airy
Airy functions
Syntax
W = airy(Z)
W = airy(k,Z)
[W,ierr] = airy(k,Z)
Definition
The Airy functions form a pair of linearly independent solutions to
2
d W
d Z2
– ZW = 0
The relationship between the Airy and modified Bessel functions is
1
Ai ( Z ) = --- Z ⁄ 3
π
Bi ( Z ) =
K 1 ⁄ 3(ζ)
Z ⁄ 3 [ I –1 ⁄ 3 ( ζ ) + I 1 ⁄ 3 ( ζ ) ]
where
2 3⁄2
ζ = --- Z
3
Description
W = airy(Z) returns the Airy function, Ai ( Z ) , for each element of the complex
array Z.
W = airy(k,Z) returns different results depending on the value of k.
k
Returns
0
The same result as airy(Z)
1
The derivative, Ai′ ( Z )
2
The Airy function of the second kind, Bi ( Z )
3
The derivative, Bi′ ( Z )
2-53
airy
[W,ierr] = airy(k,Z) also returns completion flags in an array the same size
as W.
ierr
Description
0
airy succesfully computed the Airy function for this element.
1
Illegal arguments
2
Overflow. Returns Inf
3
Some loss of accuracy in argument reduction
4
Unacceptable loss of accuracy, Z too large
5
No convergence. Returns NaN
See Also
besseli, besselj, besselk, bessely
References
[1] Amos, D. E., “A Subroutine Package for Bessel Functions of a Complex
Argument and Nonnegative Order,” Sandia National Laboratory Report,
SAND85-1018, May, 1985.
[2] Amos, D. E., “A Portable Package for Bessel Functions of a Complex
Argument and Nonnegative Order,” Trans. Math. Software, 1986.
2-54
alim
Purpose
2alim
Set or query the axes alpha limits
Syntax
alpha_limits = alim
alim([amin amax])
alim_mode = alim('mode')
alim('alim_mode')
alim(axes_handle,...)
Description
alpha_limits = alim returns the alpha limits (the axes ALim property) of the
current axes.
alim([amin amax]) sets the alpha limits to the specified values. amin is the
value of the data mapped to the first alpha value in the alphamap, and amax is
the value of the data mapped to the last alpha value in the alphamap. Data
values in between are linearly interpolated across the alphamap, while data
values outside are clamped to either the first or last alphamap value,
whichever is closest.
alim_mode = alim('mode') returns the alpha limits mode (the axes ALimMode
property) of the current axes.
alim('alim_mode') sets the alpha limits mode on the current axes. alim_mode
can be:
• auto – MATLAB automatically sets the alpha limits based on the alpha data
of the objects in the axes.
• manual – MATLAB does not change the alpha limits.
alim(axes_handle,...) operates on the specified axes.
See Also
alpha, alphamap, caxis
Axes ALim and ALimMode properties
Patch FaceVertexAlphaData property
Image and surface AlphaData properties
Transparency for related functions
Transparency in 3-D Visualization for examples
2-55
all
Purpose
2all
Test to determine if all elements are nonzero
Syntax
B = all(A)
B = all(A,dim)
Description
B = all(A) tests whether all the elements along various dimensions of an
array are nonzero or logical true (1).
If A is a vector, all(A) returns logical true (1) if all of the elements are nonzero,
and returns logical false (0) if one or more elements are zero.
If A is a matrix, all(A) treats the columns of A as vectors, returning a row
vector of 1s and 0s.
If A is a multidimensional array, all(A) treats the values along the first
non-singleton dimension as vectors, returning a logical condition for each
vector.
B = all(A,dim) tests along the dimension of A specified by scalar dim.
Examples
1 1 1
1 1 0
1 1 0
1
0
A
all(A,1)
all(A,2)
Given,
A = [0.53 0.67 0.01 0.38 0.07 0.42 0.69]
then B = (A < 0.5) returns logical true (1) only where A is less than one half:
0
0
1
1
1
1
0
The all function reduces such a vector of logical conditions to a single
condition. In this case, all(B) yields 0.
This makes all particularly useful in if statements,
if all(A < 0.5)
do something
end
2-56
all
where code is executed depending on a single condition, not a vector of possibly
conflicting conditions.
Applying the all function twice to a matrix, as in all(all(A)), always reduces
it to a scalar condition.
all(all(eye(3)))
ans =
0
See Also
any, logical operators, relational operators, colon
Other functions that collapse an array’s dimensions include:
max, mean, median, min, prod, std, sum, trapz
2-57
allchild
Purpose
2allchild
Find all children of specified objects
Syntax
child_handles = allchild(handle_list)
Description
child_handles = allchild(handle_list) returns the list of all children
(including ones with hidden handles) for each handle. If handle_list is a
single element, allchild returns the output in a vector. Otherwise, the output is
a cell array.
Examples
Compare the results returned by these two statements.
get(gca,'Children')
allchild(gca)
See Also
2-58
findall, findobj
alpha
Purpose
2alpha
Set transparency properties for objects in current axes
Syntax
alpha(face_alpha)
alpha(alpha_data)
alpha(alpha_data_mapping)
alpha(object_handle,...)
Description
alpha sets one of three transparency properties, depending on what arguments
you specify with the call to this function.
FaceAlpha
alpha(face_alpha) set the FaceAlpha property of all image, patch, and
surface objects in the current axes. You can set face_alpha to:
• a scalar – set the FaceAlpha property to the specified value (for images, set
the AlphaData property to the specified value)
• 'flat' – set the FaceAlpha property to flat
• 'interp' – set the FaceAlpha property to interp
• 'texture' – set the FaceAlpha property to texture
• 'opaque' – set the FaceAlpha property to 1
• 'clear' – set the FaceAlpha property to 0
See Specifying a Single Transparency Value for more information.
AlphaData (Surface Objects)
alpha(alpha_data) sets the AlphaData property of all surface objects in the
current axes. You can set alpha_data to:
• a matrix the same size as CData – sets the AlphaData property to the
specified values
• 'x' – set the AlphaData property to be the same as XData
• 'y' – set the AlphaData property to be the same as YData
• 'z' – set the AlphaData property to be the same as ZData
• 'color' – set the AlphaData property to be the same as CData
2-59
alpha
• 'rand' – set the AlphaData property to a matrix of random values equal in
size to CData
AlphaData (Image Objects)
alpha(alpha_data) sets the AlphaData property of all image objects in the
current axes. You can set alpha_data to:
• a matrix the same size as CData – sets the AlphaData property to the
specified value
• 'x' – ignored
• 'y' – ignored
• 'z' – ignored
• 'color' – set the AlphaData property to be the same as CData
• 'rand' – set the AlphaData property to a matrix of random values equal in
size to CData
FaceVertexAlphaData (Patch Objects)
alpha(alpha_data) sets the FaceVertexAlphaData property of all patch
objects in the current axes. You can set alpha_data to:
• a matrix the same size as FaceVertexCData – sets the FaceVertexAlphaData
property to the specified value
• 'x' – set the FaceVertexAlphaData property to be the same as
Vertices(:,1)
• 'y' – set the FaceVertexAlphaData property to be the same as
Vertices(:,2)
• 'z' – set the FaceVertexAlphaData property to be the same as
Vertices(:,3)
• 'color' – set the FaceVertexAlphaData property to be the same as
FaceVertexCData
• 'rand' – set the FaceVertexAlphaData property to random values
See Mapping Data to Transparency for more information.
2-60
alpha
AlphaDataMapping
alpha(alpha_data_mapping) sets the AlphaDataMapping property of all
image, patch, and surface objects in the current axes. You can set
alpha_data_mapping to:
• 'scaled' – set the AlphaDataMapping property to scaled
• 'direct' – set the AlphaDataMapping property to direct
• 'none' – set the AlphaDataMapping property to none
alpha(object_handle,value) set the transparency property only on the
object identified by object_handle
See Also
alim, alphamap
Image: AlphaData, AlphaDataMapping
Patch: FaceAlpha, FaceVertexAlphaData, AlphaDataMapping
Surface: FaceAlpha, AlphaData, AlphaDataMapping
Transparency for related functions
Transparency in 3-D Visualization for examples
2-61
alphamap
Purpose
2alphamap
Specify the figure alphamap (transparency)
Syntax
alphamap(alpha_map)
alphamap('parameter')
alphamap('parameter',length)
alphamap('parameter’,delta)
alphamap(figure_handle,...)
alpha_map = alphamap
alpha_map = alphamap(figure_handle)
alpha_map = alphamap(’parameter’)
Description
alphamap enables you to set or modify a figure’s Alphamap property. Unless you
specify a figure handle as the first argument, alphamap operates on the current
figure.
alphamap(alpha_map) set the AlphaMap of the current figure to the specified
m-by-1 array of alpha values.
alphamap('parameter') create a new or modify the current alphamap. You
can specify the following parameters:
• default – set the AlphaMap property to the figure’s default alphamap
• rampup – create a linear alphamap with increasing opacity (default length
equals the current alphamap length)
• rampdown – create a linear alphamap with decreasing opacity (default length
equals the current alphamap length)
• vup – create an alphamap that is opaque in the center and becomes more
transparent linearly towards the beginning and end (default length equals
the current alphamap length)
• vdown – create an alphamap that is transparent in the center and becomes
more opaque linearly towards the beginning and end (default length equals
the current alphamap length)
• increase – modify the alphamap making it more opaque (default delta is .1,
which is added to the current values)
• decrease – modify the alphamap making it more transparent (default delta
is .1, which is subtracted from the current values)
2-62
alphamap
• spin – rotate the current alphamap (default delta is 1; note that delta must
be an integer)
alphamap('parameter',length) creates a new alphamap with the length
specified by length (used with parameters: rampup, rampdown, vup, vdown)
alphamap('parameter',delta) modifies the existing alphamap using the
value specified by delta (used with parameters: increase, decrease, spin).
alphamap(figure_handle,...) performs the operation on the alphamap of the
figure identified by figure_handle.
alpha_map = alphamap return the current alphamap.
alpha_map = alphamap(figure_handle) returns the current alphamap from
the figure identified by figure_handle.
alpha_map = alphamap(’parameter’) retruns the alphamap modified by the
parameter, but does not set the AlphaMap property.
See Also
alim, alpha
Image: AlphaData, AlphaDataMapping
Patch: FaceAlpha, AlphaData, AlphaDataMapping
Surface: FaceAlpha, AlphaData, AlphaDataMapping
Transparency for related functions
Transparency in 3-D Visualization for examples
2-63
angle
Purpose
2angle
Phase angle
Syntax
P = angle(Z)
Description
P = angle(Z) returns the phase angles, in radians, for each element of
complex array Z. The angles lie between ± π .
For complex Z, the magnitude R and phase angle theta are given by
R = abs(Z)
theta = angle(Z)
and the statement
Z = R.*exp(i*theta)
converts back to the original complex Z.
Examples
Z = [ 1
1
1
1
+
+
1i
2i
3i
4i
2
2
2
2
+
+
-
1i
2i
3i
4i
3
3
3
3
+
+
1i
2i
3i
4i
4
4
4
4
+
+
-
1i
2i
3i
4i ]
P = angle(Z)
P =
-0.7854
1.1071
-1.2490
1.3258
0.4636
-0.7854
0.9828
-1.1071
-0.3218
0.5880
-0.7854
0.9273
0.2450
-0.4636
0.6435
-0.7854
Algorithm
The angle function can be expressed as angle(z) = imag(log(z)) =
atan2(imag(z),real(z)).
See Also
abs, atan2, unwrap
2-64
ans
Purpose
2ans
The most recent answer
Syntax
ans
Description
MATLAB creates the ans variable automatically when you specify no output
argument.
Examples
The statement
2+2
is the same as
ans = 2+2
See Also
display
2-65
any
Purpose
2any
Test for any nonzeros
Syntax
B = any(A)
B = any(A,dim)
Description
B = any(A) tests whether any of the elements along various dimensions of an
array are nonzero or logical true (1).
If A is a vector, any(A) returns logical true (1) if any of the elements of A are
nonzero, and returns logical false (0) if all the elements are zero.
If A is a matrix, any(A) treats the columns of A as vectors, returning a row
vector of 1s and 0s.
If A is a multidimensional array, any(A) treats the values along the first
non-singleton dimension as vectors, returning a logical condition for each
vector.
B = any(A,dim) tests along the dimension of A specified by scalar dim.
Examples
1 0 1
0 0 0
1 0 1
1
0
A
any(A,1)
any(A,2)
Given,
A = [0.53 0.67 0.01 0.38 0.07 0.42 0.69]
then B = (A < 0.5) returns logical true (1) only where A is less than one half:
0
0
1
1
1
1
0
The any function reduces such a vector of logical conditions to a single
condition. In this case, any(B) yields 1.
This makes any particularly useful in if statements,
if any(A < 0.5)
do something
end
2-66
any
where code is executed depending on a single condition, not a vector of possibly
conflicting conditions.
Applying the any function twice to a matrix, as in any(any(A)), always reduces
it to a scalar condition.
any(any(eye(3)))
ans =
1
See Also
all, logical operators, relational operators, colon
Other functions that collapse an array’s dimensions include:
max, mean, median, min, prod, std, sum, trapz
2-67
area
Purpose
2area
Area fill of a two-dimensional plot
Syntax
area(Y)
area(X,Y)
area(...,ymin)
area(...,'PropertyName',PropertyValue,...)
h = area(...)
Description
An area plot displays elements in Y as one or more curves and fills the area
beneath each curve. When Y is a matrix, the curves are stacked showing the
relative contribution of each row element to the total height of the curve at each
x interval.
area(Y) plots the vector Y or the sum of each column in matrix Y. The x-axis
automatically scales depending on length(Y) when Y is a vector and on
size(Y,1)when Y is a matrix.
area(X,Y) plots Y at the corresponding values of X. If X is a vector, length(X)
must equal length(Y) and X must be monotonic. If X is a matrix, size(X) must
equal size(Y) and each column in X must be monotonic. To make a vector or
matrix monotonic, use sort.
area(...,ymin) specifies the lower limit in the y direction for the area fill. The
default ymin is 0.
area(...,'PropertyName',PropertyValue,...) specifies property name and
property value pairs for the patch graphics object created by area.
h = area(...) returns handles of patch graphics objects. area creates one
patch object per column in Y.
Remarks
area creates one curve from all elements in a vector or one curve per column in
a matrix. The colors of the curves are selected from equally spaced intervals
throughout the entire range of the colormap.
Examples
Plot the values in Y as a stacked area plot.
Y = [
2-68
1, 5, 3;
3, 2, 7;
area
1, 5, 3;
2, 6, 1];
area(Y)
grid on
colormap summer
set(gca,'Layer','top')
title 'Stacked Area Plot'
Stacked Area Plot
12
10
8
6
4
2
0
1
See Also
1.5
2
2.5
3
3.5
4
plot
“Area, Bar, and Pie Plots” for related functions
Area Graphs for more examples
2-69
asec
Purpose
2asec
Inverse secant
Syntax
Y = asec(X)
Description
Y = asec(X) returns the inverse secant (arcsecant) for each element of X.
The asec function operates element-wise on arrays. The function’s domains
and ranges include complex values. All angles are in radians.
Examples
Graph the inverse secant over the domains 1 ≤ x ≤ 5 and – 5 ≤ x ≤ – 1 .
x1 = -5:0.01:-1;
x2 = 1:0.01:5;
plot(x1,asec(x1),x2,asec(x2)), grid on
3.5
3
2.5
2
1.5
1
0.5
0
−5
Definition
0
5
The inverse secant can be defined as
1
sec– 1 ( z ) = cos– 1  --- 
 z
Algorithm
asec uses FDLIBM, which was developed at SunSoft, a Sun Microsystems, Inc.
business, by Kwok C. Ng, and others. For information about FDLIBM, see
http://www.netlib.org.
2-70
asec
See Also
asech, sec
2-71
asech
Purpose
2asech
Inverse hyperbolic secant
Syntax
Y = asech(X)
Description
Y = asech(X) returns the inverse hyperbolic secant for each element of X.
The asech function operates element-wise on arrays. The function’s domains
and ranges include complex values. All angles are in radians.
Examples
Graph the inverse hyperbolic secant over the domain 0.01 ≤ x ≤ 1 .
x = 0.01:0.001:1;
plot(x,asech(x)), grid on
6
5
4
3
2
1
0
0
Definition
0.2
0.4
0.6
0.8
1
The hyperbolic inverse secant can be defined as
1
sech– 1 ( z ) = cosh– 1  --- 
 z
Algorithm
asech uses FDLIBM, which was developed at SunSoft, a Sun Microsystems,
Inc. business, by Kwok C. Ng, and others. For information about FDLIBM, see
http://www.netlib.org.
2-72
asech
See Also
asec, sech
2-73
asin
Purpose
2asin
Inverse sine
Syntax
Y = asin(X)
Description
Y = asin(X) returns the inverse sine (arcsine) for each element of X. For real
elements of X in the domain [ – 1, 1 ] , asin(X) is in the range [ – π ⁄ 2, π ⁄ 2 ] . For
real elements of x outside the range [ – 1, 1 ] , asin(X) is complex.
The asin function operates element-wise on arrays. The function’s domains
and ranges include complex values. All angles are in radians.
Examples
Graph the inverse sine function over the domain – 1 ≤ x ≤ 1 .
x = -1:.01:1;
plot(x,asin(x)), grid on
2
1.5
1
0.5
0
−0.5
−1
−1.5
−2
−1
Definition
0
0.5
The inverse sine can be defined as
–1
sin ( z)
2-74
−0.5
1
--2 2
= – i log iz + ( 1 – z )
1
asin
Algorithm
asin uses FDLIBM, which was developed at SunSoft, a Sun Microsystems, Inc.
business, by Kwok C. Ng, and others. For information about FDLIBM, see
http://www.netlib.org.
See Also
sin, asinh
2-75
asinh
Purpose
2asinh
Inverse hyperbolic sine
Syntax
Y = asinh(X)
Description
Y = asinh(X) returns the inverse hyperbolic sine for each element of X.
The asinh function operates element-wise on arrays. The function’s domains
and ranges include complex values. All angles are in radians.
Examples
Graph the inverse hyperbolic sine function over the domain – 5 ≤ x ≤ 5 .
x = -5:.01:5;
plot(x,asinh(x)), grid on
2.5
2
1.5
1
0.5
0
−0.5
−1
−1.5
−2
−2.5
−5
Definition
0
The hyperbolic inverse sine can be defined as
–1
2
sinh ( z ) = log z + ( z + 1 )
2-76
5
1
--2
asinh
Algorithm
asinh uses FDLIBM, which was developed at SunSoft, a Sun Microsystems,
Inc. business, by Kwok C. Ng, and others. For information about FDLIBM, see
http://www.netlib.org.
See Also
asin, sinh
2-77
assignin
Purpose
2assignin
Assign a value to a workspace variable
Syntax
assignin(ws,'var',val)
Description
assignin(ws,'var',val) assigns the value val to the variable var in the
workspace ws. var is created if it doesn’t exist. ws can have a value of 'base' or
'caller' to denote the MATLAB base workspace or the workspace of the caller
function.
The assignin function is particularly useful for these tasks:
• Exporting data from a function to the MATLAB workspace
• Within a function, changing the value of a variable that is defined in the
workspace of the caller function (such as a variable in the function argument
list)
Remarks
The MATLAB base workspace is the workspace that is seen from the MATLAB
command line (when not in the debugger). The caller workspace is the
workspace of the function that called the M-file. Note the base and caller
workspaces are equivalent in the context of an M-file that is invoked from the
MATLAB command line.
Examples
This example creates a dialog box for the image display function, prompting a
user for an image name and a colormap name. The assignin function is used
to export the user–entered values to the MATLAB workspace variables imfile
and cmap.
prompt = {'Enter image name:','Enter colormap name:'};
title = 'Image display - assignin example';
lines = 1;
def = {'my_image','hsv'};
answer = inputdlg(prompt,title,lines,def);
assignin('base','imfile',answer{1});
assignin('base','cmap',answer{2});
2-78
assignin
See Also
evalin
2-79
atan
Purpose
2atan
Inverse tangent
Syntax
Y = atan(X)
Description
Y = atan(X) returns the inverse tangent (arctangent) for each element of X.
For real elements of X, atan(X) is in the range [ – π ⁄ 2, π ⁄ 2 ] .
The atan function operates element-wise on arrays. The function’s domains
and ranges include complex values. All angles are in radians.
Examples
Graph the inverse tangent function over the domain – 20 ≤ x ≤ 20 .
x = -20:0.01:20;
plot(x,atan(x)), grid on
2
1.5
1
0.5
0
−0.5
−1
−1.5
−2
−20
Definition
−15
−10
−5
0
5
10
15
20
The inverse tangent can be defined as
i
i+z
tan– 1 ( z ) = ---- log  ----------- 
i– z
2
Algorithm
atan uses FDLIBM, which was developed at SunSoft, a Sun Microsystems, Inc.
business, by Kwok C. Ng, and others. For information about FDLIBM, see
http://www.netlib.org.
2-80
atan
See Also
atan2, tan, atanh
2-81
atan2
Purpose
2atan2
Four-quadrant inverse tangent
Syntax
P = atan2(Y,X)
Description
P = atan2(Y,X) returns an array P the same size as X and Y containing the
element-by-element, four-quadrant inverse tangent (arctangent) of the real
parts of Y and X. Any imaginary parts are ignored.
Elements of P lie in the closed interval [-pi,pi], where pi is the MATLAB
floating-point representation of π . atan uses sign(Y) and sign(X) to
determine the specific quadrant.
y
π/2
π
–π
0
x
–π/2
atan2(Y,X) contrasts with atan(Y/X), whose results are limited to the interval
[ – π ⁄ 2, π ⁄ 2 ] , or the right side of this diagram.
Examples
Any complex number z = x + iy is converted to polar coordinates with
r = abs(z)
theta = atan2(imag(z),real(z))
For example,
z = 4 + 3i;
r = abs(z)
theta = atan2(imag(z),real(z))
r =
5
2-82
atan2
theta =
0.6435
This is a common operation, so MATLAB provides a function, angle(z), that
computes theta = atan2(imag(z),real(z)).
To convert back to the original complex number
z = r *exp(i *theta)
z =
4.0000 + 3.0000i
Algorithm
atan2 uses FDLIBM, which was developed at SunSoft, a Sun Microsystems,
Inc. business, by Kwok C. Ng, and others. For information about FDLIBM, see
http://www.netlib.org.
See Also
angle, atan, atanh
2-83
atanh
Purpose
2atanh
Inverse hyperbolic tangent
Syntax
Y = atanh(X)
Description
The atanh function operates element-wise on arrays. The function’s domains
and ranges include complex values. All angles are in radians.
Y = atanh(X) returns the inverse hyperbolic tangent for each element of X.
Examples
Graph the inverse hyperbolic tangent function over the domain – 1 < x < 1 .
x = -0.99:0.01:0.99;
plot(x,atanh(x)), grid on
3
2
1
0
−1
−2
−3
−1
Definition
−0.5
0
0.5
1
The hyperbolic inverse tangent can be defined as
1+z
1
tanh– 1 ( z ) = --- log  ------------ 
1– z
2
Algorithm
atanh uses FDLIBM, which was developed at SunSoft, a Sun Microsystems,
Inc. business, by Kwok C. Ng, and others. For information about FDLIBM, see
http://www.netlib.org.
2-84
atanh
See Also
atan2, atan, tanh
2-85
audiodevinfo
Purpose
2audiodevinfo
Obtain information on installed audio devices
Syntax
d = audiodevinfo
audiodevinfo(io)
audiodevinfo(io,ID)
audiodevinfo(io,ID,'DriverVersion')
audiodevinfo(io,name)
audiodevinfo(io,rate,bits,chans)
audiodevinfo(io,ID,rate,bits,chans)
Description
Note This function is for use only with 32-bit, Windows-based machines.
d = audiodevinfo returns a structure, d with an input field and an output
field. Each field is an array of structures that contains information about the
system’s audio input and output devices. Each array contains these fields: a
string with the name of the device, a string with the version of the installed
driver (DriverVersion), and the device’s numeric ID.
audiodevinfo(io) returns the number of input (io=1) or output (io=0) audio
devices on the system.
audiodevinfo(io,ID) returns the name of the audio device specified by its ID.
audiodevinfo(io,ID,'DriverVersion') returns a string containing the
driver version of the specified audio device.
audiodevinfo(io,name) returns the device ID specified by name. You can enter
a partial name, but the case must match. If no device with the specified name is
found, -1 is returned.
audiodevinfo(io,rate,bits,chans) returns the device ID of the first audio
device that supports the specified sample rate, number of bits, and number of
channels, chans. If no matching device is found, -1 is returned.
audiodevinfo(io,ID,rate,bits,chans) returns 1 if the device, specified by
its ID, supports the specified sample rate, number of bits, and number of
channels, chans. If the device does not support the specified parameters, 0 is
returned.
2-86
audiodevinfo
See Also
audioplayer, audiorecorder
2-87
audioplayer
Purpose
2audioplayer
Create an audio player object
Syntax
y
y
y
y
Description
Note audioplayer is available only on Windows-based machines. On 32-bit,
Windows-based machines with an installed 24-bit audio device, audioplayer
supports 24-bit playback.
=
=
=
=
audioplayer(x,Fs)
audioplayer(x,Fs,nbits)
audioplayer(r)
audioplayer(r,id)
To use all of the audioplayer features, your system needs a properly installed
and configured sound card with 8- and 16-bit I/O, two channels, and support
for sampling rates of up to 48 kHz.
y = audioplayer(x,Fs) returns a handle to an audio player object y using
input audio signal x. The input signal x can be a vector or two-dimensional
array containing single, double, int8, uint8, or int16 MATLAB data types.
The input sample values for single and double data must be between -1 and
1. For int8, uint8, and int16 data, the ranges of sample values are -128 to 127,
0 to 255, and -32768 to 32767, respectively.
Fs is the sampling rate in Hz to use for playback. Valid values for Fs depend on
the specific audio hardware installed. Typical values supported by most sound
cards are 8000, 11025, 22050, and 44100 Hz.
y = audioplayer(x,Fs,nbits) returns a handle to an audio player object
where nbits is the bit quantization to use for single or double data types. This
is an optional parameter with a default value of 16. Valid values for nbits are
8 and 16 (and 24, if a 24-bit device is installed). You do not need to specify nbits
for int8, uint8 or int16 data because the quantization is set automatically to
8 or 16, respectively.
y = audioplayer(r) returns a handle to an audio player object from an
audiorecorder object r.
y = audioplayer(r,id) returns a handle to an audio player object from an
audiorecorder object r, using the specified audio device id for output.
2-88
audioplayer
After you create an audio player object, you can use the methods listed below
on that object. y represents the name of the returned audio player.
Method
Description
play(y)
play(y,start)
play(y,[start stop])
play(y,range)
Starts playback from the beginning
and plays to the end, or from start
sample to the end, or from start
sample to stop sample. The values of
start and stop can be specified in a
two-element vector range.
playblocking(y)
playblocking(y,start)
playblocking(y,[start stop])
playblocking(y,range)
Same as play, but does not return
control until playback completes.
stop(y)
Stops playback.
pause(y)
Pauses playback.
resume(y)
Restarts playback from where
playback was paused.
isplaying(y)
Indicates whether playback is in
progress. If 0, playback is not in
progress. If 1, playback is in progress.
display(y)
disp(y)
get(y)
Displays all property information
about audio player y.
Audio player objects have the properties listed below. To set a user-settable
property use this syntax:
set(y, 'property1', value,'property2',value,...)
To view a read-only property
get(y,’property’)
% Displays ‘property’ setting.
2-89
audioplayer
Property
Description
Type
Type
Name of the object’s class
read-only
SampleRate
Sampling frequency in Hz
user-settable
BitsPerSample
Number of bits per sample
read-only
NumberOfChannels
Number of channels
read-only
TotalSamples
Total length, in samples, of the
audio data
read-only
Running
Status of the audio player ('on' or
'off')
read-only
CurrentSample
Current sample being played by
the audio output device (If it is
not playing, currentsample is
the next sample to be played with
play or resume.)
read-only
UserData
User data of any type
user-settable
Tag
User-specified object label string
user-settable
For information on using the following four properties, see Creating Timer
Callback Functions in the MATLAB documentation. Note that for audio
object callbacks, eventStruct (event) is currently empty ([]).
2-90
TimerFcn
Name of, or handle to,
user-specified function to be
called during playback
user-settable
TimerPeriod
Time, in seconds, between
TimerFcn callbacks
user-settable
audioplayer
Example
Property
Description
Type
StartFcn
Name of, or handle to, the
function to be called once when
playback starts
user-settable
StopFcn
Name of or handle to the function
to be called once when playback
stops
user-settable
Load a sample audio file, create an audio player object, and play the audio at a
higher sampling rate. x contains the audio samples and Fs is the sampling rate.
You can use any of the audioplayer functions listed above on the player.
load handel;
player=audioplayer(y,Fs);
play(player,[1 (get(player,'SampleRate')*3)]);
To stop the playback, use this command:
stop(player);
See Also
% Equivalent to player.stop
audiorecorder, sound, wavplay, wavwrite, wavread, get, set, methods
2-91
audiorecorder
Purpose
2audiorecorder
Create an audio recorder object
Syntax
y = audiorecorder
y = audiorecorder(Fs,nbits,channels)
y = audiorecorder(Fs,nbits,channels,id)
Description
Note To use all of the audio recorder object features, your system must have
a properly installed and configured sound card with 8- and 16-bit I/O and
support for sampling rates of up to 48 kHz.
On 32-bit, Windows-based machines with an installed 24-bit audio device,
audiorecorder supports 24-bit recording.
y = audiorecorder returns a handle to an 8-kHz, 8-bit, mono audio recorder
object.
y = audiorecorder(Fs,nbits,channels) returns a handle to an audio
recorder object using the sampling rate, Fs ( in Hz), the sample size of nbits,
and the number of channels. Fs can be any sampling rate supported by the
audio hardware. Common sampling rates are 8000, 11025, 22050, and 44000.
The value of nbits must be 8 or 16 (or 24, if a 24-bit device is installed). For
mono or stereo, channels must be 1 or 2, respectively.
y = audiorecorder(Fs,nbits,channels,id) returns a handle to an audio
recorder object using the audio device specified by its id for input.
After you create an audio recorder object, you can use the methods listed below
on that object. y represents the name of the returned audio recorder.
2-92
Method
Description
record(y)
record(y,length)
Starts recording.
Records for length number of seconds.
recordblocking(y,length)
Same as record, but does not return
control until recording completes.
stop(y)
Stops recording.
audiorecorder
Method
Description
pause(y)
Pauses recording.
resume(y)
Restarts recording from where
recording was paused.
isrecording(y)
Indicates the status of recording. If 0,
recording is not in progress. If 1,
recording is in progress.
play(y)
Creates an audioplayer, plays the
recorded audio data, and returns a
handle to the created audioplayer.
getplayer(y)
Creates an audioplayer and returns a
handle to the created audioplayer.
getaudiodata(y)
getaudiodata(y,'type')
Returns the recorded audio data to the
MATLAB workspace. type is a string
containing the desired data type.
Supported data types are double,
single, int16, int8, or uint8. If type
is omitted, it defaults to 'double'.
For double and single, the array
contains values between -1 and 1. For
int8, values are between -128 to 127.
For uint8, values are from 0 to 255.
For int16, values are from -32768 to
32767. If the recording is in mono, the
returned array has one column. If it is
in stereo, the array has two columns—
one for each channel.
display(y)
disp(y)
get(y)
Displays all property information
about audio recorder y.
2-93
audiorecorder
Audio recorder objects have the properties listed below. To set a user-settable
property use this syntax:
set(y, 'property1', value,'property2',value,...)
To view a read-only property
get(y,’property’)
2-94
%displays ‘property’ setting.
Property
Description
Type
Type
Name of the object’s class
read-only
SampleRate
Sampling frequency in Hz
read-only
BitsPerSample
Number of bits per recorded
sample
read-only
NumberOfChannels
Number of channels of recorded
audio
read-only
TotalSamples
Total length, in samples, of the
recording
read-only
Running
Status of the audio recorder ('on'
or 'off')
read-only
CurrentSample
Current sample being recorded
by the audio output device (If it is
not recording, currentsample is
the next sample to be recorded
with record or resume.)
read-only
UserData
User data of any type
user-settable
audiorecorder
Property
Description
Type
For information on using the following four properties, see Creating Timer
Callback Functions in the MATLAB documentation. Note that for audio
object callbacks, eventStruct (event) is currently empty ([]).
Examples
TimerFcn
Name of or handle to
user-specified function to be
called during recording
user-settable
TimerPeriod
Time, in seconds, between
TimerFcn callbacks
user-settable
StartFcn
Name of or handle to the function
to be called a single time when
recording starts
user-settable
StopFcn
Name of or handle to the function
to be called a single time when
recording stops
user-settable
NumberOfBuffers
Number of buffers used for
recording (You should adjust this
only if you have skips, dropouts,
etc. in your recording.)
user-settable
BufferLength
Length in seconds of buffer (You
should adjust this only if you
have skips, dropouts, etc. in your
recording.)
user-settable
Tag
User-specified object label string
user-settable
Example 1
Using a microphone, record 3.5 seconds of 44.1-kHz, 16-bit, stereo data, and
then return the data to the MATLAB workspace as a double array.
recorder = audiorecorder(44100,16,2);
recordblocking(recorder,3.5);
audioarray = getaudiodata(recorder);
2-95
audiorecorder
Example 2
Using a microphone, record 8-bit, 22-kHz mono data, play it back, record again
and return the data to the MATLAB workspace as a uint8 array.
micrecorder = audiorecorder(22050,8,1);
record(micrecorder);
% Now, speak into microphone
stop(micrecorder);
speechplayer = play(micrecorder);
% Now, listen to the recording
stop(speechplayer);
speechdata = getaudiodata(micrecorder, 'uint8');
Remarks
The current implementation of AudioRecorder is not intended for long, high
sample rate recording because it uses system memory for storage and does not
use disk buffering. When large recordings are attempted, MATLAB
performance may degrade.
See Also
audioplayer, wavread, wavrecord, wavwrite, get, set, methods
2-96
auread
Purpose
2auread
Graphical
Interface
As an alternative to auread, use the Import Wizard. To activate the Import
Wizard, select Import data from the File menu.
Syntax
y = auread('aufile')
[y,Fs,bits] = auread('aufile')
[...] = auread('aufile',N)
[...] = auread('aufile',[N1,N2])
siz = auread('aufile','size')
Description
y = auread('aufile') loads a sound file specified by the string aufile,
returning the sampled data in y. The .au extension is appended if no extension
is given. Amplitude values are in the range [–1,+1]. auread supports
Read NeXT/SUN (.au) sound file
multi-channel data in the following formats:
• 8-bit mu-law
• 8-, 16-, and 32-bit linear
• floating-point
[y,Fs,bits] = auread('aufile') returns the sample rate (Fs) in Hertz and
the number of bits per sample (bits) used to encode the data in the file.
[...] = auread('aufile',N) returns only the first N samples from each
channel in the file.
[...] = auread('aufile',[N1 N2]) returns only samples N1 through N2
from each channel in the file.
siz = auread('aufile','size') returns the size of the audio data contained
in the file in place of the actual audio data, returning the vector siz =
[samples channels].
See Also
auwrite, wavread
2-97
auwrite
Purpose
2auwrite
Write NeXT/SUN (.au) sound file
Syntax
auwrite(y,'aufile')
auwrite(y,Fs,'aufile')
auwrite(y,Fs,N,'aufile')
auwrite(y,Fs,N,'method','aufile')
Description
auwrite(y,'aufile') writes a sound file specified by the string aufile. The
data should be arranged with one channel per column. Amplitude values
outside the range [–1,+1] are clipped prior to writing. auwrite supports
multi-channel data for 8-bit mu-law, and 8- and 16-bit linear formats.
auwrite(y,Fs,'aufile') specifies the sample rate of the data in Hertz.
auwrite(y,Fs,N,'aufile') selects the number of bits in the encoder.
Allowable settings are N = 8 and N = 16.
auwrite(y,Fs,N,'method','aufile') allows selection of the encoding
method, which can be either mu or linear. Note that mu-law files must be 8-bit.
By default, method = 'mu'.
See Also
2-98
auread, wavwrite
avifile
Purpose
2avifile
Create a new Audio Video Interleaved (AVI) file
Syntax
aviobj = avifile(filename)
aviobj =
avifile(filename,'PropertyName',value,'PropertyName',value,...)
Description
aviobj = avifile(filename) creates an AVI file, giving it the name specified
in filename, using default values for all AVI file object properties. If filename
does not include an extension, avifile appends .avi to the filename. AVI is a
file format for storing audio and video data.
avifile returns a handle to an AVI file object, aviobj. You use this object to
refer to the AVI file in other functions. An AVI file object supports properties
and methods that control aspects of the AVI file created.
creates
an AVI file with the specified parameter settings. This table lists available
parameters.
aviobj = avifile(filename,'Param',Value,'Param',Value,...)
Parameter
Value
Default
'colormap'
An m-by-3 matrix defining the colormap
to be used for indexed AVI movies,
where m must be no greater than 256
(236 if using Indeo compression). You
must set this parameter before calling
addframe, unless you are using
addframe with the MATLAB movie
syntax.
There is no
default
colormap.
'compression'
A text string specifying which
compression codec to use.
On Windows:
'Indeo3'
'Indeo5'
'Cinepak'
'MSVC'
'None'
On Unix:
'None'
'Indeo3',
on
Windows.
'None' on
Unix.
2-99
avifile
Parameter
Value
Default
To use a custom compression codec,
specify the four-character code that
identifies the codec (typically included
in the codec documentation). The
addframe function reports an error if it
can not find the specified custom
compressor.
'fps'
A scalar value specifying the speed of
the AVI movie in frames per second
(fps).
15 fps
'keyframe'
For compressors that support temporal
compression, this is the number of key
frames per second.
2 key
frames per
second.
'name'
A descriptive name for the video
stream. This parameter must be no
greater than 64 characters long.
The default
is the
filename.
'quality'
A number between 0 and 100. This
parameter has no effect on
uncompressed movies. Higher quality
numbers result in higher video quality
and larger file sizes. Lower quality
numbers result in lower video quality
and smaller file sizes.
75
You can also use structure syntax to set AVI file object properties. For
example, to set the quality property to 100 use the following syntax:
aviobj = avifile(filename);
aviobj.Quality = 100;
Example
This example shows how to use the avifile function to create the AVI file
example.avi.
fig=figure;
set(fig,'DoubleBuffer','on');
2-100
avifile
set(gca,'xlim',[-80 80],'ylim',[-80 80],...
'NextPlot','replace','Visible','off')
mov = avifile('example.avi')
x = -pi:.1:pi;
radius = 0:length(x);
for k=1:length(x)
h = patch(sin(x)*radius(k),cos(x)*radius(k),...
[abs(cos(x(k))) 0 0]);
set(h,'EraseMode','xor');
F = getframe(gca);
mov = addframe(mov,F);
end
mov = close(mov);
See Also
addframe, close, movie2avi
2-101
aviinfo
Purpose
2aviinfo
Return information about an Audio Video Interleaved (AVI) file
Syntax
fileinfo = aviinfo(filename)
Description
fileinfo = aviinfo(filename) returns a structure whose fields contain
information about the AVI file specified in the string, filename. If filename
does not include an extension, then .avi is used. The file must be in the current
working directory or in a directory on the MATLAB path.
The set of fields in the fileinfo structure are shown below.
2-102
Field Name
Description
AudioFormat
A string containing the name of the format used
to store the audio data, if audio data is present
AudioRate
An integer indicating the sample rate in Hertz of
the audio stream, if audio data is present
Filename
A string specifying the name of the file
FileModDate
A string containing the modification date of the
file
FileSize
An integer indicating the size of the file in bytes
FramesPerSecond
An integer indicating the desired frames per
second
Height
An integer indicating the height of the AVI movie
in pixels
ImageType
A string indicating the type of image. Either
'truecolor' for a truecolor (RGB) image, or
'indexed' for an indexed image.
NumAudioChannels
An integer indicating the number of channels in
the audio stream, if audio data is present
NumFrames
An integer indicating the total number of frames
in the movie
aviinfo
See also
Field Name
Description
NumColormapEntries
An integer specifying the number of colormap
entries
Quality
A number between 0 and 100 indicating the video
quality in the AVI file. Higher quality numbers
indicate higher video quality; lower quality
numbers indicate lower video quality. This value
is not always set in AVI files and therefore may be
inaccurate.
VideoCompression
A string containing the compressor used to
compress the AVI file. If the compressor is not
Microsoft Video 1, Run Length Encoding (RLE),
Cinepak, or Intel Indeo, aviinfo returns a
four-character code.
Width
An integer indicating the width of the AVI movie
in pixels
avifile, aviread
2-103
aviread
Purpose
2aviread
Read an Audio Video Interleaved (AVI) file.
Syntax
mov = aviread(filename)
mov = aviread(filename,index)
Description
mov = aviread(filename) reads the AVI movie filename into the MATLAB
movie structure mov. If filename does not include an extension, then .avi is
used. Use the movie function to view the movie, mov. On UNIX, filename must
be an uncompressed AVI file.
mov has two fields, cdata and colormap. The content of these fields varies
depending on the type of image.
Image Type
mov.cdata Field
mov.colormap Field
Truecolor
height-by-width-by-3
array
Empty
Indexed
height-by-width array
m-by-3 array
mov = aviread(filename,index) reads only the frame(s) specified by index.
index can be a single index or an array of indices into the video stream. In AVI
files, the first frame has the index value 1, the second frame has the index
value 2, and so on.
See also
2-104
aviinfo, avifile, movie
axes
Purpose
2axes
Create axes graphics object
Syntax
axes
axes('PropertyName',PropertyValue,...)
axes(h)
h = axes(...)
Description
axes is the low-level function for creating axes graphics objects.
axes creates an axes graphics object in the current figure using default
property values.
axes('PropertyName',PropertyValue,...) creates an axes object having the
specified property values. MATLAB uses default values for any properties that
you do not explicitly define as arguments.
axes(h) makes existing axes h the current axes. It also makes h the first axes
listed in the figure’s Children property and sets the figure’s CurrentAxes
property to h. The current axes is the target for functions that draw image, line,
patch, surface, and text graphics objects.
h = axes(...) returns the handle of the created axes object.
Remarks
MATLAB automatically creates an axes, if one does not already exist, when
you issue a command that draws image, light, line, patch, surface, or text
graphics objects.
The axes function accepts property name/property value pairs, structure
arrays, and cell arrays as input arguments (see the set and get commands for
examples of how to specify these data types). These properties, which control
various aspects of the axes object, are described in the “Axes Properties”
section.
Use the set function to modify the properties of an existing axes or the get
function to query the current values of axes properties. Use the gca command
to obtain the handle of the current axes.
The axis (not axes) function provides simplified access to commonly used
properties that control the scaling and appearance of axes.
2-105
axes
While the basic purpose of an axes object is to provide a coordinate system for
plotted data, axes properties provide considerable control over the way
MATLAB displays data.
Stretch-to-Fill
By default, MATLAB stretches the axes to fill the axes position rectangle (the
rectangle defined by the last two elements in the Position property). This
results in graphs that use the available space in the rectangle. However, some
3-D graphs (such as a sphere) appear distorted because of this stretching, and
are better viewed with a specific three-dimensional aspect ratio.
Stretch-to-fill is active when the DataAspectRatioMode,
PlotBoxAspectRatioMode, and CameraViewAngleMode are all auto (the
default). However, stretch-to-fill is turned off when the DataAspectRatio,
PlotBoxAspectRatio, or CameraViewAngle is user-specified, or when one or
more of the corresponding modes is set to manual (which happens
automatically when you set the corresponding property value).
This picture shows the same sphere displayed both with and without the
stretch-to-fill. The dotted lines show the axes Position rectangle.
1
1
8
0.8
6
0.6
4
0.4
2
0.2
0
0
2
−0.2
4
−0.4
6
−0.6
8
−0.8
1
−1
−0.8
−0.6
−0.4
−0.2
0
0.2
0.4
Stretch-to-fill active
0.6
0.8
1
−1
−1
−0.5
0
0.5
1
Stretch-to-fill disabled
When stretch-to-fill is disabled, MATLAB sets the size of the axes to be as large
as possible within the constraints imposed by the Position rectangle without
introducing distortion. In the picture above, the height of the rectangle
constrains the axes size.
2-106
axes
Examples
Zooming
Zoom in using aspect ratio and limits:
sphere
set(gca,'DataAspectRatio',[1 1 1],...
'PlotBoxAspectRatio',[1 1 1],'ZLim',[−0.6 0.6])
Zoom in and out using the CameraViewAngle:
sphere
set(gca,'CameraViewAngle',get(gca,'CameraViewAngle')−5)
set(gca,'CameraViewAngle',get(gca,'CameraViewAngle')+5)
Note that both examples disable the MATLAB stretch-to-fill behavior.
Positioning the Axes
The axes Position property enables you to define the location of the axes
within the figure window. For example,
h = axes('Position',position_rectangle)
creates an axes object at the specified position within the current figure and
returns a handle to it. Specify the location and size of the axes with a rectangle
defined by a four-element vector,
position_rectangle = [left, bottom, width, height];
The left and bottom elements of this vector define the distance from the
lower-left corner of the figure to the lower-left corner of the rectangle. The
width and height elements define the dimensions of the rectangle. You specify
these values in units determined by the Units property. By default, MATLAB
uses normalized units where (0,0) is the lower-left corner and (1.0,1.0) is the
upper-right corner of the figure window.
You can define multiple axes in a single figure window:
axes('position',[.1 .1
mesh(peaks(20));
axes('position',[.1 .7
pcolor([1:10;1:10]);
.8
.6])
.8
.2])
2-107
axes
In this example, the first plot occupies the bottom two-thirds of the figure, and
the second occupies the top third.
2
1.5
1
1
2
3
4
5
6
7
8
9
10
10
5
0
−5
−10
20
15
20
15
10
10
5
0
See Also
5
0
axis, cla, clf, figure, gca, grid, subplot, title, xlabel, ylabel, zlabel,
view
“Axes Operations” for related functions
Axes Properties for more examples
2-108
axes
Object
Hierarchy
Root
Figure
Axes
Uicontrol
Uimenu
Image
Light
Line
Uicontextmenu
Patch
Rectangle
Surface
Text
Setting Default Properties
You can set default axes properties on the figure and root levels:
set(0,'DefaultAxesPropertyName',PropertyValue,...)
set(gcf,'DefaultAxesPropertyName',PropertyValue,...)
where PropertyName is the name of the axes property and PropertyValue is
the value you are specifying. Use set and get to access axes properties.
Property List
Property Name
The following table lists all axes properties and provides a brief description of
each. The property name links take you an expanded description of the
properties.
Property Description
Property Value
Controlling Style and Appearance
Box
Toggle axes plot box on and off
Clipping
This property has no effect; axes are
always clipped to the figure window
GridLineStyle
Line style used to draw axes grid
lines
Values: on, off
Default: off
Values: −, −−, :, -., none
Default: : (dotted line)
2-109
axes
Property Name
Property Description
Property Value
MinorGridLineStyle
Line style used to draw axes minor
grid lines
Values: −, −−, :, -., none
Default: : (dotted line)
Layer
Draw axes above or below graphs
Values: bottom, top
Default: bottom
LineStyleOrder
Sequence of line styles used for
multiline plots
Values: LineSpec
Default: − (solid line for)
LineWidth
Width of axis lines, in points (1/72"
per point)
Values: number of points
Default: 0.5 points
SelectionHighlight
Highlight axes when selected
(Selected property set to on)
Values: on, off Default: on
TickDir
Direction of axis tick marks
Values: in, out
Default: in (2-D), out (3-D)
TickDirMode
Use MATLAB or user-specified tick
mark direction
Values: auto, manual
Default: auto
TickLength
Length of tick marks normalized to
axis line length, specified as
two-element vector
Values: [2-D 3-D]
Default: [0.01 0.025}
Visible
Make axes visible or invisible
Values: on, off
Default: on
XGrid, YGrid, ZGrid
Toggle grid lines on and off in
respective axis
Values: on, off
Default: off
General Information About the Axes
Children
Handles of the images, lights, lines,
patches, surfaces, and text objects
displayed in the axes
Values: vector of handles
CurrentPoint
Location of last mouse button click
defined in the axes data units
Values: a 2-by-3 matrix
2-110
axes
Property Name
Property Description
Property Value
HitTest
Specify whether axes can become
the current object (see figure
CurrentObject property)
Values: on, off
Default: on
Parent
Handle of the figure window
containing the axes
Values: scalar figure handle
Position
Location and size of axes within the
figure
Values: [left bottom width
height]
Default: [0.1300 0.1100
0.7750 0.8150] in
normalized Units
Selected
Indicate whether axes is in a
“selected” state
Values: on, off
Default: on
Tag
User-specified label
Values: any string
Default: '' (empty string)
Type
The type of graphics object (read
only)
Value: the string 'axes'
Units
Units used to interpret the
Position property
Values: inches,
centimeters, characters,
normalized, points, pixels
Default: normalized
UserData
User-specified data
Values: any matrix
Default: [] (empty matrix)
FontAngle
Select italic or normal font
Values: normal, italic,
oblique
Default: normal
FontName
Font family name (e.g., Helvetica,
Courier)
Values: a font supported by
your system or the string
Selecting Fonts and Labels
FixedWidth
Default: Typically Helvetica
2-111
axes
Property Name
Property Description
Property Value
FontSize
Size of the font used for title and
labels
Values: an integer in
FontUnits Default: 10
FontUnits
Units used to interpret the
FontSize property
Values: points,
normalized, inches,
centimeters, pixels
Default: points
FontWeight
Select bold or normal font
Values: normal, bold,
light, demi
Default: normal
Title
Handle of the title text object
Values: any valid text object
handle
XLabel, YLabel, ZLabel
Handles of the respective axis label
text objects
Values: any valid text object
handle
XTickLabel,
YTickLabel,
ZTickLabel
Specify tick mark labels for the
respective axis
Values: matrix of strings
Defaults: numeric values
selected automatically by
MATLAB
XTickLabelMode,
YTickLabelMode,
ZTickLabelMode
Use MATLAB or user-specified tick
mark labels
Values: auto, manual
Default: auto
XAxisLocation
Specify the location of the x-axis
Values: top, bottom
Default: bottom
YAxisLocation
Specify the location of the y-axis
Values: right left
Default: left
XDir, YDir, ZDir
Specify the direction of increasing
values for the respective axes
Values: normal, reverse
Default: normal
Controlling Axis Scaling
2-112
axes
Property Name
Property Description
Property Value
XLim, YLim, ZLim
Specify the limits to the respective
axes
Values: [min max]
Default: min and max
determined automatically
by MATLAB
XLimMode, YLimMode,
ZLimMode
Use MATLAB or user-specified
values for the respective axis limits
Values: auto, manual
Default: auto
XMinorGrid,YMinorGrid,
ZMinorGrid
Determines whether MATLAB
displays gridlines connecting minor
tick marks in the respective axis.
Values: on, off
Default: off
XMinorTick,YMinorTick,
ZMinorTick
Determines whether MATLAB
displays minor tick marks in the
respective axis.
Values: on, off
Default: off
XScale, YScale, ZScale
Select linear or logarithmic scaling
of the respective axis
Values: linear, log
Default: linear (changed
by plotting commands that
create nonlinear plots)
XTick, YTick, ZTick
Specify the location of the axis ticks
marks
Values: a vector of data
values locating tick marks
Default: MATLAB
automatically determines
tick mark placement
XTickMode, YTickMode,
ZTickMode
Use MATLAB or user-specified
values for the respective tick mark
locations
Values: auto, manual
Default: auto
Specify the position of point from
which you view the scene
Values: [x,y,z] axes
coordinates
Default: automatically
determined by MATLAB
Controlling the View
CameraPosition
2-113
axes
Property Name
Property Description
Property Value
CameraPositionMode
Use MATLAB or user-specified
camera position
Values: auto, manual
Default: auto
CameraTarget
Center of view pointed to by camera
Values: [x,y,z] axes
coordinates
Default: automatically
determined by MATLAB
CameraTargetMode
Use MATLAB or user-specified
camera target
Values: auto, manual
Default: auto
CameraUpVector
Direction that is oriented up
Values: [x,y,z] axes
coordinates
Default: automatically
determined by MATLAB
CameraUpVectorMode
Use MATLAB or user-specified
camera up vector
Values: auto, manual
Default: auto
CameraViewAngle
Camera field of view
Values: angle in degrees
between 0 and 180
Default: automatically
determined by MATLAB
CameraViewAngleMode
Use MATLAB or user-specified
camera view angle
Values: auto, manual
Default: auto
Projection
Select type of projection
Values: orthographic,
perspective
Default: orthographic
Controlling the Axes Aspect Ratio
DataAspectRatio
Relative scaling of data units
Values: three relative
values [dx dy dz]
Default: automatically
determined by MATLAB
DataAspectRatioMode
Use MATLAB or user-specified data
aspect ratio
Values: auto, manual
Default: auto
2-114
axes
Property Name
Property Description
Property Value
PlotBoxAspectRatio
Relative scaling of axes plot box
Values: three relative
values [dx dy dz]
Default: automatically
determined by MATLAB
PlotBoxAspectRatioMode
Use MATLAB or user-specified plot
box aspect ratio
Values: auto, manual
Default: auto
Controlling Callback Routine Execution
BusyAction
Specify how to handle events that
interrupt execution callback
routines
Values: cancel, queue
Default: queue
ButtonDownFcn
Define a callback routine that
executes when a button is pressed
over the axes
Values: string or function
handle
Default: an empty string
CreateFcn
Define a callback routine that
executes when an axes is created
Values: string or function
handle
Default: an empty string
DeleteFcn
Define a callback routine that
executes when an axes is created
Values: string or function
handle
Default: an empty string
Interruptible
Control whether an executing
callback routine can be interrupted
Values: on, off Default: on
UIContextMenu
Associate a context menu with the
axes
Values: handle of a
Uicontextmenu
Specifying the Rendering Mode
DrawMode
Specify the rendering method to use
with the Painters renderer
Values: normal, fast
Default: normal
Targeting Axes for Graphics Display
HandleVisibility
Control access to a specific axes’
handle
Values: on, callback, off
Default: on
2-115
axes
Property Name
Property Description
Property Value
NextPlot
Determine the eligibility of the axes
for displaying graphics
Values: add, replace,
replacechildren
Default: replace
Properties that Specify Transparency
ALim
Alpha axis limits
Values: [amin amax]
ALimMode
Alpha axis limits mode
Values: auto | manual
Default: auto
Properties that Specify Color
AmbientLightColor
Color of the background light in a
scene
Values: ColorSpec
Default: [1 1 1]
CLim
Control how data is mapped to
colormap
Values: [cmin cmax]
Default: automatically
determined by MATLAB
CLimMode
Use MATLAB or user-specified
values for CLim
Values: auto, manual
Default: auto
Color
Color of the axes background
Values: none, ColorSpec
Default: none
ColorOrder
Line colors used for multiline plots
Values: m-by-3 matrix of
RGB values
Default: depends on color
scheme used
XColor, YColor, ZColor
Colors of the axis lines and tick
marks
Values: ColorSpec
Default: depends on current
color scheme
2-116
Axes Properties
Modifying
Properties
2Axes Properties
You can set and query graphics object properties in two ways:
• The Property Editor is an interactive tool that enables you to see and change
object property values.
• The set and get commands enable you to set and query the values of
properties
To change the default value of properties see Setting Default Property Values.
Axes Property
Descriptions
This section lists property names along with the types of values each accepts.
Curly braces { } enclose default values.
ALim
[amin, amax]
Alpha axis limits. A two-element vector that determines how MATLAB maps
the AlphaData values of surface, patch and image objects to the figure's
alphamap. amin is the value of the data mapped to the first alpha value in the
alphamap, and amax is the value of the data mapped to the last alpha value in
the alphamap. Data values in between are linearly interpolated across the
alphamap, while data values outside are clamped to either the first or last
alphamap value, whichever is closest.
When ALimMode is auto (the default), MATLAB assigns amin the minimum
data value and amax the maximum data value in the graphics object's
AlphaData. This maps AlphaData elements with minimum data values to the
first alphamap entry and those with maximum data values to the last
alphamap entry. Data values in between are mapped linearly to the values
If the axes contains multiple graphics objects, MATLAB sets ALim to span the
range of all objects' AlphaData (or FaceVertexAlphaData for patch objects).
ALimMode
{auto} | manual
Alpha axis limits mode. In auto mode, MATLAB sets the ALim property to span
the AlphaData limits of the graphics objects displayed in the axes. If ALimMode
is manual, MATLAB does not change the value of ALim when the AlphaData
limits of axes children change. Setting the ALim property sets ALimMode to
manual.
AmbientLightColor ColorSpec
The background light in a scene. Ambient light is a directionless light that
shines uniformly on all objects in the axes. However, if there are no visible light
2-117
Axes Properties
objects in the axes, MATLAB does not use AmbientLightColor. If there are
light objects in the axes, the AmbientLightColor is added to the other light
sources.
AspectRatio
(Obsolete)
This property produces a warning message when queried or changed. It has
been superseded by the DataAspectRatio[Mode] and
PlotBoxAspectRatio[Mode] properties.
Box
on | {off}
Axes box mode. This property specifies whether to enclose the axes extent in a
box for 2-D views or a cube for 3-D views. The default is to not display the box.
BusyAction
cancel | {queue}
Callback routine interruption. The BusyAction property enables you to control
how MATLAB handles events that potentially interrupt executing callback
routines. If there is a callback routine executing, subsequently invoked
callback routines always attempt to interrupt it. If the Interruptible property
of the object whose callback is executing is set to on (the default), then
interruption occurs at the next point where the event queue is processed. If the
Interruptible property is off, the BusyAction property (of the object owning
the executing callback) determines how MATLAB handles the event. The
choices are:
• cancel – discard the event that attempted to execute a second callback
routine.
• queue – queue the event that attempted to execute a second callback routine
until the current callback finishes.
ButtonDownFcn
string or function handle
Button press callback routine. A callback routine that executes whenever you
press a mouse button while the pointer is within the axes, but not over another
graphics object displayed in the axes. For 3-D views, the active area is defined
by a rectangle that encloses the axes.
Define this routine as a string that is a valid MATLAB expression or the name
of an M-file. The expression executes in the MATLAB workspace.
See Function Handle Callbacks for information on how to use function handles
to define the callback function.
2-118
Axes Properties
CameraPosition
[x, y, z] axes coordinates
The location of the camera. This property defines the position from which the
camera views the scene. Specify the point in axes coordinates.
If you fix CameraViewAngle, you can zoom in and out on the scene by changing
the CameraPosition, moving the camera closer to the CameraTarget to zoom in
and farther away from the CameraTarget to zoom out. As you change the
CameraPosition, the amount of perspective also changes, if Projection is
perspective. You can also zoom by changing the CameraViewAngle; however,
this does not change the amount of perspective in the scene.
CameraPositionMode
{auto} | manual
Auto or manual CameraPosition. When set to auto, MATLAB automatically
calculates the CameraPosition such that the camera lies a fixed distance from
the CameraTarget along the azimuth and elevation specified by view. Setting a
value for CameraPosition sets this property to manual.
CameraTarget
[x, y, z] axes coordinates
Camera aiming point. This property specifies the location in the axes that the
camera points to. The CameraTarget and the CameraPosition define the vector
(the view axis) along which the camera looks.
CameraTargetMode
{auto} | manual
Auto or manual CameraTarget placement. When this property is auto,
MATLAB automatically positions the CameraTarget at the centroid of the axes
plotbox. Specifying a value for CameraTarget sets this property to manual.
CameraUpVector
[x, y, z] axes coordinates
Camera rotation. This property specifies the rotation of the camera around the
viewing axis defined by the CameraTarget and the CameraPosition properties.
Specify CameraUpVector as a three-element array containing the x, y, and z
components of the vector. For example, [0 1 0] specifies the positive y-axis as
the up direction.
The default CameraUpVector is [0 0 1], which defines the positive z-axis as the
up direction.
CameraUpVectorMode auto} | manual
Default or user-specified up vector. When CameraUpVectorMode is auto,
MATLAB uses a value of [0 0 1] (positive z-direction is up) for 3-D views and
2-119
Axes Properties
[0 1 0] (positive y-direction is up) for 2-D views. Setting a value for
CameraUpVector sets this property to manual.
CameraViewAngle
scalar greater than 0 and less than or equal to
180 (angle in degrees)
The field of view. This property determines the camera field of view. Changing
this value affects the size of graphics objects displayed in the axes, but does not
affect the degree of perspective distortion. The greater the angle, the larger the
field of view, and the smaller objects appear in the scene.
CameraViewAngleMode{auto} | manual
Auto or manual CameraViewAngle. When in auto mode, MATLAB sets
CameraViewAngle to the minimum angle that captures the entire scene (up to
180˚).
The following table summarizes MATLAB automatic camera behavior.
CameraView
Angle
Camera
Target
Camera
Position
Behavior
auto
auto
auto
CameraTarget is set to plot box centroid,
CameraViewAngle is set to capture entire scene,
CameraPosition is set along the view axis.
auto
auto
manual
CameraTarget is set to plot box centroid,
CameraViewAngle is set to capture entire scene.
auto
manual
auto
CameraViewAngle is set to capture entire scene,
CameraPosition is set along the view axis.
auto
manual
manual
CameraViewAngle is set to capture entire scene.
manual
auto
auto
CameraTarget is set to plot box centroid,
CameraPosition is set along the view axis.
manual
auto
manual
CameraTarget is set to plot box centroid
manual
manual
auto
CameraPosition is set along the view axis.
manual
manual
manual
All Camera properties are user-specified.
2-120
Axes Properties
Children
vector of graphics object handles
Children of the axes. A vector containing the handles of all graphics objects
rendered within the axes (whether visible or not). The graphics objects that can
be children of axes are images, lights, lines, patches, surfaces, and text. You
can change the order of the handles and thereby change the stacking of the
objects on the display.
The text objects used to label the x-, y-, and z-axes are also children of axes, but
their HandleVisibility properties are set to callback. This means their
handles do not show up in the axes Children property unless you set the Root
ShowHiddenHandles property to on.
CLim
[cmin, cmax]
Color axis limits. A two-element vector that determines how MATLAB maps
the CData values of surface and patch objects to the figure’s colormap. cmin is
the value of the data mapped to the first color in the colormap, and cmax is the
value of the data mapped to the last color in the colormap. Data values in
between are linearly interpolated across the colormap, while data values
outside are clamped to either the first or last colormap color, whichever is
closest.
When CLimMode is auto (the default), MATLAB assigns cmin the minimum
data value and cmax the maximum data value in the graphics object’s CData.
This maps CData elements with minimum data value to the first colormap
entry and with maximum data value to the last colormap entry.
If the axes contains multiple graphics objects, MATLAB sets CLim to span the
range of all objects’ CData.
CLimMode
{auto} | manual
Color axis limits mode. In auto mode, MATLAB sets the CLim property to span
the CData limits of the graphics objects displayed in the axes. If CLimMode is
manual, MATLAB does not change the value of CLim when the CData limits of
axes children change. Setting the CLim property sets this property to manual.
Clipping
{on} | off
This property has no effect on axes.
2-121
Axes Properties
Color
{none} | ColorSpec
Color of the axes back planes. Setting this property to none means the axes is
transparent and the figure color shows through. A ColorSpec is a
three-element RGB vector or one of the MATLAB predefined names. Note that
while the default value is none, the matlabrc.m file may set the axes color to
a specific color.
ColorOrder
m-by-3 matrix of RGB values
Colors to use for multiline plots. ColorOrder is an m-by-3 matrix of RGB values
that define the colors used by the plot and plot3 functions to color each line
plotted. If you do not specify a line color with plot and plot3, these functions
cycle through the ColorOrder to obtain the color for each line plotted. To obtain
the current ColorOrder, which may be set during startup, get the property
value:
get(gca,'ColorOrder')
Note that if the axes NextPlot property is set to replace (the default),
high-level functions like plot reset the ColorOrder property before
determining the colors to use. If you want MATLAB to use a ColorOrder that
is different from the default, set NextPlot to replacechildren. You can also
specify your own default ColorOrder.
CreateFcn
string or function handle
Callback routine executed during object creation. This property defines a
callback routine that executes when MATLAB creates an axes object. You must
define this property as a default value for axes. For example, the statement,
set(0,'DefaultAxesCreateFcn','set(gca,''Color'',''b'')')
defines a default value on the Root level that sets the current axes’ background
color to blue whenever you (or MATLAB) create an axes. MATLAB executes
this routine after setting all properties for the axes. Setting this property on an
existing axes object has no effect.
The handle of the object whose CreateFcn is being executed is accessible only
through the Root CallbackObject property, which can be queried using gcbo.
See Function Handle Callbacks for information on how to use function handles
to define the callback function.
2-122
Axes Properties
CurrentPoint
2-by-3 matrix
Location of last button click, in axes data units. A 2-by-3 matrix containing the
coordinates of two points defined by the location of the pointer. These two
points lie on the line that is perpendicular to the plane of the screen and passes
through the pointer. The 3-D coordinates are the points, in the axes coordinate
system, where this line intersects the front and back surfaces of the axes
volume (which is defined by the axes x, y, and z limits).
The returned matrix is of the form:
x back y back z back
x front y front z front
MATLAB updates the CurrentPoint property whenever a button-click event
occurs. The pointer does not have to be within the axes, or even the figure
window; MATLAB returns the coordinates with respect to the requested axes
regardless of the pointer location.
DataAspectRatio
[dx dy dz]
Relative scaling of data units. A three-element vector controlling the relative
scaling of data units in the x, y, and z directions. For example, setting this
property t o [1 2 1] causes the length of one unit of data in the x direction to
be the same length as two units of data in the y direction and one unit of data
in the z direction.
Note that the DataAspectRatio property interacts with the
PlotBoxAspectRatio, XLimMode, YLimMode, and ZLimMode properties to control
how MATLAB scales the x-, y-, and z-axis. Setting the DataAspectRatio will
disable the stretch-to-fill behavior, if DataAspectRatioMode,
PlotBoxAspectRatioMode, and CameraViewAngleMode are all auto. The
2-123
Axes Properties
following table describes the interaction between properties when
stretch-to-fill behavior is disabled.
X-, Y-,
Z-Limits
DataAspect
Ratio
PlotBox
AspectRatio
Behavior
auto
auto
auto
Limits chosen to span data range in all
dimensions.
auto
auto
manual
Limits chosen to span data range in all
dimensions. DataAspectRatio is modified to
achieve the requested PlotBoxAspectRatio
within the limits selected by MATLAB.
auto
manual
auto
Limits chosen to span data range in all
dimensions. PlotBoxAspectRatio is modified to
achieve the requested DataAspectRatio within
the limits selected by MATLAB.
auto
manual
manual
Limits chosen to completely fit and center the
plot within the requested PlotBoxAspectRatio
given the requested DataAspectRatio (this may
produce empty space around 2 of the 3
dimensions).
manual
auto
auto
Limits are honored. The DataAspectRatio and
PlotBoxAspectRatio are modified as necessary.
manual
auto
manual
Limits and PlotBoxAspectRatio are honored.
The DataAspectRatio is modified as necessary.
manual
manual
auto
Limits and DataAspectRatio are honored. The
PlotBoxAspectRatio is modified as necessary.
1 manual
2 auto
manual
manual
The 2 automatic limits are selected to honor the
specified aspect ratios and limit. See “Examples”
2 or 3
manual
manual
manual
Limits and DataAspectRatio are honored; the
PlotBoxAspectRatio is ignored.
2-124
Axes Properties
DataAspectRatioMode
{auto} | manual
User or MATLAB controlled data scaling. This property controls whether the
values of the DataAspectRatio property are user defined or selected
automatically by MATLAB. Setting values for the DataAspectRatio property
automatically sets this property to manual. Changing DataAspectRatioMode to
manual disables the stretch-to-fill behavior, if DataAspectRatioMode,
PlotBoxAspectRatioMode, and CameraViewAngleMode are all auto.
DeleteFcn
string or function handle
Delete axes callback routine. A callback routine that executes when the axes
object is deleted (e.g., when you issue a delete or a close command). MATLAB
executes the routine before destroying the object’s properties so the callback
routine can query these values.
The handle of the object whose DeleteFcn is being executed is accessible only
through the Root CallbackObject property, which can be queried using gcbo.
See Function Handle Callbacks for information on how to use function handles
to define the callback function.
DrawMode
{normal} | fast
Rendering method. This property controls the method MATLAB uses to render
graphics objects displayed in the axes, when the figure Renderer property is
painters.
• normal mode draws objects in back to front ordering based on the current
view in order to handle hidden surface elimination and object intersections.
• fast mode draws objects in the order in which you specify the drawing
commands, without considering the relationships of the objects in three
dimensions. This results in faster rendering because it requires no sorting of
objects according to location in the view, but may produce undesirable
results because it bypasses the hidden surface elimination and object
intersection handling provided by normal DrawMode.
When the figure Renderer is zbuffer, DrawMode is ignored, and hidden surface
elimination and object intersection handling are always provided.
FontAngle
{normal} | italic | oblique
Select italic or normal font. This property selects the character slant for axes
text. normal specifies a nonitalic font. italic and oblique specify italic font.
2-125
Axes Properties
FontName
A name such as Courier or the string FixedWidth
Font family name. The font family name specifying the font to use for axes
labels. To display and print properly, FontName must be a font that your system
supports. Note that the x-, y-, and z-axis labels do not display in a new font until
you manually reset them (by setting the XLabel, YLabel, and ZLabel properties
or by using the xlabel, ylabel, or zlabel command). Tick mark labels change
immediately.
Specifying a Fixed-Width Font
If you want an axes to use a fixed-width font that looks good in any locale, you
should set FontName to the string FixedWidth:
set(axes_handle,'FontName','FixedWidth')
This eliminates the need to hardcode the name of a fixed-width font, which may
not display text properly on systems that do not use ASCII character encoding
(such as in Japan where multibyte character sets are used). A properly written
MATLAB application that needs to use a fixed-width font should set FontName
to FixedWidth (note that this string is case sensitive) and rely on
FixedWidthFontName to be set correctly in the end-user’s environment.
End users can adapt a MATLAB application to different locales or personal
environments by setting the root FixedWidthFontName property to the
appropriate value for that locale from startup.m.
Note that setting the root FixedWidthFontName property causes an immediate
update of the display to use the new font.
FontSize
Font size specified in FontUnits
Font size. An integer specifying the font size to use for axes labels and titles, in
units determined by the FontUnits property. The default point size is 12. The
x-, y-, and z-axis text labels do not display in a new font size until you manually
reset them (by setting the XLabel, YLabel, or ZLabel properties or by using the
xlabel, ylabel, or zlabel command). Tick mark labels change immediately.
FontUnits
{points} | normalized | inches |
centimeters | pixels
Units used to interpret the FontSize property. When set to normalized,
MATLAB interprets the value of FontSize as a fraction of the height of the
axes. For example, a normalized FontSize of 0.1 sets the text characters to a
2-126
Axes Properties
font whose height is one tenth of the axes’ height. The default units (points),
are equal to 1/72 of an inch.
FontWeight
{normal} | bold | light | demi
Select bold or normal font. The character weight for axes text. The x-, y-, and
z-axis text labels do not display in bold until you manually reset them (by
setting the XLabel, YLabel, and ZLabel properties or by using the xlabel,
ylabel, or zlabel commands). Tick mark labels change immediately.
GridLineStyle
− | − −| {:} | −. | none
Line style used to draw grid lines. The line style is a string consisting of a
character, in quotes, specifying solid lines (−), dashed lines (−−), dotted lines(:),
or dash-dot lines (−.). The default grid line style is dotted. To turn on grid lines,
use the grid command.
HandleVisibility
{on} | callback | off
Control access to object’s handle by command-line users and GUIs. This
property determines when an object’s handle is visible in its parent’s list of
children. HandleVisibility is useful for preventing command-line users from
accidentally drawing into or deleting a figure that contains only user interface
devices (such as a dialog box).
Handles are always visible when HandleVisibility is on.
Setting HandleVisibility to callback causes handles to be visible from
within callback routines or functions invoked by callback routines, but not from
within functions invoked from the command line. This provides a means to
protect GUIs from command-line users, while allowing callback routines to
have complete access to object handles.
Setting HandleVisibility to off makes handles invisible at all times. This
may be necessary when a callback routine invokes a function that might
potentially damage the GUI (such as evaluating a user-typed string) and so
temporarily hides its own handles during the execution of that function.
When a handle is not visible in its parent’s list of children, it cannot be
returned by functions that obtain handles by searching the object hierarchy or
querying handle properties. This includes get, findobj, gca, gcf, gco, newplot,
cla, clf, and close.
2-127
Axes Properties
When a handle’s visibility is restricted using callback or off, the object’s
handle does not appear in its parent’s Children property, figures do not appear
in the Root’s Currentfigure property, objects do not appear in the Root’s
CallbackObject property or in the figure’s CurrentObject property, and axes
do not appear in their parent’s Currentaxes property.
You can set the Root ShowHiddenHandles property to on to make all handles
visible, regardless of their HandleVisibility settings (this does not affect the
values of the HandleVisibility properties).
Handles that are hidden are still valid. If you know an object’s handle, you can
set and get its properties, and pass it to any function that operates on handles.
HitTest
{on} | off
Selectable by mouse click. HitTest determines if the axes can become the
current object (as returned by the gco command and the figure CurrentObject
property) as a result of a mouse click on the axes. If HitTest is off, clicking on
the axes selects the object below it (which is usually the figure containing it).
Interruptible
{on} | off
Callback routine interruption mode. The Interruptible property controls
whether an axes callback routine can be interrupted by subsequently invoked
callback routines. Only callback routines defined for the ButtonDownFcn are
affected by the Interruptible property. MATLAB checks for events that can
interrupt a callback routine only when it encounters a drawnow, figure,
getframe, or pause command in the routine. See the BusyAction property for
related information.
Setting Interruptible to on allows any graphics object’s callback routine to
interrupt callback routines originating from an axes property. Note that
MATLAB does not save the state of variables or the display (e.g., the handle
returned by the gca or gcf command) when an interruption occurs.
Layer
{bottom} | top
Draw axis lines below or above graphics objects. This property determines if
axis lines and tick marks draw on top or below axes children objects for any 2-D
view (i.e., when you are looking along the x-, y-, or z-axis). This is useful for
placing grid lines and tick marks on top of images.
2-128
Axes Properties
LineStyleOrder
LineSpec
Order of line styles and markers used in a plot. This property specifies which
line styles and markers to use and in what order when creating multiple-line
plots. For example,
set(gca,'LineStyleOrder', '−*|:|o')
sets LineStyleOrder to solid line with asterisk marker, dotted line, and hollow
circle marker. The default is (−), which specifies a solid line for all data plotted.
Alternatively, you can create a cell array of character strings to define the line
styles:
set(gca,'LineStyleOrder',{'−*',':','o'})
MATLAB supports four line styles, which you can specify any number of times
in any order. MATLAB cycles through the line styles only after using all colors
defined by the ColorOrder property. For example, the first eight lines plotted
use the different colors defined by ColorOrder with the first line style.
MATLAB then cycles through the colors again, using the second line style
specified, and so on.
You can also specify line style and color directly with the plot and plot3
functions or by altering the properties of the line objects.
Note that, if the axes NextPlot property is set to replace (the default),
high-level functions like plot reset the LineStyleOrder property before
determining the line style to use. If you want MATLAB to use a
LineStyleOrder that is different from the default, set NextPlot to
replacechildren. You can also specify your own default LineStyleOrder.
LineWidth
linewidth in points
Width of axis lines. This property specifies the width, in points, of the x-, y-, and
z-axis lines. The default line width is 0.5 points (1 point = 1/72 inch).
MinorGridLineStyle − | − −| {:} | −. | none
Line style used to draw minor grid lines. The line style is a string consisting of
one or more characters, in quotes, specifying solid lines (−), dashed lines (−−),
dotted lines(:), or dash-dot lines (−.). The default minor grid line style is dotted.
To turn on minor grid lines, use the grid minor command.
2-129
Axes Properties
NextPlot
add | {replace} | replacechildren
Where to draw the next plot. This property determines how high-level plotting
functions draw into an existing axes.
• add — use the existing axes to draw graphics objects.
• replace — reset all axes properties, except Position, to their defaults and
delete all axes children before displaying graphics (equivalent to cla reset).
• replacechildren — remove all child objects, but do not reset axes properties
(equivalent to cla).
The newplot function simplifies the use of the NextPlot property and is used
by M-file functions that draw graphs using only low-level object creation
routines. See the M-file pcolor.m for an example. Note that figure graphics
objects also have a NextPlot property.
Parent
figure handle
Axes parent. The handle of the axes’ parent object. The parent of an axes object
is the figure in which it is displayed. The utility function gcf returns the
handle of the current axes’ Parent. You can reparent axes to other figure
objects.
PlotBoxAspectRatio
[px py pz]
Relative scaling of axes plotbox. A three-element vector controlling the relative
scaling of the plot box in the x-, y-, and z-directions. The plot box is a box
enclosing the axes data region as defined by the x-, y-, and z-axis limits.
Note that the PlotBoxAspectRatio property interacts with the
DataAspectRatio, XLimMode, YLimMode, and ZLimMode properties to control the
way graphics objects are displayed in the axes. Setting the
PlotBoxAspectRatio disables stretch-to-fill behavior, if
DataAspectRatioMode, PlotBoxAspectRatioMode, and CameraViewAngleMode
are all auto.
PlotBoxAspectRatioMode
{auto} | manual
User or MATLAB controlled axis scaling. This property controls whether the
values of the PlotBoxAspectRatio property are user defined or selected
automatically by MATLAB. Setting values for the PlotBoxAspectRatio
property automatically sets this property to manual. Changing the
PlotBoxAspectRatioMode to manual disables stretch-to-fill behavior, if
2-130
Axes Properties
DataAspectRatioMode, PlotBoxAspectRatioMode, and CameraViewAngleMode
are all auto.
Position
four-element vector
Position of axes. A four-element vector specifying a rectangle that locates the
axes within the figure window. The vector is of the form:
[left bottom width height]
where left and bottom define the distance from the lower-left corner of the
figure window to the lower-left corner of the rectangle. width and height are
the dimensions of the rectangle. All measurements are in units specified by the
Units property.
When axes stretch-to-fill behavior is enabled (when DataAspectRatioMode,
PlotBoxAspectRatioMode, CameraViewAngleMode are all auto), the axes are
stretched to fill the Position rectangle. When stretch-to-fill is disabled, the
axes are made as large as possible, while obeying all other properties, without
extending outside the Position rectangle
Projection
{orthographic} | perspective
Type of projection. This property selects between two projection types:
• orthographic – This projection maintains the correct relative dimensions of
graphics objects with regard to the distance a given point is from the viewer.
Parallel lines in the data are drawn parallel on the screen.
• perspective – This projection incorporates foreshortening, which allows you
to perceive depth in 2-D representations of 3-D objects. Perspective
projection does not preserve the relative dimensions of objects; a distant line
segment displays smaller than a nearer line segment of the same length.
Parallel lines in the data may not appear parallel on screen.
Selected
on | off
Is object selected. When you set this property to on, MATLAB displays selection
“handles” at the corners and midpoints if the SelectionHighlight property is
also on (the default). You can, for example, define the ButtonDownFcn callback
routine to set this property to on, thereby indicating that the axes has been
selected.
2-131
Axes Properties
SelectionHighlight
{on} | off
Objects highlight when selected. When the Selected property is on, MATLAB
indicates the selected state by drawing four edge handles and four corner
handles. When SelectionHighlight is off, MATLAB does not draw the
handles.
Tag
string (GUIDE sets this property)
User-specified object label. The Tag property provides a means to identify
graphics objects with a user-specified label. This is particularly useful when
constructing interactive graphics programs that would otherwise need to
define object handles as global variables or pass them as arguments between
callback routines.
For example, suppose you want to direct all graphics output from an M-file to
a particular axes, regardless of user actions that may have changed the current
axes. To do this, identify the axes with a Tag:
axes('Tag','Special Axes')
Then make that axes the current axes before drawing by searching for the Tag
with findobj:
axes(findobj('Tag','Special Axes'))
TickDir
in | out
Direction of tick marks. For 2-D views, the default is to direct tick marks
inward from the axis lines; 3-D views direct tick marks outward from the axis
line.
TickDirMode
{auto} | manual
Automatic tick direction control. In auto mode, MATLAB directs tick marks
inward for 2-D views and outward for 3-D views. When you specify a setting for
TickDir, MATLAB sets TickDirMode to manual. In manual mode, MATLAB
does not change the specified tick direction.
TickLength
[2DLength 3DLength]
Length of tick marks. A two-element vector specifying the length of axes tick
marks. The first element is the length of tick marks used for 2-D views and the
second element is the length of tick marks used for 3-D views. Specify tick mark
lengths in units normalized relative to the longest of the visible X-, Y-, or Z-axis
annotation lines.
2-132
Axes Properties
Title
handle of text object
Axes title. The handle of the text object that is used for the axes title. You can
use this handle to change the properties of the title text or you can set Title to
the handle of an existing text object. For example, the following statement
changes the color of the current title to red:
set(get(gca,'Title'),'Color','r')
To create a new title, set this property to the handle of the text object you want
to use:
set(gca,'Title',text('String','New Title','Color','r'))
However, it is generally simpler to use the title command to create or replace
an axes title:
title('New Title','Color','r')
Type
string (read only)
Type of graphics object. This property contains a string that identifies the class
of graphics object. For axes objects, Type is always set to 'axes'.
UIContextMenu
handle of a uicontextmenu object
Associate a context menu with the axes. Assign this property the handle of a
Uicontextmenu object created in the axes’ parent figure. Use the
uicontextmenu function to create the context menu. MATLAB displays the
context menu whenever you right-click over the axes.
Units
inches | centimeters | {normalized} |
points | pixels | characters
Position units. The units used to interpret the Position property. All units are
measured from the lower-left corner of the figure window.
• normalized units map the lower-left corner of the figure window to (0,0) and
the upper-right corner to (1.0, 1.0).
• inches, centimeters, and points are absolute units (one point equals 1/72 of
an inch).
• Character units are defined by characters from the default system font; the
width of one character is the width of the letter x, the height of one character
is the distance between the baselines of two lines of text.
2-133
Axes Properties
UserData
matrix
User specified data. This property can be any data you want to associate with
the axes object. The axes does not use this property, but you can access it using
the set and get functions.
View
Obsolete
The functionality provided by the View property is now controlled by the axes
camera properties – CameraPosition, CameraTarget, CameraUpVector, and
CameraViewAngle. See the view command.
Visible
{on} | off
Visibility of axes. By default, axes are visible. Setting this property to off
prevents axis lines, tick marks, and labels from being displayed. The visible
property does not affect children of axes.
XAxisLocation
top | {bottom}
Location of x-axis tick marks and labels. This property controls where
MATLAB displays the x-axis tick marks and labels. Setting this property to top
moves the x-axis to the top of the plot from its default position at the bottom.
YAxisLocation
right | {left}
Location of y-axis tick marks and labels. This property controls where
MATLAB displays the y-axis tick marks and labels. Setting this property to
right moves the y-axis to the right side of the plot from its default position on
the left side. See the plotyy function for a simple way to use two y-axes.
Properties That Control the X-, Y-, or Z-Axis
XColor, YColor, ZColor
ColorSpec
Color of axis lines. A three-element vector specifying an RGB triple, or a
predefined MATLAB color string. This property determines the color of the
axis lines, tick marks, tick mark labels, and the axis grid lines of the respective
x-, y-, and z-axis. The default color axis color is black. See ColorSpec for details
on specifying colors.
XDir, YDir, ZDir
{normal} | reverse
Direction of increasing values. A mode controlling the direction of increasing
axis values. axes form a right-hand coordinate system. By default:
2-134
Axes Properties
• x-axis values increase from left to right. To reverse the direction of increasing
x values, set this property to reverse.
set(gca,'XDir','reverse')
• y-axis values increase from bottom to top (2-D view) or front to back (3-D
view). To reverse the direction of increasing y values, set this property to
reverse.
set(gca,'YDir','reverse')
• z-axis values increase pointing out of the screen (2-D view) or from bottom to
top (3-D view). To reverse the direction of increasing z values, set this
property to reverse.
set(gca,'ZDir','reverse')
XGrid, YGrid, ZGrid
on | {off}
Axis gridline mode. When you set any of these properties to on, MATLAB draws
grid lines perpendicular to the respective axis (i.e., along lines of constant x, y,
or z values). Use the grid command to set all three properties on or off at once.
set(gca,'XGrid','on')
XLabel, YLabel, ZLabel
handle of text object
Axis labels. The handle of the text object used to label the x, y, or z-axis,
respectively. To assign values to any of these properties, you must obtain the
handle to the text string you want to use as a label. This statement defines a
text object and assigns its handle to the XLabel property:
set(get(gca,'XLabel'),'String','axis label')
MATLAB places the string 'axis label' appropriately for an x-axis label. Any
text object whose handle you specify as an XLabel, YLabel, or ZLabel property
is moved to the appropriate location for the respective label.
Alternatively, you can use the xlabel, ylabel, and zlabel functions, which
generally provide a simpler means to label axis lines.
XLim, YLim, ZLim
[minimum maximum]
Axis limits. A two-element vector specifying the minimum and maximum
values of the respective axis.
2-135
Axes Properties
Changing these properties affects the scale of the x-, y-, or z-dimension as well
as the placement of labels and tick marks on the axis. The default values for
these properties are [0 1].
XLimMode, YLimMode, ZLimMode{auto} | manual
MATLAB or user-controlled limits. The axis limits mode determines whether
MATLAB calculates axis limits based on the data plotted (i.e., the XData,
YData, or ZData of the axes children) or uses the values explicitly set with the
XLim, YLim, or ZLim property, in which case, the respective limits mode is set to
manual.
on | {off}
XMinorGrid, YMinorGrid, ZMinorGrid
Enable or disable minor gridlines. When set to on, MATLAB draws gridlines
aligned with the minor tick marks of the respective axis. Note that you do not
have to enable minor ticks to display minor grids.
on | {off}
XMinorTick, YMinorTick, ZMinorTick
Enable or disable minor tick marks. When set to on, MATLAB draws tick
marks between the major tick marks of the respective axis. MATLAB
automaticaly determines the number of minor ticks based on the space
between the major ticks.
XScale, YScale, ZScale
{linear} | log
Axis scaling. Linear or logarithmic scaling for the respective axis. See also
loglog, semilogx, and semilogy.
XTick, YTick, ZTick
vector of data values locating tick marks
Tick spacing. A vector of x-, y-, or z-data values that determine the location of
tick marks along the respective axis. If you do not want tick marks displayed,
set the respective property to the empty vector, [ ]. These vectors must contain
monotonically increasing values.
XTickLabel, YTickLabel, ZTickLabel
string
Tick labels. A matrix of strings to use as labels for tick marks along the
respective axis. These labels replace the numeric labels generated by
MATLAB. If you do not specify enough text labels for all the tick marks,
MATLAB uses all of the labels specified, then reuses the specified labels.
For example, the statement,
set(gca,'XTickLabel',{'One';'Two';'Three';'Four'})
2-136
Axes Properties
labels the first four tick marks on the x-axis and then reuses the labels until all
ticks are labeled.
Labels can be specified as cell arrays of strings, padded string matrices, string
vectors separated by vertical slash characters, or as numeric vectors (where
each number is implicitly converted to the equivalent string using num2str).
All of the following are equivalent:
set(gca,'XTickLabel',{'1';'10';'100'})
set(gca,'XTickLabel','1|10|100')
set(gca,'XTickLabel',[1;10;100])
set(gca,'XTickLabel',['1 ';'10 ';'100'])
Note that tick labels do not interpret TeX character sequences (however, the
Title, XLabel, YLabel, and ZLabel properties do).
XTickMode, YTickMode, ZTickMode {auto} | manual
MATLAB or user controlled tick spacing. The axis tick modes determine
whether MATLAB calculates the tick mark spacing based on the range of data
for the respective axis (auto mode) or uses the values explicitly set for any of
the XTick, YTick, and ZTick properties (manual mode). Setting values for the
XTick, YTick, or ZTick properties sets the respective axis tick mode to manual.
XTickLabelMode, YTickLabelMode, ZTickLabelMode
{auto} | manual
MATLAB or user determined tick labels. The axis tick mark labeling mode
determines whether MATLAB uses numeric tick mark labels that span the
range of the plotted data (auto mode) or uses the tick mark labels specified
with the XTickLabel, YTickLabel, or ZTickLabel property (manual mode).
Setting values for the XTickLabel, YTickLabel, or ZTickLabel property sets
the respective axis tick label mode to manual.
2-137
axis
Purpose
Syntax
2axis
Axis scaling and appearance
axis([xmin xmax ymin ymax])
axis([xmin xmax ymin ymax zmin zmax cmin cmax])
v = axis
axis
axis
axis
axis
auto
manual
tight
fill
axis ij
axis xy
axis
axis
axis
axis
axis
equal
image
square
vis3d
normal
axis off
axis on
axis(axes_handles,...)
[mode,visibility,direction] = axis('state')
Description
axis manipulates commonly used axes properties. (See Algorithm section.)
axis([xmin xmax ymin ymax]) sets the limits for the x- and y-axis of the
current axes.
axis([xmin xmax ymin ymax zmin zmax cmin cmax]) sets the x-, y-, and
z-axis limits and the color scaling limits (see caxis) of the current axes.
v = axis returns a row vector containing scaling factors for the x-, y-, and
z-axis. v has four or six components depending on whether the current axes is
2-D or 3-D, respectively. The returned values are the current axes’ XLim, Ylim,
and ZLim properties.
2-138
axis
axis auto sets MATLAB to its default behavior of computing the current axes’
limits automatically, based on the minimum and maximum values of x, y, and
z data. You can restrict this automatic behavior to a specific axis. For example,
axis 'auto x' computes only the x-axis limits automatically; axis 'auto yz'
computes the y- and z-axis limits automatically.
axis manual and axis(axis) freezes the scaling at the current limits, so that
if hold is on, subsequent plots use the same limits. This sets the XLimMode,
YLimMode, and ZLimMode properties to manual.
axis tight sets the axis limits to the range of the data.
axis fill sets the axis limits and PlotBoxAspectRatio so that the axes fill
the position rectangle. This option has an effect only if
PlotBoxAspectRatioMode or DataAspectRatioMode are manual.
axis ij places the coordinate system origin in the upper-left corner. The i-axis
is vertical, with values increasing from top to bottom. The j-axis is horizontal
with values increasing from left to right.
axis xy draws the graph in the default Cartesian axes format with the
coordinate system origin in the lower-left corner. The x-axis is horizontal with
values increasing from left to right. The y-axis is vertical with values
increasing from bottom to top.
axis equal sets the aspect ratio so that the data units are the same in every
direction. The aspect ratio of the x-, y-, and z-axis is adjusted automatically
according to the range of data units in the x, y, and z directions.
axis image is the same as axis equal except that the plot box fits tightly
around the data.
axis square makes the current axes region square (or cubed when
three-dimensional). MATLAB adjusts the x-axis, y-axis, and z-axis so that they
have equal lengths and adjusts the increments between data units accordingly.
axis vis3d freezes aspect ratio properties to enable rotation of 3-D objects and
overrides stretch-to-fill.
2-139
axis
axis normal automatically adjusts the aspect ratio of the axes and the relative
scaling of the data units so that the plot fits the figures shape as best as
possible.
axis off turns off all axis lines, tick marks, and labels.
axis on turns on all axis lines, tick marks, and labels.
axis(axes_handles,...) applies the axis command to the specified axes. For
example, the following statements
h1 = subplot(221);
h2 = subplot(222);
axis([h1 h2],'square')
set both axes to square.
[mode,visibility,direction] = axis('state') returns three strings
indicating the current setting of axes properties:
Output Argument
Strings Returned
mode
'auto' | 'manual'
visibility
'on' | 'off'
direction
'xy' | 'ij'
mode is auto if XLimMode, YLimMode, and ZLimMode are all set to auto. If
XLimMode, YLimMode, or ZLimMode is manual, mode is manual.
Examples
The statements
x = 0:.025:pi/2;
plot(x,tan(x),'-ro')
2-140
axis
use the automatic scaling of the y-axis based on ymax = tan(1.57), which is
well over 1000:
1400
1200
1000
800
600
400
200
0
0
0.2
0.4
0.6
0.8
1
1.2
1.4
1.6
The right figure shows a more satisfactory plot after typing
2-141
axis
axis([0
pi/2
0
5])
5
4.5
4
3.5
3
2.5
2
1.5
1
0.5
0
Algorithm
0
0.5
1
1.5
When you specify minimum and maximum values for the x-, y-, and z-axes,
axis sets the XLim, Ylim, and ZLim properties for the current axes to the
respective minimum and maximum values in the argument list. Additionally,
the XLimMode, YLimMode, and ZLimMode properties for the current axes are set
to manual.
axis auto sets the current axes’ XLimMode, YLimMode, and ZLimMode properties
to 'auto'.
axis manual sets the current axes’ XLimMode, YLimMode, and ZLimMode
properties to 'manual'.
2-142
axis
The following table shows the values of the axes properties set by axis equal,
axis normal, axis square, and axis image.
Axes Property
axis equal
axis normal
axis square
axis tightequal
DataAspectRatio
[1 1 1]
not set
not set
[1 1 1]
DataAspectRatioMode
manual
auto
auto
manual
PlotBoxAspectRatio
[3 4 4]
not set
[1 1 1]
auto
PlotBoxAspectRatioMode
manual
auto
manual
auto
Stretch-to-fill
disabled
active
disabled
disabled
See Also
axes, get, grid, set, subplot
Properties of axes graphics objects
“Axes Operations” for related functions
2-143
balance
Purpose
2balance
Diagonal scaling to improve eigenvalue accuracy
Syntax
[T,B] = balance(A)
B = balance(A)
Description
[T,B] = balance(A) returns a similarity transformation T such that
B = T\A*T, and B has approximately equal row and column norms. T is a
permutation of a diagonal matrix whose elements are integer powers of two to
prevent the introduction of round-off error. If A is symmetric, then B == A and
T is the identity matrix.
B = balance(A) returns just the balanced matrix B.
Remarks
Nonsymmetric matrices can have poorly conditioned eigenvalues. Small
perturbations in the matrix, such as roundoff errors, can lead to large
perturbations in the eigenvalues. The condition number of the eigenvector
matrix,
cond(V) = norm(V)*norm(inv(V))
where
[V,T] = eig(A)
relates the size of the matrix perturbation to the size of the eigenvalue
perturbation. Note that the condition number of A itself is irrelevant to the
eigenvalue problem.
Balancing is an attempt to concentrate any ill conditioning of the eigenvector
matrix into a diagonal scaling. Balancing usually cannot turn a nonsymmetric
matrix into a symmetric matrix; it only attempts to make the norm of each row
equal to the norm of the corresponding column.
Note The MATLAB eigenvalue function, eig(A), automatically balances A
before computing its eigenvalues. Turn off the balancing with
eig(A,'nobalance').
2-144
balance
Examples
This example shows the basic idea. The matrix A has large elements in the
upper right and small elements in the lower left. It is far from being symmetric.
A = [1 100 10000; .01 1 100; .0001
A =
1.0e+04 *
0.0001
0.0100
1.0000
0.0000
0.0001
0.0100
0.0000
0.0000
0.0001
.01
1]
Balancing produces a diagonal matrix T with elements that are powers of two
and a balanced matrix B that is closer to symmetric than A.
[T,B] = balance(A)
T =
1.0e+03 *
2.0480
0
0
0.0320
0
0
B =
1.0000
1.5625
0.6400
1.0000
0.8192
1.2800
0
0
0.0003
1.2207
0.7813
1.0000
To see the effect on eigenvectors, first compute the eigenvectors of A, shown
here as the columns of V.
[V,E] = eig(A); V
V =
-1.0000
0.9999
0.0050
0.0100
0.0000
0.0001
0.9937
-0.1120
0.0010
Note that all three vectors have the first component the largest. This indicates
V is badly conditioned; in fact cond(V) is 8.7766e+003. Next, look at the
eigenvectors of B.
[V,E] = eig(B); V
V =
-0.8873
0.6933
0.2839
0.4437
0.3634
0.5679
0.0898
-0.6482
-0.7561
2-145
balance
Now the eigenvectors are well behaved and cond(V) is 1.4421. The ill
conditioning is concentrated in the scaling matrix; cond(T) is 8192.
This example is small and not really badly scaled, so the computed eigenvalues
of A and B agree within roundoff error; balancing has little effect on the
computed results.
Algorithm
balance uses LAPACK routines DGEBAL (real) and ZGEBAL (complex). If you
request the output T, it also uses the LAPACK routines DGEBAK (real) and
ZGEBAK (complex).
Limitations
Balancing can destroy the properties of certain matrices; use it with some care.
If a matrix contains small elements that are due to roundoff error, balancing
may scale them up to make them as significant as the other elements of the
original matrix.
See Also
eig
References
[1] Anderson, E., Z. Bai, C. Bischof, S. Blackford, J. Demmel, J. Dongarra,
J. Du Croz, A. Greenbaum, S. Hammarling, A. McKenney, and D. Sorensen,
LAPACK User’s Guide
(http://www.netlib.org/lapack/lug/lapack_lug.html), Third Edition,
SIAM, Philadelphia, 1999.
2-146
bar, barh
Purpose
Syntax
2bar, barh
Bar chart
bar(Y)
bar(x,Y)
bar(...,width)
bar(...,'style')
bar(...,LineSpec)
h = bar(...)
barh(...)
h = barh(...)
Description
A bar chart displays the values in a vector or matrix as horizontal or vertical
bars.
bar(Y) draws one bar for each element in Y. If Y is a matrix, bar groups the
bars produced by the elements in each row. The x-axis scale ranges from 1 to
length(Y) when Y is a vector, and 1 to size(Y,1), which is the number of rows,
when Y is a matrix.
bar(x,Y) draws a bar for each element in Y at locations specified in x, where x
is a monotonically increasing vector defining the x-axis intervals for the
vertical bars. If Y is a matrix, bar clusters the elements in the same row in Y at
locations corresponding to an element in x.
bar(...,width) sets the relative bar width and controls the separation of bars
within a group. The default width is 0.8, so if you do not specify x, the bars
within a group have a slight separation. If width is 1, the bars within a group
touch one another.
bar(...,'style') specifies the style of the bars. 'style' is 'grouped' or
'stacked'. 'group' is the default mode of display.
• 'grouped' displays n groups of m vertical bars, where n is the number of
rows and m is the number of columns in Y. The group contains one bar per
column in Y.
• 'stacked' displays one bar for each row in Y. The bar height is the sum of
the elements in the row. Each bar is multi-colored, with colors corresponding
2-147
bar, barh
to distinct elements and showing the relative contribution each row element
makes to the total sum.
bar(...,LineSpec) displays all bars using the color specified by LineSpec.
h = bar(...) returns a vector of handles to patch graphics objects. bar creates
one patch graphics object per column in Y.
barh(...), and h = barh(...) create horizontal bars. Y determines the bar
length. The vector x is a monotonic vector defining the y-axis intervals for
horizontal bars.
Examples
Plot a bell shaped curve:
x = –2.9:0.2:2.9;
bar(x,exp(–x.*x))
colormap hsv
1
0.9
0.8
0.7
0.6
0.5
0.4
0.3
0.2
0.1
0
−3
−2
−1
0
1
2
3
Create four subplots showing the effects of various bar arguments:
Y = round(rand(5,3)*10);
subplot(2,2,1)
bar(Y,'group')
title 'Group'
2-148
bar, barh
subplot(2,2,2)
bar(Y,'stack')
title 'Stack'
subplot(2,2,3)
barh(Y,'stack')
title 'Stack'
subplot(2,2,4)
bar(Y,1.5)
title 'Width = 1.5'
Group
Stack
10
25
8
20
6
15
4
10
2
5
0
0
1
2
3
4
5
1
Stack
2
3
4
5
Width = 1.5
10
5
8
4
6
3
4
2
2
1
0
0
5
10
15
20
25
1
2
3
4
5
2-149
bar, barh
See Also
bar3, ColorSpec, patch, stairs, hist
“Area, Bar, and Pie Plots” for related functions
Bar and Area Graphs for more examples
2-150
bar3, bar3h
Purpose
Syntax
2bar3, bar3h
Three-dimensional bar chart
bar3(Y)
bar3(x,Y)
bar3(...,width)
bar3(...,'style')
bar3(...,LineSpec)
h = bar3(...)
bar3h(...)
h = bar3h(...)
Description
bar3 and bar3h draw three-dimensional vertical and horizontal bar charts.
bar3(Y) draws a three-dimensional bar chart, where each element in Y
corresponds to one bar. When Y is a vector, the x-axis scale ranges from 1 to
length(Y). When Y is a matrix, the x-axis scale ranges from 1 to size(Y,2),
which is the number of columns, and the elements in each row are grouped
together.
bar3(x,Y) draws a bar chart of the elements in Y at the locations specified in
x, where x is a monotonic vector defining the y-axis intervals for vertical bars.
If Y is a matrix, bar3 clusters elements from the same row in Y at locations
corresponding to an element in x. Values of elements in each row are grouped
together.
bar3(...,width) sets the width of the bars and controls the separation of bars
within a group. The default width is 0.8, so if you do not specify x, bars within
a group have a slight separation. If width is 1, the bars within a group touch
one another.
bar3(...,'style') specifies the style of the bars. 'style' is 'detached',
'grouped', or 'stacked'. 'detached' is the default mode of display.
• 'detached' displays the elements of each row in Y as separate blocks behind
one another in the x direction.
• 'grouped' displays n groups of m vertical bars, where n is the number of
rows and m is the number of columns in Y. The group contains one bar per
column in Y.
2-151
bar3, bar3h
• 'stacked' displays one bar for each row in Y. The bar height is the sum of
the elements in the row. Each bar is multi-colored, with colors corresponding
to distinct elements and showing the relative contribution each row element
makes to the total sum.
bar3(...,LineSpec) displays all bars using the color specified by LineSpec.
h = bar3(...) returns a vector of handles to patch graphics objects. bar3
creates one patch object per column in Y.
bar3h(...) and h = bar3h(...) create horizontal bars. Y determines the bar
length. The vector x is a monotonic vector defining the y-axis intervals for
horizontal bars.
Examples
This example creates six subplots showing the effects of different arguments
for bar3. The data Y is a seven-by-three matrix generated using the cool
colormap:
Y = cool(7);
subplot(3,2,1)
bar3(Y,'detached')
title('Detached')
subplot(3,2,2)
bar3(Y,0.25,'detached')
title('Width = 0.25')
subplot(3,2,3)
bar3(Y,'grouped')
title('Grouped')
subplot(3,2,4)
bar3(Y,0.5,'grouped')
title('Width = 0.5')
2-152
bar3, bar3h
subplot(3,2,5)
bar3(Y,'stacked')
title('Stacked')
subplot(3,2,6)
bar3(Y,0.3,'stacked')
title('Width = 0.3')
colormap([1 0 0;0 1 0;0 0 1])
2-153
bar3, bar3h
Detached
Width = 0.25
1
1
0.5
0.5
0
0
1
2
1
3
4
5
6
Grouped
1
0.5
0.5
0
0
2
4
4
5
6
2
3
Stacked
1.5
1.5
1
1
0.5
0.5
0
0
See Also
1
3
4
5
6
7
4
5
6
7
Width = 0.3
2
2
6
7
2
1
5
Width = 0.5
1
3
3
7
1
1
2
2
3
4
7
5
6
7
bar, LineSpec, patch
“Area, Bar, and Pie Plots” for related functions
Bar and Area Graphs for more examples
2-154
base2dec
Purpose
2base2dec
Base to decimal number conversion
Syntax
d = base2dec('strn',base)
Description
d = base2dec('strn',base) converts the string number strn of the specified
base into its decimal (base 10) equivalent. base must be an integer between 2
and 36. If 'strn' is a character array, each row is interpreted as a string in the
specified base.
Examples
The expression base2dec('212',3) converts 2123 to decimal, returning 23.
See Also
dec2base
2-155
beep
Purpose
2beep
Produce a beep sound
Syntax
beep
beep on
beep off
s = beep
Description
beep produces you computer’s default beep sound
beep on turns the beep on
beep off turn the beep off
s = beep returns the current beep mode (on or off)
2-156
besselh
Purpose
2besselh
Bessel function of the third kind (Hankel function)
Syntax
H = besselh(nu,K,Z)
H = besselh(nu,Z)
H = besselh(nu,K,Z,1)
[H,ierr] = besselh(...)
Definitions
The differential equation
z
2d
2
y
dz
2
dy
2
2
+ z ------- + ( z – ν ) y = 0
dz
where ν is a nonnegative constant, is called Bessel’s equation, and its solutions
are known as Bessel functions. J ν ( z ) and J – ν ( z ) form a fundamental set of
solutions of Bessel’s equation for noninteger ν . Y ν ( z ) is a second solution of
Bessel’s equation – linearly independent of J ν ( z ) – defined by
J ν ( z ) cos ( νπ ) – J – ν ( z )
Y ν ( z ) = ----------------------------------------------------------sin ( νπ )
The relationship between the Hankel and Bessel functions is
(1)
H ν ( z) = J ν( z) + i Y ν( z)
(2)
H ν ( z) = J ν( z) – i Y ν( z)
where J ν ( z ) is besselj, and Y ν ( z ) is bessely.
Description
(K)
H = besselh(nu,K,Z) computes the Hankel function H ν ( z ) , where K = 1 or
2, for each element of the complex array Z. If nu and Z are arrays of the same
size, the result is also that size. If either input is a scalar, besselh expands it
to the other input's size. If one input is a row vector and the other is a column
vector, the result is a two-dimensional table of function values.
H = besselh(nu,Z) uses K = 1.
(K)
H = besselh(nu,K,Z,1) scales H ν ( z ) by exp(-i*Z) if K = 1, and by
exp(+i*Z) if K = 2.
2-157
besselh
[H,ierr] = besselh(...) also returns completion flags in an array the same
size as H.
ierr
Description
0
besselh successfully computed the Hankel function for this
element.
Examples
1
Illegal arguments.
2
Overflow. Returns Inf.
3
Some loss of accuracy in argument reduction.
4
Unacceptable loss of accuracy, Z or nu too large.
5
No convergence. Returns NaN.
This example generates the contour plots of the modulus and phase of the
(1)
Hankel function H 0 ( z ) shown on page 359 of [1] Abramowitz and Stegun,
Handbook of Mathematical Functions.
It first generates the modulus contour plot
[X,Y] = meshgrid(-4:0.025:2,-1.5:0.025:1.5);
H = besselh(0,1,X+i*Y);
contour(X,Y,abs(H),0:0.2:3.2), hold on
2-158
besselh
1.5
1
0.5
0
−0.5
−1
−1.5
−4
−3
−2
−1
0
1
2
then adds the contour plot of the phase of the same function.
contour(X,Y,(180/pi)*angle(H),-180:10:180); hold off
1.5
1
0.5
0
−0.5
−1
−1.5
−4
See Also
−3
−2
−1
0
1
2
besselj, bessely, besseli, besselk
2-159
besselh
References
2-160
[1] Abramowitz, M. and I. A. Stegun, Handbook of Mathematical Functions,
National Bureau of Standards, Applied Math. Series #55, Dover Publications,
1965.
besseli
Purpose
2besseli
Modified Bessel function of the first kind
Syntax
I = besseli(nu,Z)
I = besseli(nu,Z,1)
[I,ierr] = besseli(...)
Definitions
The differential equation
2
z2
d y
dy
+ z ------- – ( z 2 + ν 2 ) y = 0
dz
d z2
where ν is a real constant, is called the modified Bessel’s equation, and its
solutions are known as modified Bessel functions.
I ν ( z ) and I – ν ( z ) form a fundamental set of solutions of the modified Bessel’s
equation for noninteger ν . I ν ( z ) is defined by
ν
I ν ( z ) =  --z- 
2
∞
∑
k=0
2 k
z 
 ---- 4
---------------------------------------k! Γ ( ν + k + 1 )
where Γ(a) is the gamma function.
K ν ( z ) is a second solution, independent of I ν ( z ) . It can be computed using
besselk.
Description
I = besseli(nu,Z) computes the modified Bessel function of the first kind,
I ν ( z ) , for each element of the array Z. The order nu need not be an integer, but
must be real. The argument Z can be complex. The result is real where Z is
positive.
If nu and Z are arrays of the same size, the result is also that size. If either input
is a scalar, it is expanded to the other input's size. If one input is a row vector
and the other is a column vector, the result is a two-dimensional table of
function values.
I = besseli(nu,Z,1) computes besseli(nu,Z).*exp(-abs(real(Z))).
2-161
besseli
[I,ierr] = besseli(...) also returns completion flags in an array the same
size as I.
ierr
Description
0
besseli succesfully computed the modified Bessel function for
this element.
Examples
1
Illegal arguments.
2
Overflow. Returns Inf.
3
Some loss of accuracy in argument reduction.
4
Unacceptable loss of accuracy, Z or nu too large.
5
No convergence. Returns NaN.
Example 1.
format long
z = (0:0.2:1)';
besseli(1,z)
ans =
0
0.10050083402813
0.20402675573357
0.31370402560492
0.43286480262064
0.56515910399249
Example 2. besseli(3:9,(0:.2,10)',1) generates the entire table on
page 423 of [1] Abramowitz and Stegun, Handbook of Mathematical Functions.
Algorithm
The besseli functions uses a Fortran MEX-file to call a library developed by
D. E. Amos [3] [4].
See Also
airy, besselh, besselj, besselk, bessely
2-162
besseli
References
[1] Abramowitz, M. and I.A. Stegun, Handbook of Mathematical Functions,
National Bureau of Standards, Applied Math. Series #55, Dover Publications,
1965, sections 9.1.1, 9.1.89 and 9.12, formulas 9.1.10 and 9.2.5.
[2] Carrier, Krook, and Pearson, Functions of a Complex Variable: Theory and
Technique, Hod Books, 1983, section 5.5.
[3] Amos, D. E., “A Subroutine Package for Bessel Functions of a Complex
Argument and Nonnegative Order,” Sandia National Laboratory Report,
SAND85-1018, May, 1985.
[4] Amos, D. E., “A Portable Package for Bessel Functions of a Complex
Argument and Nonnegative Order,” Trans. Math. Software, 1986.
2-163
besselk
Purpose
2besselk
Modified Bessel function of the second kind
Syntax
K = besselk(nu,Z)
K = besselk(nu,Z,1)
[K,ierr] = besselk(...)
Definitions
The differential equation
2
z2
d y
dy
+ z ------- – ( z 2 + ν 2 ) y = 0
dz
d z2
where ν is a real constant, is called the modified Bessel’s equation, and its
solutions are known as modified Bessel functions.
A solution K ν ( z ) of the second kind can be expressed as
I –ν ( z ) – I ν ( z )
π
K ν ( z ) =  ---  -----------------------------------2
sin ( νπ )
where I ν ( z ) and I – ν ( z ) form a fundamental set of solutions of the modified
Bessel’s equation for noninteger ν
ν
I ν ( z ) =  --z- 
2
∞
∑
k=0
2 k
z 
 ---- 4
---------------------------------------k! Γ ( ν + k + 1 )
and Γ(a) is the gamma function. K ν ( z ) is independent of I ν ( z ) .
I ν ( z ) can be computed using besseli.
Description
K = besselk(nu,Z) computes the modified Bessel function of the second kind,
K ν ( z ) , for each element of the array Z. The order nu need not be an integer, but
must be real. The argument Z can be complex. The result is real where Z is
positive.
If nu and Z are arrays of the same size, the result is also that size. If either input
is a scalar, it is expanded to the other input's size. If one input is a row vector
and the other is a column vector, the result is a two-dimensional table of
function values.
2-164
besselk
K = besselk(nu,Z,1) computes besselk(nu,Z).*exp(Z).
[K,ierr] = besselk(...) also returns completion flags in an array the same
size as K.
ierr
Description
0
besselk succesfully computed the modified Bessel function for
this element.
Examples
1
Illegal arguments.
2
Overflow. Returns Inf.
3
Some loss of accuracy in argument reduction.
4
Unacceptable loss of accuracy, Z or nu too large.
5
No convergence. Returns NaN.
Example 1.
format long
z = (0:0.2:1)';
besselk(1,z)
ans =
Inf
4.77597254322047
2.18435442473269
1.30283493976350
0.86178163447218
0.60190723019723
Example 2. besselk(3:9,(0:.2:10)',1) generates part of the table on
page 424 of [1] Abramowitz and Stegun, Handbook of Mathematical Functions.
Algorithm
The besselk function uses a Fortran MEX-file to call a library developed by
D. E. Amos [3] [4].
2-165
besselk
See Also
airy, besselh, besseli, besselj, bessely
References
[1] Abramowitz, M. and I.A. Stegun, Handbook of Mathematical Functions,
National Bureau of Standards, Applied Math. Series #55, Dover Publications,
1965, sections 9.1.1, 9.1.89 and 9.12, formulas 9.1.10 and 9.2.5.
[2] Carrier, Krook, and Pearson, Functions of a Complex Variable: Theory and
Technique, Hod Books, 1983, section 5.5.
[3] Amos, D. E., “A Subroutine Package for Bessel Functions of a Complex
Argument and Nonnegative Order,” Sandia National Laboratory Report,
SAND85-1018, May, 1985.
[4] Amos, D. E., “A Portable Package for Bessel Functions of a Complex
Argument and Nonnegative Order,” Trans. Math. Software, 1986.
2-166
besselj
Purpose
2besselj
Bessel function of the first kind
Syntax
J = besselj(nu,Z)
J = besselj(nu,Z,1)
[J,ierr] = besselj(nu,Z)
Definition
The differential equation
z
2d
2
y
dz
2
dy
2
2
+ z ------- + ( z – ν ) y = 0
dz
where ν is a real constant, is called Bessel’s equation, and its solutions are
known as Bessel functions.
J ν ( z ) and J – ν ( z ) form a fundamental set of solutions of Bessel’s equation for
noninteger ν . J ν ( z ) is defined by
J ν ( z ) =  --z-
 2
ν
∞
∑
k=0
2 k
z 
 – ---- 4
---------------------------------------k! Γ ( ν + k + 1 )
where Γ(a) is the gamma function.
Y ν ( z ) is a second solution of Bessel’s equation that is linearly independent of
J ν ( z ) . It can be computed using bessely.
Description
J = besselj(nu,Z) computes the Bessel function of the first kind, J ν ( z ) , for
each element of the array Z. The order nu need not be an integer, but must be
real. The argument Z can be complex. The result is real where Z is positive.
If nu and Z are arrays of the same size, the result is also that size. If either input
is a scalar, it is expanded to the other input's size. If one input is a row vector
and the other is a column vector, the result is a two-dimensional table of
function values.
J = besselj(nu,Z,1) computes besselj(nu,Z).*exp(-abs(imag(Z))).
[J,ierr] = besselj(nu,Z) also returns completion flags in an array the
same size as J.
2-167
besselj
ierr
Description
0
besselj succesfully computed the Bessel function for this
element.
Remarks
1
Illegal arguments.
2
Overflow. Returns Inf.
3
Some loss of accuracy in argument reduction.
4
Unacceptable loss of accuracy, Z or nu too large.
5
No convergence. Returns NaN.
The Bessel functions are related to the Hankel functions, also called Bessel
functions of the third kind,
(1)
H ν ( z) = J ν( z) + i Y ν( z)
(2)
H ν ( z) = J ν( z) – i Y ν( z)
(K )
where H ν ( z ) is besselh, J ν ( z ) is besselj, and Y ν ( z ) is bessely. The
Hankel functions also form a fundamental set of solutions to Bessel’s equation
(see besselh).
Examples
Example 1.
format long
z = (0:0.2:1)';
besselj(1,z)
ans =
0
0.09950083263924
0.19602657795532
0.28670098806392
0.36884204609417
0.44005058574493
2-168
besselj
Example 2. besselj(3:9,(0:.2:10)') generates the entire table on page 398
of [1] Abramowitz and Stegun, Handbook of Mathematical Functions.
Algorithm
The besselj function uses a Fortran MEX-file to call a library developed by
D. E. Amos [3] [4].
See Also
besselh, besseli, besselk, bessely
References
[1] Abramowitz, M. and I.A. Stegun, Handbook of Mathematical Functions,
National Bureau of Standards, Applied Math. Series #55, Dover Publications,
1965, sections 9.1.1, 9.1.89 and 9.12, formulas 9.1.10 and 9.2.5.
[2] Carrier, Krook, and Pearson, Functions of a Complex Variable: Theory and
Technique, Hod Books, 1983, section 5.5.
[3] Amos, D. E., “A Subroutine Package for Bessel Functions of a Complex
Argument and Nonnegative Order,” Sandia National Laboratory Report,
SAND85-1018, May, 1985.
[4] Amos, D. E., “A Portable Package for Bessel Functions of a Complex
Argument and Nonnegative Order,” Trans. Math. Software, 1986.
2-169
bessely
Purpose
2bessely
Bessel functions of the second kind
Syntax
Y = bessely(nu,Z)
Y = bessely(nu,Z,1)
[Y,ierr] = bessely(nu,Z)
Definition
The differential equation
z
2d
2
y
dz
2
dy
2
2
+ z ------- + ( z – ν ) y = 0
dz
where ν is a real constant, is called Bessel’s equation, and its solutions are
known as Bessel functions.
A solution Y ν ( z ) of the second kind can be expressed as
J ν ( z ) cos ( νπ ) – J – ν ( z )
Y ν ( z ) = ----------------------------------------------------------sin ( νπ )
where J ν ( z ) and J – ν ( z ) form a fundamental set of solutions of Bessel’s
equation for noninteger ν
J ν ( z ) =  --z-
 2
ν
∞
∑
k=0
2 k
z 
 – ---- 4
---------------------------------------k! Γ ( ν + k + 1 )
and Γ(a) is the gamma function. Y ν ( z ) is linearly independent of J ν ( z )
J ν ( z ) can be computed using besselj.
Description
Y = bessely(nu,Z) computes Bessel functions of the second kind, Y ν ( z ) , for
each element of the array Z. The order nu need not be an integer, but must be
real. The argument Z can be complex. The result is real where Z is positive.
If nu and Z are arrays of the same size, the result is also that size. If either input
is a scalar, it is expanded to the other input's size. If one input is a row vector
and the other is a column vector, the result is a two-dimensional table of
function values.
Y = bessely(nu,Z,1) computes bessely(nu,Z).*exp(-abs(imag(Z))).
2-170
bessely
[Y,ierr] = bessely(nu,Z) also returns completion flags in an array the
same size as Y.
ierr
Description
0
bessely succesfully computed the Bessel function for this
element.
Remarks
1
Illegal arguments.
2
Overflow. Returns Inf.
3
Some loss of accuracy in argument reduction.
4
Unacceptable loss of accuracy, Z or nu too large.
5
No convergence. Returns NaN.
The Bessel functions are related to the Hankel functions, also called Bessel
functions of the third kind,
(1)
H ν ( z) = J ν( z) + i Y ν( z)
(2)
H ν ( z) = J ν( z) – i Y ν( z)
(K )
where H ν ( z ) is besselh, J ν ( z ) is besselj, and Y ν ( z ) is bessely. The
Hankel functions also form a fundamental set of solutions to Bessel’s equation
(see besselh).
Examples
Example 1.
format long
z = (0:0.2:1)';
bessely(1,z)
ans =
-Inf
-3.32382498811185
-1.78087204427005
2-171
bessely
-1.26039134717739
-0.97814417668336
-0.78121282130029
Example 2. bessely(3:9,(0:.2:10)') generates the entire table on page 399
of [1] Abramowitz and Stegun, Handbook of Mathematical Functions.
Algorithm
The bessely function uses a Fortran MEX-file to call a library developed by
D. E Amos [3] [4].
See Also
besselh, besseli, besselj, besselk
References
[1] Abramowitz, M. and I.A. Stegun, Handbook of Mathematical Functions,
National Bureau of Standards, Applied Math. Series #55, Dover Publications,
1965, sections 9.1.1, 9.1.89 and 9.12, formulas 9.1.10 and 9.2.5.
[2] Carrier, Krook, and Pearson, Functions of a Complex Variable: Theory and
Technique, Hod Books, 1983, section 5.5.
[3] Amos, D. E., “A Subroutine Package for Bessel Functions of a Complex
Argument and Nonnegative Order,” Sandia National Laboratory Report,
SAND85-1018, May, 1985.
[4] Amos, D. E., “A Portable Package for Bessel Functions of a Complex
Argument and Nonnegative Order,” Trans. Math. Software, 1986.
2-172
beta
Purpose
2beta
Beta function
Syntax
B = beta(Z,W)
Definition
The beta function is
B ( z, w ) =
1
∫0 t z – 1 ( 1 – t ) w – 1 dt
Γ ( z )Γ ( w )
= ------------------------Γ( z + w)
where Γ ( z ) is the gamma function.
Description
B = beta(Z,W) computes the beta function for corresponding elements of
arrays Z and W. The arrays must be real and nonnegative. They must be the
same size, or either can be scalar.
Examples
In this example, which uses integer arguments,
beta(n,3)
= (n-1)!*2!/(n+2)!
= 2/(n*(n+1)*(n+2))
is the ratio of fairly small integers, and the rational format is able to recover
the exact result.
format rat
beta((0:10)',3)
ans =
1/0
1/3
1/12
1/30
1/60
1/105
1/168
1/252
1/360
1/495
1/660
2-173
beta
Algorithm
See Also
2-174
beta(z,w) = exp(gammaln(z)+gammaln(w)-gammaln(z+w))
betainc, betaln, gammaln
betainc
Purpose
2betainc
Incomplete beta function
Syntax
I = betainc(X,Z,W)
Definition
The incomplete beta function is
1
I x ( z, w ) = -------------------B ( z, w )
x
∫0 t z – 1 ( 1 – t ) w – 1 dt
where B ( z, w ) , the beta function, is defined as
B ( z, w ) =
1
∫0 t z – 1 ( 1 – t ) w – 1 dt
Γ ( z )Γ ( w )
= ------------------------Γ( z + w)
and Γ ( z ) is the gamma function.
Description
I = betainc(X,Z,W) computes the incomplete beta function for corresponding
elements of the arrays X, Z and W. The elements of X must be in the closed
interval [0,1] . The arrays Z and W must be nonnegative and real. All arrays
must be the same size, or any of them can be scalar.
Examples
format long
betainc(.5,(0:10)',3)
ans =
1.00000000000000
0.87500000000000
0.68750000000000
0.50000000000000
0.34375000000000
0.22656250000000
0.14453125000000
0.08984375000000
0.05468750000000
0.03271484375000
0.01928710937500
See Also
beta, betaln
2-175
betaln
Purpose
2betaln
Logarithm of beta function
Syntax
L = betaln(Z,W)
Description
L = betaln(Z,W) computes the natural logarithm of the beta function
log(beta(Z,W)), for corresponding elements of arrays Z and W, without
computing beta(Z,W). Since the beta function can range over very large or very
small values, its logarithm is sometimes more useful.
Z and W must be real and nonnegative. They must be the same size, or either
can be scalar.
Examples
x = 510
betaln(x,x)
ans =
-708.8616
-708.8616 is slightly less than log(realmin). Computing beta(x,x) directly
would underflow (or be denormal).
Algorithm
See Also
2-176
betaln(z,w) = gammaln(z)+gammaln(w)-gammaln(z+w)
beta, betainc, gammaln
bicg
Purpose
2bicg
BiConjugate Gradients method
Syntax
x = bicg(A,b)
bicg(A,b,tol)
bicg(A,b,tol,maxit)
bicg(A,b,tol,maxit,M)
bicg(A,b,tol,maxit,M1,M2)
bicg(A,b,tol,maxit,M1,M2,x0)
bicg(afun,b,tol,maxit,mfun1,mfun2,x0,p1,p2,...)
[x,flag] = bicg(A,b,...)
[x,flag,relres] = bicg(A,b,...)
[x,flag,relres,iter] = bicg(A,b,...)
[x,flag,relres,iter,resvec] = bicg(A,b,...)
Description
x = bicg(A,b) attempts to solve the system of linear equations A*x = b for x.
The n-by-n coefficient matrix A must be square and should be large and sparse.
The column vector b must have length n. A can be a function afun such that
afun(x) returns A*x and afun(x,'transp') returns A'*x.
If bicg converges, it displays a message to that effect. If bicg fails to converge
after the maximum number of iterations or halts for any reason, it prints a
warning message that includes the relative residual norm(b-A*x)/norm(b)
and the iteration number at which the method stopped or failed.
bicg(A,b,tol) specifies the tolerance of the method. If tol is [], then bicg
uses the default, 1e-6.
bicg(A,b,tol,maxit) specifies the maximum number of iterations. If maxit
is [], then bicg uses the default, min(n,20).
bicg(A,b,tol,maxit,M) and bicg(A,b,tol,maxit,M1,M2) use the
preconditioner M or M = M1*M2 and effectively solve the system
inv(M)*A*x = inv(M)*b for x. If M is [] then bicg applies no preconditioner.
M can be a function mfun such that mfun(x) returns M\x and mfun(x,'transp')
returns M'\x.
bicg(A,b,tol,maxit,M1,M2,x0) specifies the initial guess. If x0 is [], then
bicg uses the default, an all-zero vector.
2-177
bicg
bicg(afun,b,tol,maxit,m1fun,m2fun,x0,p1,p2,...) passes parameters
p1,p2,... to functions afun(x,p1,p2,...) and
afun(x,p1,p2,...,'transp'), and similarly to the preconditioner functions
m1fun and m2fun.
[x,flag] = bicg(A,b,...) also returns a convergence flag.
Flag
Convergence
0
bicg converged to the desired tolerance tol within maxit
iterations.
1
bicg iterated maxit times but did not converge.
2
Preconditioner M was ill-conditioned.
3
bicg stagnated. (Two consecutive iterates were the same.)
4
One of the scalar quantities calculated during bicg became
too small or too large to continue computing.
Whenever flag is not 0, the solution x returned is that with minimal norm
residual computed over all the iterations. No messages are displayed if the
flag output is specified.
[x,flag,relres] = bicg(A,b,...) also returns the relative residual
norm(b-A*x)/norm(b). If flag is 0, relres <= tol.
[x,flag,relres,iter] = bicg(A,b,...) also returns the iteration number
at which x was computed, where 0 <= iter <= maxit.
[x,flag,relres,iter,resvec] = bicg(A,b,...) also returns a vector of the
residual norms at each iteration including norm(b-A*x0).
Examples
Example 1.
n = 100;
on = ones(n,1);
A = spdiags([-2*on 4*on -on],-1:1,n,n);
b = sum(A,2);
tol = 1e-8;
2-178
bicg
maxit = 15;
M1 = spdiags([on/(-2) on],-1:0,n,n);
M2 = spdiags([4*on -on],0:1,n,n);
x = bicg(A,b,tol,maxit,M1,M2,[]);
displays this message
bicg converged at iteration 9 to a solution with relative
residual 5.3e-009
Alternatively, use this matrix-vector product function
function y = afun(x,n,transp_flag)
if (nargin > 2) & strcmp(transp_flag,'transp')
y = 4 * x;
y(1:n-1) = y(1:n-1) - 2 * x(2:n);
y(2:n) = y(2:n) - x(1:n-1);
else
y = 4 * x;
y(2:n) = y(2:n) - 2 * x(1:n-1);
y(1:n-1) = y(1:n-1) - x(2:n);
end
as input to bicg.
x1 = bicg(@afun,b,tol,maxit,M1,M2,[],n);
Example 2. This examples demonstrates the use of a preconditioner. Start
with A = west0479, a real 479-by-479 sparse matrix, and define b so that the
true solution is a vector of all ones.
load west0479;
A = west0479;
b = sum(A,2);
You can accurately solve A*x = b using backslash since A is not so large.
x = A \ b;
norm(b-A*x) / norm(b)
ans =
8.3154e-017
2-179
bicg
Now try to solve A*x = b with bicg.
[x,flag,relres,iter,resvec] = bicg(A,b)
flag =
1
relres =
1
iter =
0
The value of flag indicates that bicg iterated the default 20 times without
converging. The value of iter shows that the method behaved so badly that the
initial all-zero guess was better than all the subsequent iterates. The value of
relres supports this: relres = norm(b-A*x)/norm(b) = norm(b)/norm(b) = 1.
You can confirm that the unpreconditioned method oscillates rather wildly by
plotting the relative residuals at each iteration.
semilogy(0:20,resvec/norm(b),'-o')
xlabel('Iteration Number')
ylabel('Relative Residual')
5
10
4
Relative Residual
10
3
10
2
10
1
10
0
10
2-180
0
5
10
Iteration Number
15
20
bicg
Now, try an incomplete LU factorization with a drop tolerance of 1e-5 for the
preconditioner.
[L1,U1] = luinc(A,1e-5);
Warning: Incomplete upper triangular factor has 1 zero diagonal.
It cannot be used as a preconditioner for an iterative
method.
nnz(A), nnz(L1), nnz(U1)
ans =
1887
ans =
5562
ans =
4320
The zero on the main diagonal of the upper triangular U1 indicates that U1 is
singular. If you try to use it as a preconditioner,
[x,flag,relres,iter,resvec] = bicg(A,b,1e-6,20,L1,U1)
flag =
2
relres =
1
iter =
0
resvec =
7.0557e+005
the method fails in the very first iteration when it tries to solve a system of
equations involving the singular U1 using backslash. bicg is forced to return
the initial estimate since no other iterates were produced.
Try again with a slightly less sparse preconditioner.
[L2,U2] = luinc(A,1e-6);
2-181
bicg
nnz(L2), nnz(U2)
ans =
6231
ans =
4559
This time U2 is nonsingular and may be an appropriate preconditioner.
[x,flag,relres,iter,resvec] = bicg(A,b,1e-15,10,L2,U2)
flag =
0
relres =
2.8664e-016
iter =
8
and bicg converges to within the desired tolerance at iteration number 8.
Decreasing the value of the drop tolerance increases the fill-in of the
incomplete factors but also increases the accuracy of the approximation to the
original matrix. Thus, the preconditioned system becomes closer to
inv(U)*inv(L)*L*U*x = inv(U)*inv(L)*b, where L and U are the true LU
factors, and closer to being solved within a single iteration.
The next graph shows the progress of bicg using six different incomplete LU
factors as preconditioners. Each line in the graph is labeled with the drop
tolerance of the preconditioner used in bicg.
2-182
bicg
0
10
−5
relative residual
10
−10
10
−15
10
1e−12
1e−10
1e−6
1e−8
1e−14
0
See Also
1
2
3
4
5
iteration number
6
7
8
bicgstab, cgs, gmres, lsqr, luinc, minres, pcg, qmr, symmlq
@ (function handle), \ (backslash)
References
[1] Barrett, R., M. Berry, T. F. Chan, et al., Templates for the Solution of Linear
Systems: Building Blocks for Iterative Methods, SIAM, Philadelphia, 1994.
2-183
bicgstab
Purpose
2bicgstab
BiConjugate Gradients Stabilized method
Syntax
x = bicgstab(A,b)
bicgstab(A,b,tol)
bicgstab(A,b,tol,maxit)
bicgstab(A,b,tol,maxit,M)
bicgstab(A,b,tol,maxit,M1,M2)
bicgstab(A,b,tol,maxit,M1,M2,x0)
bicgstab(afun,b,tol,maxit,m1fun,m2fun,x0,p1,p2,...)
[x,flag] = bicgstab(A,b,...)
[x,flag,relres] = bicgstab(A,b,...)
[x,flag,relres,iter] = bicgstab(A,b,...)
[x,flag,relres,iter,resvec] = bicgstab(A,b,...)
Description
x = bicgstab(A,b) attempts to solve the system of linear equations A*x=b for
x. The n-by-n coefficient matrix A must be square and should be large and
sparse. The column vector b must have length n. A can be a function afun such
that afun(x) returns A*x.
If bicgstab converges, a message to that effect is displayed. If bicgstab fails
to converge after the maximum number of iterations or halts for any reason, a
warning message is printed displaying the relative residual
norm(b-A*x)/norm(b) and the iteration number at which the method stopped
or failed.
bicgstab(A,b,tol) specifies the tolerance of the method. If tol is [], then
bicgstab uses the default, 1e-6.
bicgstab(A,b,tol,maxit) specifies the maximum number of iterations. If
maxit is [], then bicgstab uses the default, min(n,20).
bicgstab(A,b,tol,maxit,M) and bicgstab(A,b,tol,maxit,M1,M2) use
preconditioner M or M = M1*M2 and effectively solve the system
inv(M)*A*x = inv(M)*b for x. If M is [] then bicgstab applies no
preconditioner. M can be a function that returns M\x.
bicgstab(A,b,tol,maxit,M1,M2,x0) specifies the initial guess. If x0 is [],
then bicgstab uses the default, an all zero vector.
2-184
bicgstab
bicgstab(afun,b,tol,maxit,m1fun,m2fun,x0,p1,p2,...) passes
parameters p1,p2,... to functions afun(x,p1,p2,...), m1fun(x,p1,p2,...),
and m2fun(x,p1,p2,...).
[x,flag] = bicgstab(A,b,...) also returns a convergence flag.
Flag
Convergence
0
bicgstab converged to the desired tolerance tol within
maxit iterations.
1
bicgstab iterated maxit times but did not converge.
2
Preconditioner M was ill-conditioned.
3
bicgstab stagnated. (Two consecutive iterates were the
same.)
4
One of the scalar quantities calculated during bicgstab
became too small or too large to continue computing.
Whenever flag is not 0, the solution x returned is that with minimal norm
residual computed over all the iterations. No messages are displayed if the
flag output is specified.
[x,flag,relres] = bicgstab(A,b,...) also returns the relative residual
norm(b-A*x)/norm(b). If flag is 0, relres <= tol.
[x,flag,relres,iter] = bicgstab(A,b,...) also returns the iteration
number at which x was computed, where 0 <= iter <= maxit. iter can be an
integer + 0.5, indicating convergence half way through an iteration.
[x,flag,relres,iter,resvec] = bicgstab(A,b,...) also returns a vector
of the residual norms at each half iteration, including norm(b-A*x0).
Example
Example 1. This example first solves Ax = b by providing A and the
preconditioner M1 directly as arguments. It then solves the same system using
functions that return A and the preconditioner.
A = gallery('wilk',21);
b = sum(A,2);
2-185
bicgstab
tol = 1e-12;
maxit = 15;
M1 = diag([10:-1:1 1 1:10]);
x = bicgstab(A,b,tol,maxit,M1,[],[]);
displays this message
bicgstab converged at iteration 12.5 to a solution with relative
residual 2.9e-014
Alternatively, use this matrix-vector product function
function y = afun(x,n)
y = [0;
x(1:n-1)] + [((n-1)/2:-1:0)';
(1:(n-1)/2)'] .*x + [x(2:n);
0];
and this preconditioner backsolve function
function y = mfun(r,n)
y = r ./ [((n-1)/2:-1:1)'; 1; (1:(n-1)/2)'];
as inputs to bicgstab
x1 = bicgstab(@afun,b,tol,maxit,@mfun,[],[],21);
Note that both afun and mfun must accept bicgstab's extra input n=21.
Example 2. This examples demonstrates the use of a preconditioner. Start
with A = west0479, a real 479-by-479 sparse matrix, and define b so that the
true solution is a vector of all ones.
load west0479;
A = west0479;
b = sum(A,2);
[x,flag] = bicgstab(A,b)
flag is 1 because bicgstab does not converge to the default tolerance 1e-6
within the default 20 iterations.
[L1,U1] = luinc(A,1e-5);
[x1,flag1] = bicgstab(A,b,1e-6,20,L1,U1)
2-186
bicgstab
flag1 is 2 because the upper triangular U1 has a zero on its diagonal. This
causes bicgstab to fail in the first iteration when it tries to solve a system such
as U1*y = r using backslash.
[L2,U2] = luinc(A,1e-6);
[x2,flag2,relres2,iter2,resvec2] = bicgstab(A,b,1e-15,10,L2,U2)
flag2 is 0 because bicgstab converges to the tolerance of 3.1757e-016 (the
value of relres2) at the sixth iteration (the value of iter2) when
preconditioned by the incomplete LU factorization with a drop tolerance of
1e-6. resvec2(1) = norm(b) and resvec2(13) = norm(b-A*x2). You can
follow the progress of bicgstab by plotting the relative residuals at the halfway
point and end of each iteration starting from the initial estimate (iterate
number 0).
semilogy(0:0.5:iter2,resvec2/norm(b),'-o')
xlabel('iteration number')
ylabel('relative residual')
0
10
−2
10
−4
10
−6
relative residual
10
−8
10
−10
10
−12
10
−14
10
−16
10
0
1
2
3
iteration number
4
5
6
2-187
bicgstab
See Also
bicg, cgs, gmres, lsqr, luinc, minres, pcg, qmr, symmlq
@ (function handle), \ (backslash)
References
[1] Barrett, R., M. Berry, T. F. Chan, et al., Templates for the Solution of Linear
Systems: Building Blocks for Iterative Methods, SIAM, Philadelphia, 1994.
[2] van der Vorst, H. A., “BI-CGSTAB: A fast and smoothly converging variant
of BI-CG for the solution of nonsymmetric linear systems”, SIAM J. Sci. Stat.
Comput., March 1992,Vol. 13, No. 2, pp. 631-644.
2-188
bin2dec
Purpose
2bin2dec
Binary to decimal number conversion
Syntax
bin2dec(binarystr)
Description
bin2dec(binarystr) interprets the binary string binarystr and returns the
equivalent decimal number.
Examples
bin2dec('010111') returns 23.
See Also
dec2bin
2-189
bitand
Purpose
2bitand
Bit-wise AND
Syntax
C = bitand(A,B)
Description
C = bitand(A,B) returns the bit-wise AND of two nonnegative integer
arguments A and B. To ensure the operands are integers, use the ceil, fix,
floor, and round functions.
Examples
The five-bit binary representations of the integers 13 and 27 are 01101 and
11011, respectively. Performing a bit-wise AND on these numbers yields
01001, or 9.
C = bitand(13,27)
C =
9
See Also
2-190
bitcmp, bitget, bitmax, bitor, bitset, bitshift, bitxor
bitcmp
Purpose
2bitcmp
Complement bits
Syntax
C = bitcmp(A,n)
Description
C = bitcmp(A,n) returns the bit-wise complement of A as an n-bit
floating-point integer (flint).
Example
With eight-bit arithmetic, the ones’ complement of 01100011 (99, decimal) is
10011100 (156, decimal).
C = bitcmp(99,8)
C =
156
See Also
bitand, bitget, bitmax, bitor, bitset, bitshift, bitxor
2-191
bitget
Purpose
2bitget
Get bit
Syntax
C = bitget(A,bit)
Description
C = bitget(A,bit) returns the value of the bit at position bit in A. Operand
A must be a nonnegative integer, and bit must be a number between 1 and the
number of bits in the floating-point integer (flint) representation of A (52 for
IEEE flints). To ensure the operand is an integer, use the ceil, fix, floor, and
round functions.
Example
The dec2bin function converts decimal numbers to binary. However, you can
also use the bitget function to show the binary representation of a decimal
number. Just test successive bits from most to least significant:
disp(dec2bin(13))
1101
C = bitget(13,4:-1:1)
C =
1
See Also
2-192
1
0
1
bitand, bitcmp, bitmax, bitor, bitset, bitshift, bitxor
bitmax
Purpose
2bitmax
Maximum floating-point integer
Syntax
bitmax
Description
bitmax returns the maximum unsigned floating-point integer for your
computer. It is the value when all bits are set, namely the value 2
See Also
53
– 1.
bitand, bitcmp, bitget, bitor, bitset, bitshift, bitxor
2-193
bitor
Purpose
2bitor
Bit-wise OR
Syntax
C = bitor(A,B)
Description
C = bitor(A,B) returns the bit-wise OR of two nonnegative integer
arguments A and B. To ensure the operands are integers, use the ceil, fix,
floor, and round functions.
Examples
The five-bit binary representations of the integers 13 and 27 are 01101 and
11011, respectively. Performing a bit-wise OR on these numbers yields 11111,
or 31.
C = bitor(13,27)
C =
31
See Also
2-194
bitand, bitcmp, bitget, bitmax, bitset, bitshift, bitxor
bitset
Purpose
2bitset
Set bit
Syntax
C = bitset(A,bit)
C = bitset(A,bit,v)
Description
C = bitset(A,bit) sets bit position bit in A to 1 (on). A must be a nonnegative
integer and bit must be a number between 1 and the number of bits in the
floating-point integer (flint) representation of A (52 for IEEE flints). To ensure
the operand is an integer, use the ceil, fix, floor, and round functions.
C = bitset(A,bit,v) sets the bit at position bit to the value v, which must be
either 0 or 1.
Examples
Setting the fifth bit in the five-bit binary representation of the integer 9 (01001)
yields 11001, or 25.
C = bitset(9,5)
C =
25
See Also
bitand, bitcmp, bitget, bitmax, bitor, bitshift, bitxor
2-195
bitshift
Purpose
2bitshift
Bit-wise shift
Syntax
C = bitshift(A,k,n)
C = bitshift(A,k)
Description
C = bitshift(A,k,n) returns the value of A shifted by k bits. If k>0, this is
same as a multiplication by 2k (left shift). If k<0, this is the same as a division
by 2k (right shift). An equivalent computation for this function is
C = fix(A*2^k).
If the shift causes C to overflow n bits, the overflowing bits are dropped. A must
contain nonnegative integers between 0 and BITMAX, which you can ensure by
using the ceil, fix, floor, and round functions.
C = bitshift(A,k) uses the default value of n = 53.
Examples
Shifting 1100 (12, decimal) to the left two bits yields 110000 (48, decimal).
C = bitshift(12,2)
C =
48
See Also
2-196
bitand, bitcmp, bitget, bitmax, bitor, bitset, bitxor, fix
bitxor
Purpose
2bitxor
Bit-wise XOR
Syntax
C = bitxor(A,B)
Description
C = bitxor(A,B) returns the bit-wise XOR of the two arguments A and B. Both
A and B must be integers. You can ensure this by using the ceil, fix, floor,
and round functions.
Examples
The five-bit binary representations of the integers 13 and 27 are 01101 and
11011, respectively. Performing a bit-wise XOR on these numbers yields 10110,
or 22.
C = bitxor(13,27)
C =
22
See Also
bitand, bitcmp, bitget, bitmax, bitor, bitset, bitshift
2-197
blanks
Purpose
2blanks
A string of blanks
Syntax
blanks(n)
Description
blanks(n) is a string of n blanks.
Examples
blanks is useful with the display function. For example,
disp(['xxx' blanks(20) 'yyy'])
displays twenty blanks between the strings 'xxx' and 'yyy'.
disp(blanks(n)') moves the cursor down n lines.
See Also
2-198
clc, format, home
blkdiag
Purpose
2blkdiag
Construct a block diagonal matrix from input arguments
Syntax
out = blkdiag(a,b,c,d,...)
Description
out = blkdiag(a,b,c,d,...) , where a, b, c, d, ... are matrices, outputs a
block diagonal matrix of the form
a
0
0
0
0
0
b
0
0
0
0
0
c
0
0
0
0
0
d
0
0
0
0
0
…
The input matrices do not have to be square, nor do they have to be of equal
size.
Note blkdiag works not only for matrices, but for any MATLAB objects that
support horzcat and vertcat operations.
See Also
diag, horzcat, vertcat
2-199
box
Purpose
2box
Display axes border
Syntax
box on
box off
box
box(axes_handle,...)
Description
box on displays the boundary of the current axes.
box off does not display the boundary of the current axes.
box toggles the visible state of the current axes’ boundary.
box(axes_handle,...) uses the axes specified by axes_handle instead of the
current axes.
Algorithm
The box function sets the axes Box property to on or off.
See Also
axes, grid
“Axes Operations” for related functions
2-200
break
Purpose
2break
Terminate execution of a for loop or while loop
Syntax
break
Description
break terminates the execution of a for or while loop. Statements in the loop
that appear after the break statement, are not executed.
In nested loops, break exits only from the loop in which it occurs. Control
passes to the statement that follows the end of that loop.
Remarks
break is not defined outside of a for or while loop. Use return in this context
instead.
Examples
The example below shows a while loop that reads the contents of the file fft.m
into a MATLAB character array. A break statement is used to exit the while
loop when the first empty line is encountered. The resulting character array
contains the M-file help for the fft program.
fid = fopen('fft.m','r');
s = '';
while ~feof(fid)
line = fgetl(fid);
if isempty(line), break, end
s = strvcat(s,line);
end
disp(s)
See Also
for, while, end, continue, return
2-201
brighten
Purpose
Syntax
Description
2brighten
Brighten or darken colormap
brighten(beta)
brighten(h,beta)
newmap = brighten(beta)
newmap = brighten(cmap,beta)
brighten increases or decreases the color intensities in a colormap. The
modified colormap is brighter if 0 < beta < 1 and darker if –1 < beta < 0.
brighten(beta) replaces the current colormap with a brighter or darker
colormap of essentially the same colors. brighten(beta), followed by
brighten(–beta), where beta < 1, restores the original map.
brighten(h,beta) brightens all objects that are children of the figure having
the handle h.
newmap = brighten(beta) returns a brighter or darker version of the current
colormap without changing the display.
newmap = brighten(cmap,beta) returns a brighter or darker version of the
colormap cmap without changing the display.
Examples
Brighten and then darken the current colormap:
beta = .5; brighten(beta);
beta = —.5; brighten(beta);
Algorithm
The values in the colormap are raised to the power of gamma, where gamma is
 1 – β,
γ=  1
------------1 + β,
β>0
β≤0
brighten has no effect on graphics objects defined with true color.
See Also
colormap, rgbplot
“Color Operations” for related functions
2-202
brighten
Altering Colormaps for more information
2-203
builtin
Purpose
2builtin
Execute builtin function from overloaded method
Syntax
builtin(function,x1,...,xn)
[y1,..,yn] = builtin(function,x1,...,xn)
Description
builtin is used in methods that overload builtin functions to execute the
original builtin function. If function is a string containing the name of a
builtin function, then
builtin(function,x1,...,xn) evaluates that function at the given
arguments.
[y1,..,yn] = builtin(function,x1,...,xn) returns multiple output
arguments.
Remarks
builtin(...) is the same as feval(...) except that it calls the original builtin
version of the function even if an overloaded one exists. (For this to work you
must never overload builtin.)
See Also
feval
2-204
bvp4c
Purpose
2bvp4c
Solve two-point boundary value problems (BVPs) for ordinary differential
equations
Syntax
sol = bvp4c(odefun,bcfun,solinit)
sol = bvp4c(odefun,bcfun,solinit,options)
sol = bvp4c(odefun,bcfun,solinit,options,p1,p2...)
Arguments
odefun
A function that evaluates the differential equations f ( x, y ) . It can
have the form
dydx
dydx
dydx
dydx
=
=
=
=
odefun(x,y)
odefun(x,y,p1,p2,...)
odefun(x,y,parameters)
odefun(x,y,parameters,p1,p2,...)
where x is a scalar corresponding to x , and y is a column vector
corresponding to y . parameters is a vector of unknown
parameters, and p1,p2,... are known parameters. The output
dydx is a column vector.
bcfun
A function that computes the residual in the boundary conditions
bc ( y ( a ), y ( b ) ) . It can have the form
res
res
res
res
=
=
=
=
bcfun(ya,yb)
bcfun(ya,yb,p1,p2,...)
bcfun(ya,yb,parameters)
bcfun(ya,yb,parameters,p1,p2,...)
where ya and yb are column vectors corresponding to y ( a ) and
y ( b ) . parameters is a vector of unknown parameters, and
p1,p2,... are known parameters. The output res is a column
vector.
solinit
A structure with fields:
x
Ordered nodes of the initial mesh. Boundary
conditions are imposed at a = solinit.x(1) and
b = solinit.x(end).
y
Initial guess for the solution such that
solinit.y(:,i) is a guess for the solution at the
node solinit.x(i).
2-205
bvp4c
parameters
Optional. A vector that provides an initial guess for
unknown parameters.
The structure can have any name, but the fields must be named x,
y, and parameters. You can form solinit with the helper function
bvpinit. See bvpinit for details.
options
Optional integration argument. A structure you create using the
bvpset function. See bvpset for details.
p1,p2... Optional. Known parameters that the solver passes to odefun,
bcfun, and all the functions specified in options.
Description
sol = bvp4c(odefun,bcfun,solinit) integrates a system of ordinary
differential equations of the form
y′ = f ( x, y )
on the interval [a,b] subject to general two-point boundary conditions
bc ( y ( a ), y ( b ) ) = 0
The bvp4c solver can also find unknown parameters p for problems of the form
y′ = f ( x, y, p )
bc ( y ( a ), y ( b ), p ) = 0
where p corresponds to parameters. You provide bvp4c an initial guess for any
unknown parameters in solinit.parameters. The bvp4c solver returns the
final values of these unknown parameters in sol.parameters.
bvp4c produces a solution that is continuous on [a,b] and has a continuous first
derivative there. Use the function deval and the output sol of bvp4c to
evaluate the solution at specific points xint in the interval [a,b].
sxint = deval(sol,xint)
The structure sol returned by bvp4c has the following fields:
2-206
sol.x
Mesh selected by bvp4c
sol.y
Approximation to y ( x ) at the mesh points of sol.x
sol.yp
Approximation to y′ ( x ) at the mesh points of sol.x
bvp4c
sol.parameters
Values returned by bvp4c for the unknown parameters,
if any
sol.solver
'bvp4c'
The structure sol can have any name, and bvp4c creates the fields x, y, yp,
parameters, and solver.
sol = bvp4c(odefun,bcfun,solinit,options) solves as above with default
integration properties replaced by the values in options, a structure created
with the bvpset function. See bvpset for details.
sol = bvp4c(odefun,bcfun,solinit,options,p1,p2...) passes constant
known parameters, p1, p2, ..., to odefun, bcfun, and all the functions the user
specifies in options. Use options = [] as a placeholder if no options are set.
Examples
Example 1. Boundary value problems can have multiple solutions and one
purpose of the initial guess is to indicate which solution you want. The second
order differential equation
y′′ + y = 0
has exactly two solutions that satisfy the boundary conditions
y(0) = 0
y ( 4 ) = –2
Prior to solving this problem with bvp4c, you must write the differential
equation as a system of two first order ODEs
y1 ′ = y2
y2 ′ = – y1
Here y 1 = y and y 2 = y′ . This system has the required form
y′ = f ( x, y )
bc ( y ( a ), y ( b ) ) = 0
The function f and the boundary conditions bc are coded in MATLAB as
functions twoode and twobc.
2-207
bvp4c
function dydx = twoode(x,y)
dydx = [ y(2)
-abs(y(1))];
function res = twobc(ya,yb)
res = [ ya(1)
yb(1) + 2];
Form a guess structure consisting of an initial mesh of five equally spaced
points in [0,4] and a guess of constant values y 1( x) ≡ 1 and y 2( x) ≡ 0 with the
command
solinit = bvpinit(linspace(0,4,5),[1 0]);
Now solve the problem with
sol = bvp4c(@twoode,@twobc,solinit);
Evaluate the numerical solution at 100 equally spaced points and plot y ( x )
with
x = linspace(0,4);
y = deval(sol,x);
plot(x,y(1,:));
2.5
2
1.5
1
0.5
0
−0.5
−1
−1.5
−2
0
2-208
0.5
1
1.5
2
2.5
3
3.5
4
bvp4c
You can obtain the other solution of this problem with the initial guess
solinit = bvpinit(linspace(0,4,5),[-1 0]);
2.5
2
1.5
1
0.5
0
−0.5
−1
−1.5
−2
0
0.5
1
1.5
2
2.5
3
3.5
4
Example 2. This boundary value problem involves an unknown parameter.
The task is to compute the fourth ( q = 5 ) eigenvalue λ of Mathieu's equation
y′′ + ( λ – 2 q cos 2x ) y = 0
Because the unknown parameter λ is present, this second order differential
equation is subject to three boundary conditions
y′ ( 0 ) = 0
y′ ( π ) = 0
y(0) = 1
It is convenient to use subfunctions to place all the functions required by bvp4c
in a single M-file.
function mat4bvp
lambda = 15;
solinit = bvpinit(linspace(0,pi,10),@mat4init,lambda);
sol = bvp4c(@mat4ode,@mat4bc,solinit);
2-209
bvp4c
fprintf('The fourth eigenvalue is approximately %7.3f.\n',...
sol.parameters)
xint = linspace(0,pi);
Sxint = deval(sol,xint);
plot(xint,Sxint(1,:))
axis([0 pi -1 1.1])
title('Eigenfunction of Mathieu''s equation.')
xlabel('x')
ylabel('solution y')
% -----------------------------------------------------------function dydx = mat4ode(x,y,lambda)
q = 5;
dydx = [ y(2)
-(lambda - 2*q*cos(2*x))*y(1) ];
% -----------------------------------------------------------function res = mat4bc(ya,yb,lambda)
res = [ ya(2)
yb(2)
ya(1)-1 ];
% -----------------------------------------------------------function yinit = mat4init(x)
yinit = [ cos(4*x)
-4*sin(4*x) ];
The differential equation (converted to a first order system) and the boundary
conditions are coded as subfunctions mat4ode and mat4bc, respectively.
Because unknown parameters are present, these functions must accept three
input arguments, even though some of the arguments are not used.
The guess structure solinit is formed with bvpinit. An initial guess for the
solution is supplied in the form of a function mat4init. We chose y = cos 4x
because it satisfies the boundary conditions and has the correct qualitative
behavior (the correct number of sign changes). In the call to bvpinit, the third
argument (lambda = 15) provides an initial guess for the unknown parameter
λ.
2-210
bvp4c
After the problem is solved with bvp4c, the field sol.parameters returns the
value λ = 17.097 , and the plot shows the eigenfunction associated with this
eigenvalue.
Eigenfunction of Mathieu’s equation.
1
0.8
0.6
solution y
0.4
0.2
0
−0.2
−0.4
−0.6
−0.8
−1
0
Algorithms
0.5
1
1.5
x
2
2.5
3
bvp4c is a finite difference code that implements the three-stage Lobatto IIIa
formula. This is a collocation formula and the collocation polynomial provides
a C1-continuous solution that is fourth order accurate uniformly in [a,b]. Mesh
selection and error control are based on the residual of the continuous solution.
See Also
@ (function_handle), bvpget, bvpinit, bvpset, deval
References
[1] Shampine, L.F., M.W. Reichelt, and J. Kierzenka, “Solving Boundary Value
Problems for Ordinary Differential Equations in MATLAB with bvp4c,”
available at ftp://ftp.mathworks.com/pub/doc/papers/bvp/.
2-211
bvpget
Purpose
2bvpget
Extract properties from the options structure created with bvpset
Syntax
val = bvpget(options,'name')
val = bvpget(options,'name',default)
Description
val = bvpget(options,'name') extracts the value of the named property
from the structure options, returning an empty matrix if the property value is
not specified in options. It is sufficient to type only the leading characters that
uniquely identify the property. Case is ignored for property names. [] is a valid
options argument.
val = bvpget(options,'name',default) extracts the named property as
above, but returns val = default if the named property is not specified in
options. For example,
val = bvpget(opts,'RelTol',1e-4);
returns val = 1e-4 if the RelTol is not specified in opts.
See Also
2-212
bvp4c, bvpinit, bvpset, deval
bvpinit
Purpose
Syntax
Description
2bvpinit
Form the initial guess for bvp4c
solinit
solinit
solinit
solinit
=
=
=
=
bvpinit(x,v)
bvpinit(x,v,parameters)
bvpinit(sol,[anew bnew])
bvpinit(sol,[anew bnew],parameters)
solinit = bvpinit(x,v) forms the initial guess for bvp4c in common
circumstances.
x is a vector that specifies an initial mesh. If you want to solve the boundary
value problem (BVP) on [ a, b ] , then specify x(1) as a and x(end) as b . The
function bvp4c adapts this mesh to the solution, so often a guess like
x = linspace(a,b,10) suffices. However, in difficult cases, you must place
mesh points where the solution changes rapidly. The entries of x must be
ordered and distinct, so if a < b , then x(1) < x(2) < ... < x(end), and
similarly for a > b .
v is a guess for the solution. It can be either a vector, or a function:
• Vector – For each component of the solution, bvpinit replicates the
corresponding element of the vector as a constant guess across all mesh
points. That is, v(i) is a constant guess for the ith component y(i,:) of the
solution at all the mesh points in x.
• Function – For a given mesh point, the function must return a vector whose
elements are guesses for the corresponding components of the solution. The
function must be of the form
y = guess(x)
where x is a mesh point and y is a vector whose length is the same as the
number of components in the solution. For example, if you use @guess,
bvpinit calls this function for each mesh point y(:,j) = guess(x(j)).
solinit = bvpinit(x,v,parameters) indicates that the BVP involves
unknown parameters. Use the vector parameters to provide a guess for all
unknown parameters.
2-213
bvpinit
solinit is a structure with the following fields. The structure can have any
name, but the fields must be named x, y, and parameters.
x
Ordered nodes of the initial mesh.
y
Initial guess for the solution with solinit.y(:,i) a guess for
the solution at the node solinit.x(i).
parameters
Optional. A vector that provides an initial guess for unknown
parameters.
solinit = bvpinit(sol,[anew bnew]) forms an initial guess on the interval
[anew bnew] from a solution sol on an interval [ a, b ] . The new interval must
be larger than the previous one, so either anew <= a < b <= bnew or
anew >= a > b >= bnew. The solution sol is extrapolated to the new interval.
If sol contains parameters, they are copied to solinit.
solinit = bvpinit(sol,[anew bnew],parameters) forms solinit as
described above, but uses parameters as a guess for unknown parameters in
solinit.
See Also
2-214
@ (function_handle), bvp4c, bvpget, bvpset, deval
bvpset
Purpose
2bvpset
Create/alter boundary value problem (BVP) options structure
Syntax
options = bvpset('name1',value1,'name2',value2,...)
options = bvpset(oldopts'name1',value1,...)
options = bvpset(oldopts,newopts)
bvpset
Description
options = bvpset('name1',value1,'name2',value2,...) creates a
structure options in which the named properties have the specified values.
Any unspecified properties have default values. It is sufficient to type only the
leading characters that uniquely identify the property. Case is ignored for
property names.
options = bvpset(oldopts,'name1',value1,...) alters an existing options
structure oldopts.
options = bvpset(oldopts,newopts) combines an existing options structure
oldopts with a new options structure newopts. Any new properties overwrite
corresponding old properties.
bvpset with no input arguments displays all property names and their possible
values.
BVP Properties
These properties are available.
Property
Value
Description
RelTol
Positive scalar
{1e-3}
A relative tolerance that applies to all components of the
residual vector. The computed solution S ( x ) is the exact
solution of S′( x) = F ( x, S ( x )) + res ( x ) . On each
subinterval of the mesh, the residual res ( x ) satisfies
(res(i)/max(abs(F(i)),AbsTol(i)/RelTol)) ≤ RelTol
AbsTol
Positive scalar or
vector {1e-6}
An absolue tolerance that applies to all components of the
residual vector. Elements of a vector of tolerances apply to
corresponding components of the residual vector.
2-215
bvpset
Property
Value
Description
Vectorized
on | {off}
Set on to inform bvp4c that you have coded the ODE
function F so that F([x1 x2 ...],[y1 y2 ...]) returns
[F(x1,y1) F(x2,y2) ...]. That is, your ODE function
can pass to the solver a whole array of column vectors at
once. This allows the solver to reduce the number of
function evaluations, and may significantly reduce
solution time.
SingularTerm
Matrix
Singular term of singular BVPs.
Set to the constant matrix S for equations of the form
y
y′ = S --- + f ( x, y, p )
x
that are posed on the interval [ 0, b ] where b > 0 .
FJacobian
Function |
matrix | cell
array
Analytic partial derivatives of ODEFUN.
For example, when solving y′ = f ( x, y ), set this property
to @FJAC if DFDY = FJAC(X,Y) evaluates the Jacobian of f
with respect to y . If the problem involves unknown
parameters p , [DFDY,DFDP] = FJAC(X,Y,P) must also
return the partial derivative of f with respect to p . For
problems with constant partial derivatives, set this
property to the value of DFDY or to a cell array
{DFDY,DFDP}.
BCJacobian
Function |
cell array
Analytic partial derivatives of BCFUN.
For example, for boundary conditions bc( ya, yb) = 0 , set
this property to @BCJAC if
[DBCDYA,DBCDYB] = BCJAC(YA,YB) evaluates the partial
derivatives of bc with respect to ya and to yb . If the
problem involves unknown parameters p , then
[DBCDYA,DBCDYB,DBCDP] = BCJAC(YA,YB,P) must also
return the partial derivative of bc with respect to p . For
problems with constant partial derivatives, set this
property to a cell array {DBCDYA,DBCDYB} or
{DBCDYA,DBCDYB,DBCDP}.
2-216
bvpset
Property
Value
Description
Nmax
positive integer
{floor(1000/n)}
Maximum number of mesh points allowed.
Stats
on | {off}
Display computational cost statistics.
See Also
@ (function_handle), bvp4c, bvpget, bvpinit, deval
2-217
bvpval
Purpose
2bvpval
Evaluate the numerical solution of a boundary value problem (BVP) using the
output of bvp4c
Note bvpval is obsolete and will be removed in the future. Please use deval
instead.
Syntax
sxint = bvpval(sol,xint)
Description
sxint = bvpval(sol,xint) uses sol, the output of bvp4c, to evaluate the
solution of a boundary value problem at each element of the vector xint. For
each i, sxint(:,i) is the solution corresponding to xint(i).
See Also
bvp4c, bvpinit, bvpget, bvpset
2-218
calendar
Purpose
Syntax
2calendar
Calendar
c = calendar
c = calendar(d)
c = calendar(y,m)
calendar(...)
Description
c = calendar returns a 6-by-7 matrix containing a calendar for the current
month. The calendar runs Sunday (first column) to Saturday.
c = calendar(d), where d is a serial date number or a date string, returns a
calendar for the specified month.
c = calendar(y,m), where y and m are integers, returns a calendar for the
specified month of the specified year.
calendar(...) displays the calendar on the screen.
Examples
The command:
calendar(1957,10)
reveals that the Space Age began on a Friday (on October 4, 1957, when
Sputnik 1 was launched).
S
0
6
13
20
27
0
See Also
M
0
7
14
21
28
0
Tu
1
8
15
22
29
0
Oct 1957
W
Th
2
3
9
10
16
17
23
24
30
31
0
0
F
4
11
18
25
0
0
S
5
12
19
26
0
0
datenum
2-219
camdolly
Purpose
2camdolly
Move the camera position and target
Syntax
camdolly(dx,dy,dz)
camdolly(dx,dy,dz,'targetmode')
camdolly(dx,dy,dz,'targetmode','coordsys')
camdolly(axes_handle,...)
Description
camdolly moves the camera position and the camera target by the specified
amounts.
camdolly(dx,dy,dz) moves the camera position and the camera target by the
specified amounts (see “Coordinate Systems”).
camdolly(dx,dy,dz,'targetmode') The targetmode argument can take on
two values that determine how MATLAB moves the camera:
• movetarget (default) – move both the camera and the target
• fixtarget – move only the camera
camdolly(dx,dy,dz,'targetmode','coordsys') The coordsys argument can
take on three values that determine how MATLAB interprets dx, dy, and dz:
Coordinate Systems
• camera (default) – move in the camera’s coordinate system. dx moves
left/right, dy moves down/up, and dz moves along the viewing axis. The units
are normalized to the scene.
For example, setting dx to 1 moves the camera to the right, which pushes the
scene to the left edge of the box formed by the axes position rectangle. A
negative value moves the scene in the other direction. Setting dz to 0.5
moves the camera to a position halfway between the camera position and the
camera target
• pixels – interpret dx and dy as pixel offsets. dz is ignored.
• data – interpret dx, dy, and dz as offesets in axes data coordinates.
camdolly(axes_handle,...) operates on the axes identified by the first
argument, axes_handle. When you do not specify an axes handle, camdolly
operates on the current axes.
2-220
camdolly
Remarks
camdolly sets the axes CameraPosition and CameraTarget properties, which
in turn causes the CameraPositionMode and CameraTargetMode properties to
be set to manual.
Examples
This example moves the camera along the x- and y-axes in a series of steps.
surf(peaks)
axis vis3d
t = 0:pi/20:2*pi;
dx = sin(t)./40;
dy = cos(t)./40;
for i = 1:length(t);
camdolly(dx(i),dy(i),0)
drawnow
end
See Also
axes, campos, camproj, camtarget, camup, camva
The axes properties CameraPosition, CameraTarget, CameraUpVector,
CameraViewAngle, Projection
“Controlling the Camera Viewpoint” for related functions
See Defining Scenes with Camera Graphics for more information on camera
properties.
2-221
camlight
Purpose
2camlight
Create or move a light object in camera coordinates
Syntax
camlight headlight
camlight right
camlight left
camlight
camlight(az,el)
camlight(...‘style’)
camlight(light_handle,...)
light_handle = camlight(...)
Description
camlight('headlight') creates a light at the camera position.
camlight('right') creates a light right and up from camera.
camlight('left') creates a light left and up from camera.
camlight with no arguments is the same as camlight('right').
camlight(az,el) creates a light at the specified azimuth (az) and elevation
(el) with respect to the camera position. The camera target is the center of
rotation and az and el are in degrees.
camlight(...,'style') The style argument can take on the two values:
• local (default) – the light is a point source that radiates from the location in
all directions.
• infinite – the light shines in parallel rays.
camlight(light_handle,...) uses the light specified in light_handle.
light_handle = camlight(...) returns the light’s handle.
Remarks
camlight sets the light object Position and Style properties. A light created
with camlight will not track the camera. In order for the light to stay in a
constant position relative to the camera, you must call camlight whenever you
move the camera.
2-222
camlight
Examples
This example creates a light positioned to the left of the camera and then
repositions the light each time the camera is moved:
surf(peaks)
axis vis3d
h = camlight('left');
for i = 1:20;
camorbit(10,0)
camlight(h,'left')
drawnow;
end
See Also
light, lightangle
“Lighting” for related functions
Lighting as a Visualization Tool for more information on using lights
2-223
camlookat
Purpose
2camlookat
Position the camera to view an object or group of objects
Syntax
camlookat(object_handles)
camlookat(axes_handle)
camlookat
Description
camlookat(object_handles) views the objects identified in the vector
object_handles. The vector can contain the handles of axes children.
camlookat(axes_handle) views the objects that are children of the axes
identified by axes_handle.
camlookat views the objects that are in the current axes.
Remarks
camlookat moves the camera position and camera target while preserving the
relative view direction and camera view angle. The object (or objects) being
viewed roughly fill the axes position rectangle.
camlookat sets the axes CameraPosition and CameraTarget properties.
Examples
This example creates three spheres at different locations and then
progressively positions the camera so that each sphere is the object around
which the scene is composed:
[x y z] = sphere;
s1 = surf(x,y,z);
hold on
s2 = surf(x+3,y,z+3);
s3 = surf(x,y,z+6);
daspect([1 1 1])
view(30,10)
camproj perspective
camlookat(gca) % Compose
pause(2)
camlookat(s1) % Compose
pause(2)
camlookat(s2) % Compose
pause(2)
camlookat(s3) % Compose
pause(2)
camlookat(gca)
2-224
the scene around the current axes
the scene around sphere s1
the scene around sphere s2
the scene around sphere s3
camlookat
See Also
campos, camtarget
“Controlling the Camera Viewpoint” for related functions
Defining Scenes with Camera Graphics for more information
2-225
camorbit
Purpose
2camorbit
Rotate the camera position around the camera target
Syntax
camorbit(dtheta,dphi)
camorbit(dtheta,dphi,'coordsys')
camorbit(dtheta,dphi,'coordsys','direction')
camorbit(axes_handle,...)
Description
camorbit(dtheta,dphi) rotates the camera position around the camera target
by the amounts specified in dtheta and dphi (both in degrees). dtheta is the
horizontal rotation and dphi is the vertical rotation.
camorbit(dtheta,dphi,'coordsys') The coordsys argument determines the
center of rotation. It can take on two values:
• data (default) – rotate the camera around an axis defined by the camera
target and the direction (default is the positive z direction).
• camera – rotate the camera about the point defined by the camera target.
camorbit(dtheta,dphi,'coordsys','direction') The direction
argument, in conjunction with the camera target, defines the axis of rotation
for the data coordinate system. Specify direction as a three-element vector
containing the x, y, and z-components of the direction or one of the characters,
x, y, or z, to indicate [1 0 0], [0 1 0], or [0 0 1] respectively.
camorbit(axes_handle,...) operates on the axes identified by the first
argument, axes_handle. When you do not specify an axes handle, camorbit
operates on the current axes.
Examples
Compare rotation in the two coordinate systems with these for loops. The first
rotates the camera horizontally about a line defined by the camera target point
and a direction that is parallel to the y-axis. Visualize this rotation as a cone
formed with the camera target at the apex and the camera position forming the
base:
surf(peaks)
axis vis3d
for i=1:36
camorbit(10,0,'data',[0 1 0])
drawnow
2-226
camorbit
end
Rotation in the camera coordinate system orbits the camera around the axes
along a circle while keeping the center of a circle at the camera target.
surf(peaks)
axis vis3d
for i=1:36
camorbit(10,0,'camera')
drawnow
end
See Also
axes, axis('vis3d'), camdolly, campan, camzoom, camroll
“Controlling the Camera Viewpoint” for related functions
Defining Scenes with Camera Graphics for more information
2-227
campan
Purpose
2campan
Rotate the camera target around the camera position
Syntax
campan(dtheta,dphi)
campan(dtheta,dphi,'coordsys')
campan(dtheta,dphi,'coordsys','direction')
campan(axes_handle,...)
Description
campan(dtheta,dphi) rotates the camera target around the camera position
by the amounts specified in dtheta and dphi (both in degrees). dtheta is the
horizontal rotation and dphi is the vertical rotation.
campan(dtheta,dphi,'coordsys') The coordsys argument determines the
center of rotation. It can take on two values:
• data (default) – rotate the camera target around an axis defined by the
camera position and the direction (default is the positive z direction)
• camera – rotate the camera about the point defined by the camera target.
campan(dtheta,dphi,'coordsys','direction') The direction argument,
in conjunction with the camera position, defines the axis of rotation for the data
coordinate system. Specify direction as a three-element vector containing the
x, y, and z-components of the direction or one of the characters, x, y, or z, to
indicate [1 0 0], [0 1 0], or [0 0 1] respectively.
campan(axes_handle,...) operates on the axes identified by the first
argument, axes_handle. When you do not specify an axes handle, campan
operates on the current axes.
See Also
axes, camdolly, camorbit, camtarget, camzoom, camroll
“Controlling the Camera Viewpoint” for related functions
Defining Scenes with Camera Graphics for more information
2-228
campos
Purpose
2campos
Set or query the camera position
Syntax
campos
campos([camera_position])
campos('mode')
campos('auto'
campos('manual')
campos(axes_handle,...)
Description
campos with no arguments returns the camera position in the current axes.
campos([camera_position]) sets the position of the camera in the current
axes to the specified value. Specify the position as a three-element vector
containing the x-, y-, and z-coordinates of the desired location in the data units
of the axes.
campos('mode') returns the value of the camera position mode, which can be
either auto (the default) or manual.
campos('auto') sets the camera position mode to auto.
campos('manual') sets the camera position mode to manual.
campos(axes_handle,...) performs the set or query on the axes identified by
the first argument, axes_handle. When you do not specify an axes handle,
campos operates on the current axes.
Remarks
campos sets or queries values of the axes CameraPosition and
CameraPositionMode properties. The camera position is the point in the
Cartesian coordinate system of the axes from which you view the scene.
Examples
This example moves the camera along the x-axis in a series of steps:
surf(peaks)
axis vis3d off
for x = −200:5:200
campos([x,5,10])
drawnow
end
2-229
campos
See Also
axis, camproj, camtarget, camup, camva
The axes properties CameraPosition, CameraTarget, CameraUpVector,
CameraViewAngle, Projection
“Controlling the Camera Viewpoint” for related functions
Defining Scenes with Camera Graphics for more information
2-230
camproj
Purpose
2camproj
Set or query the projection type
Syntax
camproj
camproj(projection_type)
camproj(axes_handle,...)
Description
The projection type determines whether MATLAB uses a perspective or
orthographic projection for 3-D views.
camproj with no arguments returns the projection type setting in the current
axes.
camproj('projection_type') sets the projection type in the current axes to
the specified value. Possible values for projection_type are: orthographic
and perspective.
camproj(axes_handle,...) performs the set or query on the axes identified by
the first argument, axes_handle. When you do not specify an axes handle,
camproj operates on the current axes.
Remarks
camproj sets or queries values of the axes object Projection property.
See Also
campos, camtarget, camup, camva
The axes properties CameraPosition, CameraTarget, CameraUpVector,
CameraViewAngle, Projection
“Controlling the Camera Viewpoint” for related functions
Defining Scenes with Camera Graphics for more information
2-231
camroll
Purpose
2camroll
Rotate the camera about the view axis
Syntax
camroll(dtheta)
camroll(axes_handle,dtheta)
Description
camroll(dtheta) rotates the camera around the camera viewing axis by the
amounts specified in dtheta (in degrees). The viewing axis is defined by the
line passing through the camera position and the camera target.
camroll(axes_handle,dtheta) operates on the axes identified by the first
argument, axes_handle. When you do not specify an axes handle, camroll
operates on the current axes.
Remarks
camroll set the axes CameraUpVector property and thereby also sets the
CameraUpVectorMode property to manual.
See Also
axes, axis('vis3d'), camdolly, camorbit, camzoom, campan
“Controlling the Camera Viewpoint” for related functions
Defining Scenes with Camera Graphics for more information
2-232
camtarget
Purpose
2camtarget
Set or query the location of the camera target
Syntax
camtarget
camtarget([camera_target])
camtarget('mode')
camtarget('auto')
camtarget('manual')
camtarget(axes_handle,...)
Description
The camera target is the location in the axes that the camera points to. The
camera remains oriented toward this point regardless of its position.
camtarget with no arguments returns the location of the camera target in the
current axes.
camtarget([camera_target]) sets the camera target in the current axes to
the specified value. Specify the target as a three-element vector containing the
x-, y-, and z-coordinates of the desired location in the data units of the axes.
camtarget('mode') returns the value of the camera target mode, which can be
either auto (the default) or manual.
camtarget('auto') sets the camera target mode to auto.
camtarget('manual') sets the camera target mode to manual.
camtarget(axes_handle,...) performs the set or query on the axes identified
by the first argument, axes_handle. When you do not specify an axes handle,
camtarget operates on the current axes.
Remarks
camtarget sets or queries values of the axes object Cameratarget and
CameraTargetMode properties.
When the camera target mode is auto, MATLAB positions the camera target
at the center of the axes plot box.
Examples
This example moves the camera position and the camera target along the
x-axis in a series of steps:
surf(peaks);
2-233
camtarget
axis vis3d
xp = linspace(−150,40,50);
xt = linspace(25,50,50);
for i=1:50
campos([xp(i),25,5]);
camtarget([xt(i),30,0])
drawnow
end
See Also
axis, camproj, campos, camup, camva
The axes properties CameraPosition, CameraTarget, CameraUpVector,
CameraViewAngle, Projection
“Controlling the Camera Viewpoint” for related functions
Defining Scenes with Camera Graphics for more information
2-234
camup
Purpose
2camup
Set or query the camera up vector
Syntax
camup
camup([up_vector])
camup('mode')
camup('auto')
camup('manual')
camup(axes_handle,...)
Description
The camera up vector specifies the direction that is oriented up in the scene.
camup with no arguments returns the camera up vector setting in the current
axes.
camup([up_vector]) sets the up vector in the current axes to the specified
value. Specify the up vector as x-, y-, and z-components. See Remarks.
camup('mode') returns the current value of the camera up vector mode, which
can be either auto (the default) or manual.
camup('auto') sets the camera up vector mode to auto. In auto mode,
MATLAB uses a value for the up vector of [0 1 0] for 2-D views. This means
the z-axis points up.
camup('manual') sets the camera up vector mode to manual. In manual mode,
MATLAB does not change the value of the camera up vector.
camup(axes_handle,...) performs the set or query on the axes identified by
the first argument, axes_handle. When you do not specify an axes handle,
camup operates on the current axes.
Remarks
camup sets or queries values of the axes object CameraUpVector and
CameraUpVectorMode properties.
Specify the camera up vector as the x-, y-, and z-coordinates of a point in the
axes coordinate system that forms the directed line segment PQ, where P is the
point (0,0,0) and Q is the specified x-, y-, and z-coordinates. This line always
points up. The length of the line PQ has no effect on the orientation of the
scene. This means a value of [0 0 1] produces the same results as [0 0 25].
2-235
camup
See Also
axis, camproj, campos, camtarget, camva
The axes properties CameraPosition, CameraTarget, CameraUpVector,
CameraViewAngle, Projection
“Controlling the Camera Viewpoint” for related functions
Defining Scenes with Camera Graphics for more information
2-236
camva
Purpose
2camva
Set or query the camera view angle
Syntax
camva
camva(view_angle)
camva('mode')
camva('auto')
camva('manual')
camva(axes_handle,...)
Description
The camera view angle determines the field of view of the camera. Larger
angles produce a smaller view of the scene. You can implement zooming by
changing the camera view angle.
camva with no arguments returns the camera view angle setting in the current
axes.
camva(view_angle) sets the view angle in the current axes to the specified
value. Specify the view angle in degrees.
camva('mode') returns the current value of the camera view angle mode,
which can be either auto (the default) or manual. See Remarks.
camva('auto') sets the camera view angle mode to auto.
camva('manual') sets the camera view angle mode to manual. See Remarks.
camva(axes_handle,...) performs the set or query on the axes identified by
the first argument, axes_handle. When you do not specify an axes handle,
camva operates on the current axes.
Remarks
camva sets or queries values of the axes object CameraViewAngle and
CameraViewAngleMode properties.
When the camera view angle mode is auto, MATLAB adjusts the camera view
angle so that the scene fills the available space in the window. If you move the
camera to a different position, MATLAB changes the camera view angle to
maintain a view of the scene that fills the available area in the window.
2-237
camva
Setting a camera view angle or setting the camera view angle to manual
disables the MATLAB stretch-to-fill feature (stretching of the axes to fit the
window). This means setting the camera view angle to its current value,
camva(camva)
can cause a change in the way the graph looks. See the Remarks section of the
axes reference page for more information.
Examples
This example creates two pushbuttons, one that zooms in and another that
zooms out.
uicontrol('Style','pushbutton',...
'String','Zoom In',...
'Position',[20 20 60 20],...
'Callback','if camva <= 1;return;else;camva(camva-1);end');
uicontrol('Style','pushbutton',...
'String','Zoom Out',...
'Position',[100 20 60 20],...
'Callback','if camva >= 179;return;else;camva(camva+1);end');
Now create a graph to zoom in and out on:
surf(peaks);
Note the range checking in the callback statements. This keeps the values for
the camera view angle in the range, greater than zero and less than 180.
See Also
axis, camproj, campos, camup, camtarget
The axes properties CameraPosition, CameraTarget, CameraUpVector,
CameraViewAngle, Projection
“Controlling the Camera Viewpoint” for related functions
Defining Scenes with Camera Graphics for more information
2-238
camzoom
Purpose
2camzoom
Zoom in and out on a scene
Syntax
camzoom(zoom_factor)
camzoom(axes_handle,...)
Description
camzoom(zoom_factor) zooms in or out on the scene depending on the value
specified by zoom_factor. If zoom_factor is greater than 1, the scene appears
larger; if zoom_factor is greater than zero and less than 1, the scene appears
smaller.
camzoom(axes_handle,...) operates on the axes identified by the first
argument, axes_handle. When you do not specify an axes handle, camzoom
operates on the current axes.
Remarks
camzoom sets the axes CameraViewAngle property, which in turn causes the
CameraViewAngleMode property to be set to manual. Note that setting the
CameraViewAngle property disables the MATLAB stretch-to-fill feature
(stretching of the axes to fit the window). This may result in a change to the
aspect ratio of your graph. See the axes function for more information on this
behavior.
See Also
axes, camdolly, camorbit, campan, camroll, camva
“Controlling the Camera Viewpoint” for related functions
Defining Scenes with Camera Graphics for more information
2-239
capture
Purpose
2capture
capture is obsolete in Release 11 (5.3). getframe provides the same
functionality and supports TrueColor displays by returning TrueColor images.
Syntax
capture
capture(h)
[X,cmap] = capture(h)
Description
capture creates a bitmap copy of the contents of the current figure, including
any uicontrol graphics objects. It creates a new figure and displays the bitmap
copy as an image graphics object in the new figure.
capture(h) creates a new figure that contains a copy of the figure identified by
h.
[X,cmap] = capture(h) returns an image matrix X and a colormap. You
display this information using the statements
colormap(cmap)
image(X)
Remarks
The resolution of a bitmap copy is less than that obtained with the print
command.
See Also
image, print
“Figure Windows” for related functions
2-240
cart2pol
Purpose
2cart2pol
Transform Cartesian coordinates to polar or cylindrical
Syntax
[THETA,RHO,Z] = cart2pol(X,Y,Z)
[THETA,RHO] = cart2pol(X,Y)
Description
[THETA,RHO,Z] = cart2pol(X,Y,Z) transforms three-dimensional Cartesian
coordinates stored in corresponding elements of arrays X, Y, and Z, into
cylindrical coordinates. THETA is a counterclockwise angular displacement in
radians from the positive x-axis, RHO is the distance from the origin to a point
in the x-y plane, and Z is the height above the x-y plane. Arrays X, Y, and Z must
be the same size (or any can be scalar).
[THETA,RHO] = cart2pol(X,Y) transforms two-dimensional Cartesian
coordinates stored in corresponding elements of arrays X and Y into polar
coordinates.
Algorithm
The mapping from two-dimensional Cartesian coordinates to polar
coordinates, and from three-dimensional Cartesian coordinates to cylindrical
coordinates is
Y
Z
P
P
z
rh
o
Y
rho
theta
theta
X
X
See Also
Two-Dimensional Mapping
Three-Dimensional Mapping
theta = atan2(y,x)
rho = sqrt(x.^2 + y.^2)
theta = atan2(y,x)
rho = sqrt(x.^2 + y.^2)
z = z
cart2sph, pol2cart, sph2cart
2-241
cart2sph
Purpose
2cart2sph
Transform Cartesian coordinates to spherical
Syntax
[THETA,PHI,R] = cart2sph(X,Y,Z)
Description
[THETA,PHI,R] = cart2sph(X,Y,Z) transforms Cartesian coordinates stored
in corresponding elements of arrays X, Y, and Z into spherical coordinates.
Azimuth THETA and elevation PHI are angular displacements in radians
measured from the positive x-axis, and the x-y plane, respectively; and R is the
distance from the origin to a point.
Arrays X, Y, and Z must be the same size.
Algorithm
The mapping from three-dimensional Cartesian coordinates to spherical
coordinates is
Z
P
r
Y
phi
th
et
a
X
See Also
2-242
cart2pol, pol2cart, sph2cart
theta = atan2(y,x)
phi = atan2(z, sqrt(x.^2 + y.^2))
r = sqrt(x.^2+y.^2+z.^2)
case
Purpose
2case
Description
case is part of the switch statement syntax, which allows for conditional
execution.
Case switch
A particular case consists of the case statement itself, followed by a case
expression, and one or more statements.
A case is executed only if its associated case expression (case_expr) is the first
to match the switch expression (switch_expr).
Examples
The general form of the switch statement is:
switch switch_expr
case case_expr
statement,...,statement
case {case_expr1,case_expr2,case_expr3,...}
statement,...,statement
...
otherwise
statement,...,statement
end
See Also
switch
2-243
cat
Purpose
2cat
Concatenate arrays
Syntax
C = cat(dim,A,B)
C = cat(dim,A1,A2,A3,A4...)
Description
C = cat(dim,A,B) concatenates the arrays A and B along dim.
C = cat(dim,A1,A2,A3,A4,...) concatenates all the input arrays (A1, A2, A3,
A4, and so on) along dim.
cat(2,A,B) is the same as [A,B] and cat(1,A,B) is the same as [A;B].
Remarks
When used with comma separated list syntax, cat(dim,C{:}) or
cat(dim,C.field) is a convenient way to concatenate a cell or structure array
containing numeric matrices into a single matrix.
Examples
Given,
A =
B =
1
3
2
4
5
7
6
8
concatenating along different dimensions produces:
1
3
5
7
2
4
6
8
C = cat(1,A,B)
1
3
A = magic(3); B = pascal(3);
C = cat(4,A,B);
produce a 3-by-3-by-1-by-2 array.
num2cell
The special character []
2-244
5
7
6
8
C = cat(2,A,B)
The commands
See Also
2
4
5
7
1
3
6
8
2
4
C = cat(3,A,B)
catch
Purpose
2catch
Description
The general form of a try statement is:
Begin catch block
try,
statement,
...,
statement,
catch,
statement,
...,
statement,
end
Normally, only the statements between the try and catch are executed.
However, if an error occurs while executing any of the statements, the error is
captured into lasterr, and the statements between the catch and end are
executed. If an error occurs within the catch statements, execution stops
unless caught by another try...catch block. The error string produced by a
failed try block can be obtained with lasterr.
See Also
end, eval, evalin, try
2-245
caxis
Purpose
2caxis
Color axis scaling
Syntax
caxis([cmin cmax])
caxis auto
caxis manual
caxis(caxis)
v = caxis
caxis(axes_handle,...)
Description
caxis controls the mapping of data values to the colormap. It affects any
surfaces, patches, and images with indexed CData and CDataMapping set to
scaled. It does not affect surfaces, patches, or images with true color CData or
with CDataMapping set to direct.
caxis([cmin cmax]) sets the color limits to specified minimum and maximum
values. Data values less than cmin or greater than cmax map to cmin and cmax,
respectively. Values between cmin and cmax linearly map to the current
colormap.
caxis auto lets MATLAB compute the color limits automatically using the
minimum and maximum data values. This is the default behavior. Color values
set to Inf map to the maximum color, and values set to −Inf map to the
minimum color. Faces or edges with color values set to NaN are not drawn.
caxis manual and caxis(caxis) freeze the color axis scaling at the current
limits. This enables subsequent plots to use the same limits when hold is on.
v = caxis returns a two-element row vector containing the [cmin cmax]
currently in use.
caxis(axes_handle,...) uses the axes specified by axes_handle instead of
the current axes.
Remarks
caxis changes the CLim and CLimMode properties of axes graphics objects.
How Color Axis Scaling Works
Surface, patch, and image graphics objects having indexed CData and
CDataMapping set to scaled, map CData values to colors in the figure colormap
each time they render. CData values equal to or less than cmin map to the first
2-246
caxis
color value in the colormap, and CData values equal to or greater than cmax
map to the last color value in the colormap. MATLAB performs the following
linear transformation on the intermediate values (referred to as C below) to
map them to an entry in the colormap (whose length is m, and whose row index
is referred to as index below).
index = fix((C–cmin)/(cmax–cmin)∗m)+1
Examples
Create (X,Y,Z) data for a sphere and view the data as a surface.
[X,Y,Z] = sphere;
C = Z;
surf(X,Y,Z,C)
Values of C have the range [−1 1]. Values of C near −1 are assigned the lowest
values in the colormap; values of C near 1 are assigned the highest values in
the colormap.
To map the top half of the surface to the highest value in the color table, use
caxis([−1 0])
To use only the bottom half of the color table, enter
caxis([−1 3])
which maps the lowest CData values to the bottom of the colormap, and the
highest values to the middle of the colormap (by specifying a cmax whose value
is equal to cmin plus twice the range of the CData).
The command
caxis auto
resets axis scaling back to auto-ranging and you see all the colors in the
surface. In this case, entering
caxis
returns
[–1 1]
2-247
caxis
Adjusting the color axis can be useful when using images with scaled color
data. For example, load the image data and colormap for Cape Cod,
Massachusetts.
load cape
This command loads the images data X and the image’s colormap map into the
workspace. Now display the image with CDataMapping set to scaled and install
the image’s colormap.
image(X,'CDataMapping','scaled')
colormap(map)
MATLAB sets the color limits to span the range of the image data, which is 1
to 192:
caxis
ans =
1
2-248
192
caxis
The blue color of the ocean is the first color in the colormap and is mapped to
the lowest data value (1). You can effectively move sealevel by changing the
lower color limit value. For example,
Caxis = [1 192]
Caxis = [3 192]
50
50
100
100
150
150
200
200
250
250
300
300
100
200
300
100
Caxis = [5 192]
50
100
100
150
150
200
200
250
250
300
300
See Also
200
300
Caxis = [6 192]
50
100
200
300
100
200
300
axes, axis, colormap, get, mesh, pcolor, set, surf
The CLim and CLimMode properties of axes graphics objects.
The Colormap property of figure graphics objects.
“Color Operations” for related functions
Axes Color Limits for more examples
2-249
cd
Purpose
2cd
Graphical
Interface
As an alternative to the cd function, use the Current Directory field in the
MATLAB desktop toolbar.
Syntax
cd
w = cd
cd('directory')
cd('..')
cd directory or cd ..
Description
cd displays the current working directory.
Change working directory
w = cd assigns the current working directory to w.
cd('directory') sets the current working directory to directory. Use the full
pathname for directory. On UNIX platforms, the character ~ is interpreted as
the user’s root directory.
cd('..') changes the current working directory to the directory above it.
cd directory or cd .. is the unquoted form of the syntax.
Examples
On UNIX
cd('/usr/local/matlab/toolbox/demos')
changes the current working directory to demos.
On Windows
cd('c:/toolbox/matlab/demos')
changes the current working directory to demos. Then typing
cd ..
changes the current working directory to matlab.
See Also
2-250
dir, path, pwd, what
cdf2rdf
Purpose
2cdf2rdf
Convert complex diagonal form to real block diagonal form
Syntax
[V,D] = cdf2rdf(V,D)
Description
If the eigensystem [V,D] = eig(X) has complex eigenvalues appearing in
complex-conjugate pairs, cdf2rdf transforms the system so D is in real
diagonal form, with 2-by-2 real blocks along the diagonal replacing the complex
pairs originally there. The eigenvectors are transformed so that
X = V*D/V
continues to hold. The individual columns of V are no longer eigenvectors, but
each pair of vectors associated with a 2-by-2 block in D spans the corresponding
invariant vectors.
Examples
The matrix
X =
1
0
0
2
4
-5
3
5
4
has a pair of complex eigenvalues.
[V,D] = eig(X)
V =
1.0000
0
0
-0.0191 - 0.4002i
0 - 0.6479i
0.6479
-0.0191 + 0.4002i
0 + 0.6479i
0.6479
1.0000
0
0
0
4.0000 + 5.0000i
0
0
0
4.0000 - 5.0000i
D =
Converting this to real block diagonal form produces
[V,D] = cdf2rdf(V,D)
2-251
cdf2rdf
V =
1.0000
0
0
-0.0191
0
0.6479
-0.4002
-0.6479
0
1.0000
0
0
0
4.0000
-5.0000
0
5.0000
4.0000
D =
Algorithm
The real diagonal form for the eigenvalues is obtained from the complex form
using a specially constructed similarity transformation.
See Also
eig, rsf2csf
2-252
cdfepoch
Purpose
2cdfepoch
Construct a cdfepoch object for Common Data Format (CDF) export
Syntax
E = cdfepoch(date)
Description
E = cdfepoch(date) constructs a cdfepoch object, where date is a valid string
(datestr), a number (datenum) representing a date, or a cdfepoch object.
When writing data to a CDF using cdfwrite, use cdfepoch to convert
MATLAB formatted dates to CDF formatted dates. The MATLAB cdfepoch
object simulates the CDFEPOCH datatype in CDF files
Note A CDF epoch is the number of milliseconds since 1-Jan-0000. MATLAB
datenums are the number of days since 0-Jan-0000.
See also
cdfinfo, cdfread, cdfwrite, datenum
2-253
cdfinfo
Purpose
2cdfinfo
Return information about a CDF file
Syntax
info = cdfinfo(file)
Description
info = cdfinfo(file) returns information about the Common Data Format
(CDF) file specified in the string, file. The function returns a structure, info,
that contains the fields shown in the following table.
Field
Description
Return Type
FileModDate
Date the file was last modified
String
Filename
Name of the file
String
FileSettings
Library settings used to create
the file
Structure array
FileSize
Size of the file, in bytes
Double
Format
File format (CDF)
String
FormatVersion
Version of the CDF library
used to create the file
String
GlobalAttributes
Global metadata
Structure array
Subfiles
Filenames containing the CDF
file’s data, if it is a multifile
CDF
Cell array
VariableAttributes
Metadata for the variables
Structure array
Variables
Details about the variables in
the file
Cell array
The GlobalAttributes and VariableAttributes Fields
GlobalAttributes and VariableAttributes are structure arrays that each
contain one field for each global or variable attribute respectively. The name of
the field corresponds to the name of an attribute. The data in that field,
contained in a cell array, represents the entry values for that attribute.
2-254
cdfinfo
For VariableAttributes, the attribute data resides in an N-by-2 cell array,
where N is the number of variables. The first column of this cell array contains
the variable names associated with the entries. The second column contains
the entry values.
Note Attribute names may not match the names of the attributes in the CDF
file exactly. Because attribute names can contain characters that are illegal in
MATLAB field names, they may be translated into legal field names. Illegal
characters that appear at the beginning of attributes are removed; other
illegal characters are replaced with underscores ('_'). If an attribute’s name is
modified, the attribute’s internal number is appended to the end of the field
name. For example, Variable%Attribute might become
Variable_Attribute_013.
The Variables Field
The Variables field of the returned info structure is an N-by-6 cell array,
where N is the number of variables. The six columns of the cell array contain
the following information.
Column No.
Description
Return Type
1
Name of the variable
String
2
Dimensions of the variable, as returned by
the size function
Double
array
3
Number of records assigned for the variable
Double
4
Data type of the variable, as stored in the
CDF file
String
2-255
cdfinfo
Column No.
5
Description
Return Type
Record and dimension variance settings for
the variable. The single T or F to the left of
the slash designates whether values vary by
record. The zero or more T or F letters to the
right of the slash designate whether values
vary at each dimension. Here are some
examples.
String
T/
F/T
T/TFF
6
(scalar variable)
(one-dimensional variable)
(three-dimensional variable)
Sparsity of the variable’s records. This is a
string holding one of three possible values:
String
• 'Full'
• 'Sparse (padded)'
• 'Sparse (nearest)'
Examples
info = cdfinfo('example.cdf')
info =
Filename: 'example.cdf'
FileModDate: '29-Jun-1995 05:51:58'
FileSize: 230513
Format: 'CDF'
FormatVersion: '2.4.8'
FileSettings: [1x1 struct]
Subfiles: {}
Variables: {7x6 cell}
GlobalAttributes: [1x1 struct]
VariableAttributes: [1x1 struct]
info.Variables
ans =
'L_gse'
[1x2 double]
'Status%C1'
[1x2 double]
'B_gse%C1'
[1x2 double]
'B_nsigma%C1' [1x2 double]
2-256
[
1]
[7493]
[7493]
[7493]
'char'
'F/T'
'uint8'
'T/T'
'single' 'T/T'
'single' 'T/'
'Full'
'Full'
'Full'
'Full'
cdfinfo
See Also
cdfread
2-257
cdfread
Purpose
2cdfread
Read data from a CDF file
Syntax
data =
data =
data =
data =
[data,
Description
data = cdfread(file) reads all of the variables from each record of the
Common Data Format (CDF) file specified in the string, file. The return
value, data, is a cell array in which each row contains a record and each column
cdfread(file)
cdfread(file, 'records', recnums, ...)
cdfread(file, 'variables', varnames, ...)
cdfread(file, 'slices', dimensionvalues, ...)
info] = cdfread(file, ...)
represents a variable.
data = cdfread(file, 'records', recnums, ...) reads only those records
specified in the vector, recnums. The record numbers are zero-based. The
return value, data, is a cell array having length(recnums) number of rows and
as many columns as there are variables.
data = cdfread(file, 'variables', varnames, ...) reads only those
variables specified in the 1-by-N or N-by-1 cell array of strings, varnames. The
return alue, data, is returned in a cell array having length(varnames)
number of columns and a row for each record requested.
data = cdfread(file, 'slices', dimensionvalues, ...) reads specific
values from the records of one variable in the CDF file. The N-by-3 matrix,
dimensionvalues, indicates which records are to be read by specifying start,
interval, and count parameters for each of the N dimensions of the variable.
The start parameter is zero-based.
The number of rows in dimensionvalues must be less than or equal to the
number of dimensions of the variable. Unspecified rows default to [0 1 N],
where N is the total number of values in a record. This causes cdfread to read
every value from those dimensions.
Because you can read just one variable at a time, you must also include a
'variables' parameter with this syntax.
[data, info] = cdfread(file, ...) also returns details about the CDF file
in the info structure.
2-258
cdfread
Examples
Read all of the data from the file.
data = cdfread('example.cdf');
Read just the data from variable 'Time'.
data = cdfread('example.cdf', 'Variable', {'Time'});
Read the first value in the first dimension, the second value in the second
dimension, the first and third values in the third dimension, and all values in
the remaining dimension of the variable 'multidimensional'.
data = cdfread('example.cdf', 'Variable', ...
{'multidimensional'}, 'Slices', [0 1 1; 1 1 1; 0 2 2]);
This is similar to reading the whole variable into 'data', and then using the
MATLAB command
data{1}(1, 2, [1 3], :)
See Also
cdfinfo, cdfwrite, cdfepoch
2-259
cdfwrite
Purpose
2cdfwrite
Write data to a CDF file
Syntax
cdfwrite(file, variablelist)
cdfwrite(..., 'PadValues', padvals)
cdfwrite(..., 'GlobalAttributes', gattrib)
cdfwrite(..., 'VariableAttributes', vattrib)
cdfwrite(..., 'WriteMode', mode)
cdfwrite(..., 'Format', format)
Description
cdfwrite(file,variablelist) writes out a Common Data Format (CDF) file,
specified in the string, file. The variablelist argument is a cell array of
ordered pairs, which are comprised of a CDF variable name (a string) and the
corresponding CDF variable value. To write out multiple records for a variable,
put the values in a cell array, where each element in the cell array represents
a record.
cdfwrite(...,'PadValues',padvals) writes out pad values for given
variable names. padvals is a cell array of ordered pairs, which are comprised
of a variable name (a string) and a corresponding pad value. Pad values are the
default value associated with the variable when an out-of-bounds record is
accessed. Variable names that appear in padvals must appear in
variablelist.
cdfwrite(...,'GlobalAttributes',gattrib) writes the structure gattrib
as global metadata for the CDF file. Each field of the structure is the name of
a global attribute. The value of each field contains the value of the attribute.
To write out multiple values for an attribute, put the values in a cell array
where each element in the cell array represents a record.
Note To specify a global attribute name that is illegal in MATLAB, create a
field called 'CDFAttributeRename' in the attribute structure. The value of
this field must have a value that is a cell array of ordered pairs. The ordered
pair consists of the name of the original attribute, as listed in the
GlobalAttributes structure and the corresponding name of the attribute to be
written to the CDF file.
2-260
cdfwrite
cdfwrite(..., 'VariableAttributes', vattrib) writes the structure
vattrib as variable metadata for the CDF. Each field of the struct is the name
of a variable attribute. The value of each field should be an M-by-2 cell array
where M is the number of variables with attributes. The first element in the
cell array should be the name of the variable and the second element should be
the value of the attribute for that variable.
Note To specify a variable attribute name that is illegal in MATLAB, create
a field called 'CDFAttributeRename' in the attribute structure. The value of
this field must have a value that is a cell array of ordered pairs. The ordered
pair consists of the name of the original attribute, as listed in the
VariableAttributes struct, and the corresponding name of the attribute to
be written to the CDF file. If you are specifying a variable attribute of a CDF
variable that you are renaming, the name of the variable in the
VariableAttributes structure must be the same as the renamed variable.
cdfwrite(...,'WriteMode',mode) where mode is either 'overwrite' or
'append', indicates whether or not the specified variables should be appended
to the CDF file if the file already exists. By default, cdfwrite overwrites
existing variables and attributes.,
cdfwrite(...,'Format',format) where format is either 'multifile' or
'singlefile', indicates whether or not the data is written out as a multifile
CDF. In a multifile CDF, each variable is stored in a separate file with the
name *.vN, where N is the number of the variable that is written out to the
CDF. By default, cdfwrite writes out a single file CDF. When 'WriteMode' is
set to 'Append', the 'Format' option is ignored, and the format of the
pre-existing CDF is used.
Examples
Write out a file 'example.cdf' containing a variable 'Longitude' with the
value [0:360].
cdfwrite('example', {'Longitude', 0:360});
Write out a file 'example.cdf' containing variables 'Longitude' and
'Latitude' with the variable 'Latitude' having a pad value of 10 for all
out-of-bounds records that are accessed.
2-261
cdfwrite
cdfwrite('example', {'Longitude', 0:360, 'Latitude', 10:20},...
'PadValues', {'Latitude', 10});
Write out a file 'example.cdf', containing a variable 'Longitude' with the
value [0:360], and with a variable attribute of 'validmin' with the value 10.
varAttribStruct.validmin = {'longitude' [10]};
cdfwrite('example', {'Longitude' 0:360}, 'VarAttribStruct',...
varAttribStruct);
See Also
2-262
cdfread, cdfinfo, cdfepoch
ceil
Purpose
2ceil
Round toward infinity
Syntax
B = ceil(A)
Description
B = ceil(A) rounds the elements of A to the nearest integers greater than or
equal to A. For complex A, the imaginary and real parts are rounded
independently.
Examples
a = [-1.9, -0.2, 3.4, 5.6, 7, 2.4+3.6i]
a =
Columns 1 through 4
-1.9000
-0.2000
3.4000
5.6000
Columns 5 through 6
7.0000
2.4000 + 3.6000i
ceil(a)
ans =
Columns 1 through 4
-1.0000
0
4.0000
6.0000
Columns 5 through 6
7.0000
3.0000 + 4.0000i
See Also
fix, floor, round
2-263
cell
Purpose
2cell
Create cell array
Syntax
c
c
c
c
c
Description
c = cell(n) creates an n-by-n cell array of empty matrices. An error message
appears if n is not a scalar.
=
=
=
=
=
cell(n)
cell(m,n) or c = cell([m n])
cell(m,n,p,...) or c = cell([m n p ...])
cell(size(A))
cell(javaobj)
c = cell(m,n) or c = cell([m,n]) creates an m-by-n cell array of empty
matrices. Arguments m and n must be scalars.
c = cell(m,n,p,...) or c = cell([m n p ...]) creates an m-by-n-by-p-...
cell array of empty matrices. Arguments m, n, p,... must be scalars.
c = cell(size(A)) creates a cell array the same size as A containing all empty
matrices.
c = cell(javaobj) converts a Java array or Java object, javaobj, into a
MATLAB cell array. Elements of the resulting cell array will be of the
MATLAB type (if any) closest to the Java array elements or Java object.
Examples
This example creates a cell array that is the same size as another array, A.
A = ones(2,2)
A =
1
1
1
1
c = cell(size(A))
c =
[]
[]
[]
[]
The next example converts an array of java.lang.String objects into a
MATLAB cell array.
2-264
cell
strArray = java_array('java.lang.String',3);
strArray(1) = java.lang.String('one');
strArray(2) = java.lang.String('two');
strArray(3) = java.lang.String('three');
cellArray = cell(strArray)
cellArray =
'one'
'two'
'three'
See Also
num2cell, ones, rand, randn, zeros
2-265
cell2mat
Purpose
2cell2mat
Convert cell array of matrices into single matrix
Syntax
m = cell2mat(c)
Description
m = cell2mat(c) converts a multidimensional cell array, c, with contents of
the same data type into a single matrix, m. The contents of c must be able to
concatenate into a hyperrectangle. Moreover, for each pair of neighboring cells,
the dimensions of the cell’s contents must match, excluding the dimension in
which the cells are neighbors.
The example shown below combines matrices in a 3-by-2 cell array into a single
60-by-50 matrix:
cell2mat(c)
10x25
10x25
20x25
20x25
cell2mat
30x25
Remarks
60x50
30x25
The dimensionality (or number of dimensions) of m will match the highest
dimensionality contained in the cell array.
cell2mat is not supported for cell arrays containing cell arrays or objects.
Examples
Combine the matrices in four cells of cell array C into the single matrix, M:
C = {[1] [2 3 4]; [5; 9] [6 7 8; 10 11 12]}
C =
[
1]
[1x3 double]
[2x1 double]
[2x3 double]
2-266
cell2mat
C{1,1}
ans =
1
C{1,2}
ans =
2
3
4
C{2,1}
ans =
5
9
C{2,2}
ans =
6
10
7
11
8
12
M = cell2mat(C)
M =
1
2
3
5
6
7
9
10
11
See Also
4
8
12
mat2cell, num2cell
2-267
cell2struct
Purpose
2cell2struct
Convert cell array to structure array
Syntax
s = cell2struct(c,fields,dim)
Description
s = cell2struct(c,fields,dim) creates a structure array, s, from the
information contained within cell array, c.
The fields argument specifies field names for the structure array. fields can
be a character array or a cell array of strings.
The dim argument controls which axis of the cell array is to be used in creating
the structure array. The length of c along the specified dimension must match
the number of fields named in fields. In other words, the following must be
true.
size(c,dim) == length(fields)
size(c,dim) == size(fields,1)
Examples
% if fields is a cell array
% if fields is a char array
The cell array, c, in this example contains information on trees. The three
columns of the array indicate the common name, genus, and average height of
a tree.
c = {'birch','betula',65;
c =
'birch'
'betula'
'maple'
'acer'
'maple','acer',50}
[65]
[50]
To put this information into a structure with the fields name, genus, and
height, use cell2struct along the second dimension of the 2-by-3 cell array.
fields = {'name', 'genus', 'height'};
s = cell2struct(c, fields, 2);
This yields the following 2-by-1 structure array.
s(1)
ans =
name: 'birch'
genus: 'betula'
height: 65
See Also
2-268
fieldnames, struct2cell
s(2)
ans =
name: 'maple'
genus: 'acer'
height: 50
celldisp
Purpose
2celldisp
Display cell array contents.
Syntax
celldisp(C)
celldisp(C,name)
Description
celldisp(C) recursively displays the contents of a cell array.
celldisp(C,name) uses the string name for the display instead of the name of
the first input (or ans).
Example
Use celldisp to display the contents of a 2-by-3 cell array:
C = {[1 2] 'Tony' 3+4i; [1 2;3 4] -5 'abc'};
celldisp(C)
C{1,1} =
1
2
C{2,1} =
1
3
2
4
C{1,2} =
Tony
C{2,2} =
-5
C{1,3} =
3.0000+ 4.0000i
C{2,3} =
abc
See Also
cellplot
2-269
cellfun
Purpose
2cellfun
Apply a function to each element in a cell array
Syntax
D = cellfun('fname',C)
D = cellfun('size',C,k)
D = cellfun('isclass',C,classname)
Description
D = cellfun('fname',C) applies the function fname to the elements of the cell
array C and returns the results in the double array D. Each element of D
contains the value returned by fname for the corresponding element in C. The
output array D is the same size as the cell array C.
These functions are supported:
Function
Return Value
isempty
true for an empty cell element
islogical
true for a logical cell element
isreal
true for a real cell element
length
Length of the cell element
ndims
Number of dimensions of the cell element
prodofsize
Number of elements in the cell element
D = cellfun('size',C,k) returns the size along the k-th dimension of each
element of C.
D = cellfun('isclass',C,'classname') returns true for each element of C
that matches classname. This function syntax returns false for objects that
are a subclass of classname.
Limitations
If the cell array contains objects, cellfun does not call overloaded versions of
the function fname.
Example
Consider this 2-by-3 cell array:
C{1,1} = [1 2; 4 5];
C{1,2} = 'Name';
2-270
cellfun
C{1,3}
C{2,1}
C{2,2}
C{2,3}
=
=
=
=
pi;
2 + 4i;
7;
magic(3);
cellfun returns a 2-by-3 double array:
D = cellfun('isreal',C)
D =
1
0
1
1
1
1
len = cellfun('length',C)
len =
2
1
4
1
1
3
isdbl = cellfun('isclass',C,'double')
isdbl =
1
1
See Also
0
1
1
1
isempty, islogical, isreal, length, ndims, size
2-271
cellplot
Purpose
2cellplot
Graphically display the structure of cell arrays
Syntax
cellplot(c)
cellplot(c,'legend')
handles = cellplot(...)
Description
cellplot(c) displays a figure window that graphically represents the
contents of c. Filled rectangles represent elements of vectors and arrays, while
scalars and short text strings are displayed as text.
cellplot(c,'legend') also puts a legend next to the plot.
handles = cellplot(c) displays a figure window and returns a vector of
surface handles.
Limitations
The cellplot function can display only two-dimensional cell arrays.
Examples
Consider a 2-by-2 cell array containing a matrix, a vector, and two text strings:
c{1,1}
c{1,2}
c{2,1}
c{2,2}
=
=
=
=
'2-by-2';
'eigenvalues of eye(2)';
eye(2);
eig(eye(2));
The command cellplot(c) produces:
2-272
cellstr
Purpose
2cellstr
Create cell array of strings from character array
Syntax
c = cellstr(S)
Description
c = cellstr(S) places each row of the character array S into separate cells of
c. Use the char function to convert back to a string matrix.
Examples
Given the string matrix
S=['abc ';'defg';'hi
']
S =
abc
defg
hi
whos S
Name
S
Size
3x4
Bytes
24
Class
char array
The following command returns a 3-by-1 cell array.
c = cellstr(S)
c =
'abc'
'defg'
'hi'
whos c
Name
c
See Also
Size
3x1
Bytes
294
Class
cell array
iscellstr, strings
2-273
cgs
Purpose
2cgs
Conjugate Gradients Squared method
Syntax
x = cgs(A,b)
cgs(A,b,tol)
cgs(A,b,tol,maxit)
cgs(A,b,tol,maxit,M)
cgs(A,b,tol,maxit,M1,M2)
cgs(A,b,tol,maxit,M1,M2,x0)
cgs(afun,b,tol,maxit,m1fun,m2fun,x0,p1,p2,...)
[x,flag] = cgs(A,b,...)
[x,flag,relres] = cgs(A,b,...)
[x,flag,relres,iter] = cgs(A,b,...)
[x,flag,relres,iter,resvec] = cgs(A,b,...)
Description
x = cgs(A,b) attempts to solve the system of linear equations A*x = b for x.
The n-by-n coefficient matrix A must be square and should be large and sparse.
The column vector b must have length n. A can be a function afun such that
afun(x) returns A*x.
If cgs converges, a message to that effect is displayed. If cgs fails to converge
after the maximum number of iterations or halts for any reason, a warning
message is printed displaying the relative residual norm(b-A*x)/norm(b) and
the iteration number at which the method stopped or failed.
cgs(A,b,tol) specifies the tolerance of the method, tol. If tol is [], then cgs
uses the default, 1e-6.
cgs(A,b,tol,maxit) specifies the maximum number of iterations, maxit. If
maxit is [] then cgs uses the default, min(n,20).
cgs(A,b,tol,maxit,M) and cgs(A,b,tol,maxit,M1,M2) use the
preconditioner M or M = M1*M2 and effectively solve the system
inv(M)*A*x = inv(M)*b for x. If M is [] then cgs applies no preconditioner. M
can be a function that returns M\x.
cgs(A,b,tol,maxit,M1,M2,x0) specifies the initial guess x0. If x0 is [], then
cgs uses the default, an all-zero vector.
2-274
cgs
cgs(afun,b,tol,maxit,m1fun,m2fun,x0,p1,p2,...) passes parameters
p1,p2,... to functions afun(x,p1,p2,...), m1fun(x,p1,p2,...), and
m2fun(x,p1,p2,...)
[x,flag] = cgs(A,b,...) returns a solution x and a flag that describes the
convergence of cgs.
Flag
Convergence
0
cgs converged to the desired tolerance tol within maxit
iterations.
1
cgs iterated maxit times but did not converge.
2
Preconditioner M was ill-conditioned.
3
cgs stagnated. (Two consecutive iterates were the same.)
4
One of the scalar quantities calculated during cgs became
too small or too large to continue computing.
Whenever flag is not 0, the solution x returned is that with minimal norm
residual computed over all the iterations. No messages are displayed if the
flag output is specified.
[x,flag,relres] = cgs(A,b,...) also returns the relative residual
norm(b-A*x)/norm(b). If flag is 0, then relres <= tol.
[x,flag,relres,iter] = cgs(A,b,...) also returns the iteration number at
which x was computed, where 0 <= iter <= maxit.
[x,flag,relres,iter,resvec] = cgs(A,b,...) also returns a vector of the
residual norms at each iteration, including norm(b-A*x0).
Examples
Example 1.
A = gallery('wilk',21);
b = sum(A,2);
tol = 1e-12; maxit = 15;
M1 = diag([10:-1:1 1 1:10]);
x = cgs(A,b,tol,maxit,M1,[],[]);
2-275
cgs
Alternatively, use this matrix-vector product function
function y = afun(x,n)
y = [ 0;
x(1:n-1)] + [((n-1)/2:-1:0)';
(1:(n-1)/2)'] .*x + [x(2:n);
0 ];
and this preconditioner backsolve function
function y = mfun(r,n)
y = r ./ [((n-1)/2:-1:1)'; 1; (1:(n-1)/2)'];
as inputs to cgs.
x1 = cgs(@afun,b,tol,maxit,@mfun,[],[],21);
Note that both afun and mfun must accept cgs’s extra input n=21.
Example 2.
load west0479
A = west0479
b = sum(A,2)
[x,flag] = cgs(A,b)
flag is 1 because cgs does not converge to the default tolerance 1e-6 within the
default 20 iterations.
[L1,U1] = luinc(A,1e-5)
[x1,flag1] = cgs(A,b,1e-6,20,L1,U1)
flag1 is 2 because the upper triangular U1 has a zero on its diagonal, and cgs
fails in the first iteration when it tries to solve a system such as U1*y = r for
y with backslash.
[L2,U2] = luinc(A,1e-6)
[x2,flag2,relres2,iter2,resvec2] = cgs(A,b,1e-15,10,L2,U2)
flag2 is 0 because cgs converges to the tolerance of 6.344e-16 (the value of
relres2) at the fifth iteration (the value of iter2) when preconditioned by the
incomplete LU factorization with a drop tolerance of 1e-6.
resvec2(1) = norm(b) and resvec2(6) = norm(b-A*x2). You can follow the
2-276
cgs
progress of cgs by plotting the relative residuals at each iteration starting from
the initial estimate (iterate number 0) with
semilogy(0:iter2,resvec2/norm(b),'-o')
xlabel('iteration number')
ylabel('relative residual')
0
10
−2
10
−4
10
−6
relative residual
10
−8
10
−10
10
−12
10
−14
10
−16
10
See Also
0
0.5
1
1.5
2
2.5
3
iteration number
3.5
4
4.5
5
bicg, bicgstab, gmres, lsqr, luinc, minres, pcg, qmr, symmlq
@ (function handle), \ (backslash)
References
[1] Barrett, R., M. Berry, T. F. Chan, et al., Templates for the Solution of Linear
Systems: Building Blocks for Iterative Methods, SIAM, Philadelphia, 1994.
[2] Sonneveld, Peter, “CGS: A fast Lanczos-type solver for nonsymmetric linear
systems”, SIAM J. Sci. Stat. Comput., January 1989, Vol. 10, No. 1, pp. 36-52.
2-277
char
Purpose
2char
Create character array (string)
Syntax
S = char(X)
S = char(C)
S = char(t1,t2,t3...)
Description
S = char(X) converts the array X that contains positive integers representing
character codes into a MATLAB character array (the first 127 codes are
ASCII). The actual characters displayed depend on the character set encoding
for a given font. The result for any elements of X outside the range from 0 to
65535 is not defined (and may vary from platform to platform). Use double to
convert a character array into its numeric codes.
S = char(C) when C is a cell array of strings, places each element of C into the
rows of the character array s. Use cellstr to convert back.
S = char(t1,t2,t3,..) forms the character array S containing the text
strings T1,T2,T3,... as rows, automatically padding each string with blanks to
form a valid matrix. Each text parameter, Ti, can itself be a character array.
This allows the creation of arbitrarily large character arrays. Empty strings
are significant.
Remarks
Ordinarily, the elements of A are integers in the range 32:127, which are the
printable ASCII characters, or in the range 0:255, which are all 8-bit values.
For noninteger values, or values outside the range 0:255, the characters
printed are determined by fix(rem(A,256)).
Examples
To print a 3-by-32 display of the printable ASCII characters:
ascii
ascii
! ” #
@ A B
' a b
2-278
=
=
$
C
c
char(reshape(32:127,32,3)')
% & ' ( ) ∗+ , - . / 0 1 2 3 4 5 6 7 8 9 : ; < = > ?
D E F G H I J K L M N O P Q R S T U V W X Y Z [ \ ] ^ _
d e f g h i j k l m n o p q r s t u v w x y z { | } ~
char
See Also
cellstr, double, get, set, strings, strvcat, text
2-279
checkin
Purpose
2checkin
Graphical
Interface
As an alternative to the checkin function, use Source Control Check In in the
Editor, Simulink, or Stateflow File menu.
Syntax
checkin('filename','comments','string')
checkin({'filename1','filename2','filename3', ...},'comments',
'string')
checkin('filename','option','value', ...)
Description
checkin('filename','comments','string') checks in the file named
filename to the source control system. Use the full pathname for the filename.
Check file into source control system
You must save the file before checking it in. The file can be open or closed when
you use checkin. The string argument is a MATLAB string containing
check-in comments for the source control system. You must supply the
comments argument and 'string'.
checkin({'filename1','filename2','filename3', ...},'comments',
'string') checks in the files named filename1 through filenamen to the
source control system. Use the full pathnames for the files. Additional
arguments apply to all files checked in.
checkin('filename','option','value', ...) provides additional checkin
options. The option and value arguments are shown in the table below.
option
Argument
Purpose
value Argument
'force'
When set to on, filename is checked in
even if the file has not changed since it
was checked out. The default value for
force is off.
'on'
'off' (default)
'lock'
When set to on, filename remains
checked out. Comments are submitted.
The default value for lock is off.
'on'
'off' (default)
You can check in a file that you checked out in a previous MATLAB session or
that you checked out directly from your source control system.
2-280
checkin
Examples
Check in a File with Comments
Typing
checkin('/matlab/mymfiles/clock.m','comments','Adjustment for
Y2K')
checks in the file /matlab/mymfiles/clock.m to the source control system with
the comment Adjustment for Y2K.
Check in Multiple Files with Comments
Typing
checkin({'/matlab/mymfiles/clock.m', ...
'/matlab/mymfiles/calendar.m'},'comments','Adjustment for Y2K')
checks two files into the source control system using the same comment for
each.
Check a File in and Keep It Checked out
Typing
checkin('/matlab/mymfiles/clock.m','comments','Adjustment for
Y2K','lock','on')
checks the file /matlab/mymfiles/clock.m into the source control system and
keeps the file checked out.
See Also
checkout, cmopts, undocheckout
2-281
checkout
Purpose
2checkout
Graphical
Interface
As an alternative to the checkout function, use Source Control Check Out in
the Editor, Simulink, or Stateflow File menu.
Syntax
checkout('filename')
checkout({'filename1','filename2','filename3', ...})
checkout('filename','option','value', ...)
Description
checkout('filename') checks out the file named filename from the source
control system. filename must be the full pathname for the file. The file can be
open or closed when you use checkout.
Check file out of source control system
checkout({'filename1','filename2','filename3', ...}) checks out the
files named filename1 through filenamen from the source control system. Use
the full pathnames for the files. Additional arguments apply to all files checked
out.
checkout('filename','option','value', ...) provides additional
checkout options. The option and value arguments are shown in the following
table.
2-282
checkout
option
Argument
Purpose
value
Argument
'force'
When set to on, the checkout is forced,
even if you already have the file checked
out. This is effectively an undocheckout
followed by a checkout. When force is
set to off, you can’t check out the file if
you already have it checked out.
'on'
'off' (default)
'lock'
When set to on, the checkout gets the file,
allows you to write to it, and locks the file
so that access to the file for others is read
only. When set to off, the checkout gets a
read-only version of the file, allowing
another user to check out the file for
updating. With lock set to off, you don’t
have to check in a file after checking it
out.
'on' (default)
'off'
'revision'
Checks out the specified revision of the
file.
'version_num'
If you end the MATLAB session, the file remains checked out. You can check
in the file from within MATLAB during a later session, or directly from your
source control system.
Examples
Check out a File
Typing
checkout('/matlab/mymfiles/clock.m')
checks out the file /matlab/mymfiles/clock.m from the source control system.
2-283
checkout
Check out Multiple Files
Typing
checkout({'/matlab/mymfiles/clock.m',...
'/matlab/mymfiles/calendar.m'})
checks out /matlab/mymfiles/clock.m and
/matlab/mymfiles/calendar.m from the source control system.
Force a Checkout, Even If File Is Already Checked out
Typing
checkout('/matlab/mymfiles/clock.m','force','on')
checks out /matlab/mymfiles/clock.m even if clock.m is already checked out
to you.
Check out Specified Revision of File
Typing
checkout('/matlab/mymfiles/clock.m','revision','1.1')
checks out revision 1.1 of clock.m.
See Also
2-284
checkin, cmopts, undocheckout
chol
Purpose
2chol
Cholesky factorization
Syntax
R = chol(X)
[R,p] = chol(X)
Description
The chol function uses only the diagonal and upper triangle of X. The lower
triangular is assumed to be the (complex conjugate) transpose of the upper.
That is, X is Hermitian.
R = chol(X), where X is positive definite produces an upper triangular R so
that R'*R = X. If X is not positive definite, an error message is printed.
[R,p] = chol(X), with two output arguments, never produces an error
message. If X is positive definite, then p is 0 and R is the same as above. If X is
not positive definite, then p is a positive integer and R is an upper triangular
matrix of order q = p-1 so that R'*R = X(1:q,1:q).
Examples
The binomial coefficients arranged in a symmetric array create an interesting
positive definite matrix.
n = 5;
X = pascal(n)
X =
1
1
1
1
2
3
1
3
6
1
4
10
1
5
15
1
4
10
20
35
1
5
15
35
70
It is interesting because its Cholesky factor consists of the same coefficients,
arranged in an upper triangular matrix.
R = chol(X)
R =
1
1
0
1
0
0
0
0
0
0
1
2
1
0
0
1
3
3
1
0
1
4
6
4
1
2-285
chol
Destroy the positive definiteness (and actually make the matrix singular) by
subtracting 1 from the last element.
X(n,n) = X(n,n)-1
X =
1
1
1
1
1
1
2
3
4
5
1
3
6
10
15
1
4
10
20
35
1
5
15
35
69
Now an attempt to find the Cholesky factorization fails.
Algorithm
chol uses the the LAPACK subroutines DPOTRF (real) and ZPOTRF (complex).
References
[1] Anderson, E., Z. Bai, C. Bischof, S. Blackford, J. Demmel, J. Dongarra,
J. Du Croz, A. Greenbaum, S. Hammarling, A. McKenney, and D. Sorensen,
LAPACK User’s Guide
(http://www.netlib.org/lapack/lug/lapack_lug.html), Third Edition,
SIAM, Philadelphia, 1999.
See Also
cholinc, cholupdate
2-286
cholinc
Purpose
2cholinc
Sparse incomplete Cholesky and Cholesky-Infinity factorizations
Syntax
R = cholinc(X,droptol)
R = cholinc(X,options)
R = cholinc(X,'0')
[R,p] = cholinc(X,'0')
R = cholinc(X,'inf')
Description
cholinc produces two different kinds of incomplete Cholesky factorizations:
the drop tolerance and the 0 level of fill-in factorizations. These factors may be
useful as preconditioners for a symmetric positive definite system of linear
equations being solved by an iterative method such as pcg (Preconditioned
Conjugate Gradients). cholinc works only for sparse matrices.
R = cholinc(X,droptol) performs the incomplete Cholesky factorization of X,
with drop tolerance droptol.
R = cholinc(X,options) allows additional options to the incomplete
Cholesky factorization. options is a structure with up to three fields:
droptol
Drop tolerance of the incomplete factorization
michol
Modified incomplete Cholesky
rdiag
Replace zeros on the diagonal of R
Only the fields of interest need to be set.
droptol is a non-negative scalar used as the drop tolerance for the incomplete
Cholesky factorization. This factorization is computed by performing the
incomplete LU factorization with the pivot threshold option set to 0 (which
forces diagonal pivoting) and then scaling the rows of the incomplete upper
triangular factor, U, by the square root of the diagonal entries in that column.
Since the nonzero entries U(i,j) are bounded below by droptol*norm(X(:,j))
(see luinc), the nonzero entries R(i,j) are bounded below by the local drop
tolerance droptol*norm(X(:,j))/R(i,i).
Setting droptol = 0 produces the complete Cholesky factorization, which is
the default.
2-287
cholinc
michol stands for modified incomplete Cholesky factorization. Its value is
either 0 (unmodified, the default) or 1 (modified). This performs the modified
incomplete LU factorization of X and scales the returned upper triangular
factor as described above.
rdiag is either 0 or 1. If it is 1, any zero diagonal entries of the upper triangular
factor R are replaced by the square root of the local drop tolerance in an
attempt to avoid a singular factor. The default is 0.
R = cholinc(X,'0') produces the incomplete Cholesky factor of a real sparse
matrix that is symmetric and positive definite using no fill-in. The upper
triangular R has the same sparsity pattern as triu(X), although R may be zero
in some positions where X is nonzero due to cancellation. The lower triangle of
X is assumed to be the transpose of the upper. Note that the positive
definiteness of X does not guarantee the existence of a factor with the required
sparsity. An error message results if the factorization is not possible. If the
factorization is successful, R'*R agrees with X over its sparsity pattern.
[R,p] = cholinc(X,'0') with two output arguments, never produces an error
message. If R exists, p is 0. If R does not exist, then p is a positive integer and R
is an upper triangular matrix of size q-by-n where q = p-1. In this latter case,
the sparsity pattern of R is that of the q-by-n upper triangle of X. R'*R agrees
with X over the sparsity pattern of its first q rows and first q columns.
R = cholinc(X,'inf') produces the Cholesky-Infinity factorization. This
factorization is based on the Cholesky factorization, and additionally handles
real positive semi-definite matrices. It may be useful for finding a solution to
systems which arise in interior-point methods. When a zero pivot is
encountered in the ordinary Cholesky factorization, the diagonal of the
Cholesky-Infinity factor is set to Inf and the rest of that row is set to 0. This
forces a 0 in the corresponding entry of the solution vector in the associated
system of linear equations. In practice, X is assumed to be positive
semi-definite so even negative pivots are replaced with a value of Inf.
Remarks
2-288
The incomplete factorizations may be useful as preconditioners for solving
large sparse systems of linear equations. A single 0 on the diagonal of the upper
triangular factor makes it singular. The incomplete factorization with a drop
tolerance prints a warning message if the upper triangular factor has zeros on
the diagonal. Similarly, using the rdiag option to replace a zero diagonal only
cholinc
gets rid of the symptoms of the problem, but it does not solve it. The
preconditioner may not be singular, but it probably is not useful, and a warning
message is printed.
The Cholesky-Infinity factorization is meant to be used within interior-point
methods. Otherwise, its use is not recommended.
Examples
Example 1.
Start with a symmetric positive definite matrix, S.
S = delsq(numgrid('C',15));
S is the two-dimensional, five-point discrete negative Lapacian on the grid
generated by numgrid('C',15).
Compute the Cholesky factorization and the incomplete Cholesky factorization
of level 0 to compare the fill-in. Make S singular by zeroing out a diagonal entry
and compute the (partial) incomplete Cholesky factorization of level 0.
C = chol(S);
R0 = cholinc(S,'0');
S2 = S; S2(101,101) = 0;
[R,p] = cholinc(S2,'0');
Fill-in occurs within the bands of S in the complete Cholesky factor, but none
in the incomplete Cholesky factor. The incomplete factorization of the singular
S2 stopped at row p = 101 resulting in a 100-by-139 partial factor.
D1 = (R0'*R0).*spones(S)-S;
D2 = (R'*R).*spones(S2)-S2;
D1 has elements of the order of eps, showing that R0'*R0 agrees with S over its
sparsity pattern. D2 has elements of the order of eps over its first 100 rows and
first 100 columns, D2(1:100,:) and D2(:,1:100).
2-289
cholinc
S
C= chol(S)
0
0
20
20
40
40
60
60
80
80
100
100
120
120
140
0
140
50
100
nz = 643
R0=cholinc(S,’0’)
0
50
100
nz = 1557
Partial factor [R,p]=cholinc(S2,’0’)
0
0
20
20
40
60
40
80
60
100
80
120
140
100
0
0
50
100
nz = 391
50
100
nz = 290
Example 2.
The first subplot below shows that cholinc(S,0), the incomplete Cholesky
factor with a drop tolerance of 0, is the same as the Cholesky factor of S.
Increasing the drop tolerance increases the sparsity of the incomplete factors,
as seen below.
cholinc(S,0)
cholinc(S,1e−3)
0
0
20
20
40
40
60
60
80
80
100
100
120
120
140
0
50
100
nz = 1557
140
0
cholinc(S,1e−2)
2-290
cholinc(S,1e−1)
0
0
20
20
40
40
60
60
80
80
100
100
120
120
140
0
50
100
nz = 671
50
100
nz = 1211
140
0
50
100
nz = 391
cholinc
Unfortunately, the sparser factors are poor approximations, as is seen by the
plot of drop tolerance versus norm(R'*R-S,1)/norm(S,1) in the next figure.
Drop tolerance vs nnz(cholinc(S,droptol))
1500
1000
500
0 −4
10
−3
−2
10
10
−1
10
0
10
Drop tolerance vs norm(R’*R−S)/norm(S)
0
10
−1
10
−2
10
−3
10
−4
10
−4
10
−3
10
−2
10
−1
10
0
10
Example 3.
The Hilbert matrices have (i,j) entries 1/(i+j-1) and are theoretically positive
definite:
H3 = hilb(3)
H3 =
1.0000
0.5000
0.3333
0.5000
0.3333
0.2500
0.3333
0.2500
0.2000
R3 = chol(H3)
R3 =
1.0000
0.5000
0
0.2887
0
0
0.3333
0.2887
0.0745
In practice, the Cholesky factorization breaks down for larger matrices:
H20 = sparse(hilb(20));
[R,p] = chol(H20);
p =
14
2-291
cholinc
For hilb(20), the Cholesky factorization failed in the computation of row 14
because of a numerically zero pivot. You can use the Cholesky-Infinity
factorization to avoid this error. When a zero pivot is encountered, cholinc
places an Inf on the main diagonal, zeros out the rest of the row, and continues
with the computation:
Rinf = cholinc(H20,'inf');
In this case, all subsequent pivots are also too small, so the remainder of the
upper triangular factor is:
full(Rinf(14:end,14:end))
ans =
Inf
0
0
0
0
Inf
0
0
0
0
Inf
0
0
0
0
Inf
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
Inf
0
0
0
0
0
0
0
Inf
0
0
0
0
0
0
0
Inf
Limitations
cholinc works on square sparse matrices only. For cholinc(X,'0') and
cholinc(X,'inf'), X must be real.
Algorithm
R = cholinc(X,droptol) is obtained from [L,U] = luinc(X,options), where
options.droptol = droptol and options.thresh = 0. The rows of the
uppertriangular U are scaled by the square root of the diagonal in that row, and
this scaled factor becomes R.
R = cholinc(X,options) is produced in a similar manner, except the rdiag
option translates into the udiag option and the milu option takes the value of
the michol option.
R = cholinc(X,'0') is based on the “KJI” variant of the Cholesky
factorization. Updates are made only to positions which are nonzero in the
upper triangle of X.
R = cholinc(X,'inf') is based on the algorithm in Zhang [2].
2-292
cholinc
See Also
chol, luinc, pcg
References
[1] Saad, Yousef, Iterative Methods for Sparse Linear Systems, PWS Publishing
Company, 1996. Chapter 10, “Preconditioning Techniques.”
[2] Zhang, Yin, Solving Large-Scale Linear Programs by Interior-Point
Methods Under the MATLAB Environment, Department of Mathematics and
Statistics, University of Maryland Baltimore County, Technical Report
TR96-01
2-293
cholupdate
Purpose
2cholupdate
Rank 1 update to Cholesky factorization
Syntax
R1 = cholupdate(R,x)
R1 = cholupdate(R,x,'+')
R1 = cholupdate(R,x,'-')
[R1,p] = cholupdate(R,x,'-')
Description
R1 = cholupdate(R,x) where R = chol(A) is the original Cholesky
factorization of A, returns the upper triangular Cholesky factor of A + x*x',
where x is a column vector of appropriate length. cholupdate uses only the
diagonal and upper triangle of R. The lower triangle of R is ignored.
R1 = cholupdate(R,x,'+') is the same as R1 = cholupdate(R,x).
R1 = cholupdate(R,x,'-') returns the Cholesky factor of A - x*x'. An
error message reports when R is not a valid Cholesky factor or when the
downdated matrix is not positive definite and so does not have a Cholesky
factoriza- tion.
[R1,p] = cholupdate(R,x,'-') will not return an error message. If p is 0,
R1 is the Cholesky factor of A - x*x'. If p is greater than 0, R1 is the Cholesky
factor of the original A. If p is 1, cholupdate failed because the downdated
matrix is not positive definite. If p is 2, cholupdate failed because the upper
triangle of R was not a valid Cholesky factor.
Remarks
Example
cholupdate works only for full matrices.
A = pascal(4)
A =
1
1
1
1
R = chol(A)
1
2
3
4
2-294
1
3
6
10
1
4
10
20
cholupdate
R =
1
0
0
0
1
1
0
0
1
2
1
0
1
3
3
1
x = [0 0 0 1]';
This is called a rank one update to A since rank(x*x') is 1:
A + x*x'
ans =
1
1
1
1
1
2
3
4
1
3
6
10
1
4
10
21
Instead of computing the Cholesky factor with R1 = chol(A + x*x'), we can
use cholupdate:
R1 = cholupdate(R,x)
R1 =
1.0000
0
0
0
1.0000
1.0000
0
0
1.0000
2.0000
1.0000
0
1.0000
3.0000
3.0000
1.4142
Next destroy the positive definiteness (and actually make the matrix singular)
by subtracting 1 from the last element of A. The downdated matrix is:
A - x*x'
ans =
1
1
1
1
1
2
3
4
1
3
6
10
1
4
10
19
2-295
cholupdate
Compare chol with cholupdate:
R1 = chol(A-x*x')
??? Error using ==> chol
Matrix must be positive definite.
R1 = cholupdate(R,x,'-')
??? Error using ==> cholupdate
Downdated matrix must be positive definite.
However, subtracting 0.5 from the last element of A produces a positive
definite matrix, and we can use cholupdate to compute its Cholesky factor:
x = [0 0 0 1/sqrt(2)]';
R1 = cholupdate(R,x,'-')
R1 =
1.0000
1.0000
1.0000
0
1.0000
2.0000
0
0
1.0000
0
0
0
1.0000
3.0000
3.0000
0.7071
Algorithm
cholupdate uses the algorithms from the LINPACK subroutines ZCHUD and
ZCHDD. cholupdate is useful since computing the new Cholesky factor from
scratch is an O ( N 3 ) algorithm, while simply updating the existing factor in
this way is an O ( N 2 ) algorithm.
See Also
chol, qrupdate
References
[1] Dongarra, J.J., J.R. Bunch, C.B. Moler, and G.W. Stewart, LINPACK Users'
Guide, SIAM, Philadelphia, 1979.
2-296
circshift
Purpose
2circshift
Shift array circularly
Syntax
B = circshift(A,shiftsize)
Description
B = circshift(A,shiftsize) circularly shifts the values in the array, A, by
shiftsize elements. shiftsize is a vector of integer scalars where the n-th
element specifies the shift amount for the n-th dimension of array A. If an
element in shiftsize is positive, the values of A are shifted down (or to the
right). If it is negative, the values of A are shifted up (or to the left). If it is 0,
the values in that dimension are not shifted.
Example
Circularly shift first dimension values down by 1.
A = [ 1 2 3;4 5 6; 7 8 9]
A =
1
2
3
4
5
6
7
8
9
B = circshift(A,1)
B =
7
8
9
1
2
3
4
5
6
Circularly shift first dimension values down by 1 and second dimension values
to the left by 1.
B = circshift(A,[1 -1]);
B =
8
9
7
2
3
1
5
6
4
See Also
fftshift, shiftdim
2-297
cla
Purpose
2cla
Clear current axes
Syntax
cla
cla reset
Description
cla deletes from the current axes all graphics objects whose handles are not
hidden (i.e., their HandleVisibility property is set to on).
cla reset deletes from the current axes all graphics objects regardless of the
setting of their HandleVisibility property and resets all axes properties,
except Position and Units, to their default values.
Remarks
The cla command behaves the same way when issued on the command line as
it does in callback routines – it does not recognize the HandleVisibility
setting of callback. This means that when issued from within a callback
routine, cla deletes only those objects whose HandleVisibility property is set
to on.
See Also
clf, hold, newplot, reset
“Axes Operations” for related functions
2-298
clabel
Purpose
Syntax
2clabel
Contour plot elevation labels
clabel(C,h)
clabel(C,h,v)
clabel(C,h,'manual')
clabel(C)
clabel(C,v)
clabel(C,'manual')
Description
The clabel function adds height labels to a two-dimensional contour plot.
clabel(C,h) rotates the labels and inserts them in the contour lines. The
function inserts only those labels that fit within the contour, depending on the
size of the contour.
clabel(C,h,v) creates labels only for those contour levels given in vector v,
then rotates the labels and inserts them in the contour lines.
clabel(C,h,'manual') places contour labels at locations you select with a
mouse. Press the left mouse button (the mouse button on a single-button
mouse) or the space bar to label a contour at the closest location beneath the
center of the cursor. Press the Return key while the cursor is within the figure
window to terminate labeling. The labels are rotated and inserted in the
contour lines.
clabel(C) adds labels to the current contour plot using the contour structure
C output from contour. The function labels all contours displayed and
randomly selects label positions.
clabel(C,v) labels only those contour levels given in vector v.
clabel(C,'manual') places contour labels at locations you select with a
mouse.
Remarks
When the syntax includes the argument h, this function rotates the labels and
inserts them in the contour lines (see Example). Otherwise, the labels are
displayed upright and a '+' indicates which contour line the label is
annotating.
2-299
clabel
Examples
Generate, draw, and label a simple contour plot.
[x,y] = meshgrid(–2:.2:2);
z = x.^exp(–x.^2–y.^2);
[C,h] = contour(x,y,z);
clabel(C,h);
2
1.5
0.6
−0.5
0.6
0.2
8
0.
0.4
0.6
0.4
0.2
1
0.6
−1
0
1
−1.5
1
0.2
See Also
0.8
−2
−2
−
0. 9.86
2 9e
−1
7
0.4
0.6
1
−1.5
0.8
−1
0.4
0.8
−0.5
−0.2
0
0.2
−9.869e−17
0.5
8
2
0.
−0.
1
0.5
1
1.5
2
contour, contourc, contourf
“Annotating Plots” for related functions
Drawing Text in a Box for an example that illustrates the use of contour labels
2-300
class
Purpose
2class
Create object or return class of object
Syntax
str
obj
obj
obj
Description
str = class(object) returns a string specifying the class of object.
=
=
=
=
class(object)
class(s,'class_name')
class(s,'class_name',parent1,parent2...)
class(struct([]),'class_name',parent1,parent2...)
The following table lists the object class names that may be returned. All
except the last one are MATLAB classes.
logical
Logical array of true and false values
char
Characters array
int8
8-bit signed integer array
uint8
8-bit unsigned integer array
int16
16-bit signed integer array
uint16
16-bit unsigned integer array
int32
32-bit signed integer array
uint32
32-bit unsigned integer array
int64
64-bit signed integer array
uint64
64-bit unsigned integer array
single
Single-precision floating point number array
double
Double-precision floating point number array
cell
Cell array
struct
Structure array
function handle
Array of values for calling functions indirectly
'class_name'
Custom MATLAB object class or Java class
obj = class(s,'class_name') creates an object of MATLAB class
'class_name' using structure s as a template. This syntax is valid only in a
2-301
class
function named class_name.m in a directory named @class_name (where
'class_name' is the same as the string passed into class).
obj = class(s,'class_name',parent1,parent2,...) creates an object of
MATLAB class 'class_name' that inherits the methods and fields of the
parent objects parent1, parent2, and so on. Structure s is used as a template
for the object.
obj = class(struct([]),'class_name',parent1,parent2,...) creates an
object of MATLAB class 'class_name' that inherits the methods and fields of
the parent objects parent1, parent2, and so on. Specifying the empty
structure, struct([]), as the first argument ensures that the object created
contains no fields other than those that are inherited from the parent objects.
Examples
To return in nameStr the name of the class of Java object j
nameStr = class(j)
To create a user-defined MATLAB object of class polynom
p = class(p,'polynom')
See Also
inferiorto, isa, superiorto
The “MATLAB Classes and Objects” and the “Calling Java from MATLAB”
chapters in Programming and Data Types.
2-302
clc
Purpose
2clc
Graphical
Interface
As an alternative to the clc function, use Clear Command Window in the
MATLAB desktop Edit menu.
Syntax
clc
Description
clc clears all input and output from the Command Window display, giving you
a “clean screen.”
Clear Command Window
After using clc, you cannot use the scroll bar to see the history of functions,
but still can use the up arrow to recall statements from the command history.
Examples
Use clc in an M-file to always display output in the same starting position on
the screen.
See Also
clear, clf, close, home
2-303
clear
Purpose
2clear
Graphical
Interface
As an alternative to the clear function, use Clear Workspace in the MATLAB
desktop Edit menu, or in the context menu in the Workspace browser.
Syntax
clear
clear name
clear name1 name2 name3 ...
clear global name
clear keyword
clear('name1','name2','name3',...)
Description
clear removes all variables from the workspace. This frees up system memory.
Remove items from workspace, freeing up system memory
clear name removes just the M-file or MEX-file function or variable name from
the workspace. You can use wildcards (*) to remove items selectively. For
example, clear my* removes any variables whose names begin with the string
my. It removes debugging breakpoints in M-files and reinitializes persistent
variables, since the breakpoints for a function and persistent variables are
cleared whenever the M-file is changed or cleared. If name is global, it is
removed from the current workspace, but left accessible to any functions
declaring it global. If name has been locked by mlock, it remains in memory.
Use a partial path to distinguish between different overloaded versions of a
function. For example, clear inline/display clears only the display method
for inline objects, leaving any other implementations in memory.
clear name1 name2 name3 ... removes name1, name2, and name3 from the
workspace.
clear global name removes the global variable name. If name is global, clear
name removes name from the current workspace, but leaves it accessible to any
functions declaring it global. Use clear global name to completely remove a
global variable.
2-304
clear
clear keyword clears the items indicated by keyword.
Keyword
Items Cleared
all
Removes all variables, functions, and MEX-files from
memory, leaving the workspace empty. Using clear all
removes debugging breakpoints in M-files and
reinitializes persistent variables, since the breakpoints
for a function and persistent variables are cleared
whenever the M-file is changed or cleared. When issued
from the Command Window prompt, also removes the
Java packages import list.
classes
The same as clear all, but also clears MATLAB class
definitions. If any objects exist outside the workspace
(for example, in user data or persistent variables in a
locked M-file), a warning is issued and the class
definition is not cleared. Issue a clear classes
function if the number or names of fields in a class are
changed.
functions
Clears all the currently compiled M-functions and
MEX-functions from memory. Using clear function
removes debugging breakpoints in the function M-file
and reinitializes persistent variables, since the
breakpoints for a function and persistent variables are
cleared whenever the M-file is changed or cleared.
global
Clears all global variables from the workspace.
import
Removes the Java packages import list. It can only be
issued from the Command Window prompt. It cannot be
used in a function.
variables
Clears all variables from the workspace.
clear('name1','name2','name3',...) is the function form of the syntax. Use
this form when the variable name or function name is stored in a string.
2-305
clear
Remarks
When you use clear in a function, it has the following effect on items in your
function and base workspaces:
• clear name—If name is the name of a function, the function is cleared in both
the function workspace and in your base workspace.
• clear functions—All functions are cleared in both the function workspace
and in your base workspace.
• clear global—All global variables are cleared in both the function
workspace and in your base workspace.
• clear all—All functions, global variables, and classes are cleared in both
the function workspace and in your base workspace.
Limitations
clear does not affect the amount of memory allocated to the MATLAB process
under UNIX.
Examples
Given a workspace containing the following variables
Name
Size
c
frame
gbl1
gbl2
xint
3x4
1x1
1x1
1x1
1x1
Bytes
1200
8
8
1
Class
cell array
java.awt.Frame
double array (global)
double array (global)
int8 array
you can clear a single variable, xint, by typing
clear xint
To clear all global variables, type
clear global
whos
Name
Size
c
frame
2-306
3x4
1x1
Bytes
1200
Class
cell array
java.awt.Frame
clear
To clear all compiled M- and MEX-functions from memory, type clear
functions. In the case shown below, clear functions was unable to clear one
M-file function from memory, testfun, because the function is locked.
clear functions
inmem
ans =
'testfun'
mislocked testfun
ans =
1
% Attempt to clear all functions.
% One M-file function remains in memory.
% This function is locked in memory.
Once you unlock the function from memory, you can clear it.
munlock testfun
clear functions
inmem
ans =
Empty cell array: 0-by-1
See Also
clc, close, import, mlock, munlock, pack, persistent, who, whos
2-307
clear (serial)
Purpose
2clear (serial)
Remove a serial port object from the MATLAB workspace
Syntax
clear obj
Arguments
obj
Description
clear obj removes obj from the MATLAB workspace.
Remarks
If obj is connected to the device and it is cleared from the workspace, then obj
remains connected to the device. You can restore obj to the workspace with the
instrfind function. A serial port object connected to the device has a Status
property value of open.
A serial port object or an array of serial port objects.
To disconnect obj from the device, use the fclose function. To remove obj from
memory, use the delete function. You should remove invalid serial port objects
from the workspace with clear.
If you use the help command to display help for clear, then you need to supply
the pathname shown below.
help serial/private/clear
Example
This example creates the serial port object s, copies s to a new variable scopy,
and clears s from the MATLAB workspace. s is then restored to the workspace
with instrfind and is shown to be identical to scopy.
s = serial('COM1');
scopy = s;
clear s
s = instrfind;
isequal(scopy,s)
ans =
1
See Also
Functions
delete, fclose, instrfind, isvalid
Properties
Status
2-308
clf
Purpose
2clf
Clear current figure window
Syntax
clf
clf reset
Description
clf deletes from the current figure all graphics objects whose handles are not
hidden (i.e., their HandleVisibility property is set to on).
clf reset deletes from the current figure all graphics objects regardless of the
setting of their HandleVisibility property and resets all figure properties,
except Position, Units, PaperPosition, and PaperUnits to their default
values.
Remarks
The clf command behaves the same way when issued on the command line as
it does in callback routines – it does not recognize the HandleVisibility
setting of callback. This means that when issued from within a callback
routine, clf deletes only those objects whose HandleVisibility property is set
to on.
See Also
cla, clc, hold, reset
“Figure Windows” for related functions
2-309
clipboard
Purpose
2clipboard
Graphical
Interface
As an alternative to clipboard, use the Import Wizard. To use the Import
Wizard to copy data from the clipboard, select Paste Special from the Edit
menu.
Syntax
clipboard('copy',data)
str = clipboard('paste')
data = clipboard('pastespecial')
Description
clipboard('copy', data) sets the clipboard contents to data. If data is not a
character array, clipboard uses mat2str to convert it to a string.
Copy and paste strings to and from the system clipboard.
str = clipboard('paste') returns the current contents of the clipboard as a
string or as an empty string (' '), if the current clipboard content cannot be
converted to a string.
data = clipboard('pastespecial') returns the current contents of the
clipboard as an array using uiimport.
Note Requires an active X display on Unix and Java elsewhere.
See Also
2-310
load, uiimport
clock
Purpose
2clock
Current time as a date vector
Syntax
c = clock
Description
c = clock returns a 6-element date vector containing the current date and
time in decimal form:
c = [year month day hour minute seconds]
The first five elements are integers. The seconds element is accurate to several
digits beyond the decimal point. The statement fix(clock) rounds to integer
display format.
See Also
cputime, datenum, datevec, etime, tic, toc
2-311
close
Purpose
2close
Delete specified figure
Syntax
close
close(h)
close name
close all
close all hidden
status = close(...)
Description
close deletes the current figure or the specified figure(s). It optionally returns
the status of the close operation.
close deletes the current figure (equivalent to close(gcf)).
close(h) deletes the figure identified by h. If h is a vector or matrix, close
deletes all figures identified by h.
close name deletes the figure with the specified name.
close all deletes all figures whose handles are not hidden.
close all hidden deletes all figures including those with hidden handles.
status = close(...) returns 1 if the specified windows have been deleted
and 0 otherwise.
Remarks
The close function works by evaluating the specified figure’s
CloseRequestFcn property with the statement:
eval(get(h,'CloseRequestFcn'))
The default CloseRequestFcn, closereq, deletes the current figure using
delete(get(0,'CurrentFigure')). If you specify multiple figure handles,
close executes each figure’s CloseRequestFcn in turn. If MATLAB encounters
an error that terminates the execution of a CloseRequestFcn, the figure is not
deleted. Note that using your computer’s window manager (i.e., the Close
menu item) also calls the figure’s CloseRequestFcn.
If a figure’s handle is hidden (i.e., the figure’s HandleVisibility property is set
to callback or off and the root ShowHiddenHandles property is set on), you
2-312
close
must specify the hidden option when trying to access a figure using the all
option.
To delete all figures unconditionally, use the statements:
set(0,'ShowHiddenHandles','on')
delete(get(0,'Children'))
The delete function does not execute the figure’s CloseRequestFcn; it simply
deletes the specified figure.
The figure CloseRequestFcn allows you to either delay or abort the closing of
a figure once the close function has been issued. For example, you can display
a dialog box to see if the user really wants to delete the figure or save and clean
up before closing.
See Also
delete, figure, gcf
The figure HandleVisibility property
The root ShowHiddenHandles property
“Figure Windows” for related functions
2-313
close
Purpose
2close
Close Audio Video Interleaved (AVI) file
Syntax
aviobj = close(aviobj)
Description
aviobj = close(aviobj) finishes writing and closes the AVI file associated
with aviobj, which is an AVI file object, created using the avifile function.
See Also
2-314
avifile, addframe, movie2avi
closereq
Purpose
2closereq
Default figure close request function
Syntax
closereq
Description
closereq delete the current figure.
See Also
The figure CloseRequestFcn property
“Figure Windows” for related functions
2-315
cmopts
Purpose
2cmopts
Graphical
Interface
As an alternative to cmopts, use preferences. Select File -> Preferences in the
MATLAB desktop, and then select General -> Source Control.
Syntax
cmopts
Description
cmopts returns the name of the source control system you selected using
Get name of source control system
preferences, which is one of the following:
clearcase
customverctrl
pvcs
rcs
sourcesafe
If you have not selected a source control system, cmopts returns
none
Specifying a Source Control System
To specify the source control system:
1 From the MATLAB Editor window or from a Simulink or Stateflow model
window, select File -> Preferences.
The Preferences dialog box opens.
2 In the left pane, click the + for General, and then select Source Control.
The currently selected system is shown.
3 Select the system you want to use from the Source control system list.
4 Click OK.
For more information, see source control preferences.
Examples
Type cmopts and MATLAB returns rcs, meaning the source control system
specified in preferences is RCS.
See Also
checkin, checkout, customverctrl
2-316
colamd
Purpose
2colamd
Column approximate minimum degree permutation
Syntax
p = colamd(S)
p = colamd(S,knobs)
[p,stats] = colamd(S)
[p,stats] = colamd(S,knobs)
Description
p = colamd(S) returns the column approximate minimum degree
permutation vector for the sparse matrix S. For a non-symmetric matrix S,
S(:,p) tends to have sparser LU factors than S. The Cholesky factorization of
S(:,p)' * S(:,p) also tends to be sparser than that of S'*S.
knobs is a two-element vector. If S is m-by-n, then rows with more than
(knobs(1))*n entries are ignored. Columns with more than (knobs(2))*m
entries are removed prior to ordering, and ordered last in the output
permutation p. If the knobs parameter is not present, then
knobs(1) = knobs(2) = spparms('wh_frac').
stats is an optional vector that provides data about the ordering and the
validity of the matrix S.
stats(1)
Number of dense or empty rows ignored by colamd
stats(2)
Number of dense or empty columns ignored by colamd
stats(3)
Number of garbage collections performed on the internal data
structure used by colamd (roughly of size
2.2*nnz(S) + 4*m + 7*n integers)
stats(4)
0 if the matrix is valid, or 1 if invalid
stats(5)
Rightmost column index that is unsorted or contains duplicate
entries, or 0 if no such column exists
stats(6)
Last seen duplicate or out-of-order row index in the column
index given by stats(5), or 0 if no such row index exists
stats(7)
Number of duplicate and out-of-order row indices
Although, MATLAB built-in functions generate valid sparse matrices, a user
may construct an invalid sparse matrix using the MATLAB C or Fortran APIs
and pass it to colamd. For this reason, colamd verifies that S is valid:
2-317
colamd
• If a row index appears two or more times in the same column, colamd ignores
the duplicate entries, continues processing, and provides information about
the duplicate entries in stats(4:7).
• If row indices in a column are out of order, colamd sorts each column of its
internal copy of the matrix S (but does not repair the input matrix S),
continues processing, and provides information about the out-of-order
entries in stats(4:7).
• If S is invalid in any other way, colamd cannot continue. It prints an error
message, and returns no output arguments (p or stats) .
The ordering is followed by a column elimination tree post-ordering.
Note colamd tends to be faster than colmmd and tends to return a better
ordering.
See Also
colmmd, colperm, spparms, symamd, symmmd, symrcm
References
[1] The authors of the code for colamd are Stefan I. Larimore and Timothy A.
Davis ([email protected]), University of Florida. The algorithm was
developed in collaboration with John Gilbert, Xerox PARC, and Esmond Ng,
Oak Ridge National Laboratory. Sparse Matrix Algorithms Research at the
University of Florida: http://www.cise.ufl.edu/research/sparse/
2-318
colmmd
Purpose
2colmmd
Sparse column minimum degree permutation
Syntax
p = colmmd(S)
Description
p = colmmd(S) returns the column minimum degree permutation vector for
the sparse matrix S. For a nonsymmetric matrix S, this is a column
permutation p such that S(:,p) tends to have sparser LU factors than S.
The colmmd permutation is automatically used by \ and / for the solution of
nonsymmetric and symmetric indefinite sparse linear systems.
Use spparms to change some options and parameters associated with heuristics
in the algorithm.
Algorithm
The minimum degree algorithm for symmetric matrices is described in the
review paper by George and Liu [1]. For nonsymmetric matrices, the MATLAB
minimum degree algorithm is new and is described in the paper by Gilbert,
Moler, and Schreiber [2]. It is roughly like symmetric minimum degree for
A'*A, but does not actually form A'*A.
Each stage of the algorithm chooses a vertex in the graph of A'*A of lowest
degree (that is, a column of A having nonzero elements in common with the
fewest other columns), eliminates that vertex, and updates the remainder of
the graph by adding fill (that is, merging rows). If the input matrix S is of size
m-by-n, the columns are all eliminated and the permutation is complete after n
stages. To speed up the process, several heuristics are used to carry out
multiple stages simultaneously.
Examples
The Harwell-Boeing collection of sparse matrices and the MATLAB demos
directory include a test matrix WEST0479. It is a matrix of order 479 resulting
from a model due to Westerberg of an eight-stage chemical distillation column.
The spy plot shows evidence of the eight stages. The colmmd ordering
scrambles this structure.
load west0479
A = west0479;
p = colmmd(A);
spy(A)
spy(A(:,p))
2-319
colmmd
A
A(:,p)
0
0
100
100
200
200
300
300
400
400
0
100
200
300
nz = 1887
400
0
100
200
300
nz = 1887
400
Comparing the spy plot of the LU factorization of the original matrix with that
of the reordered matrix shows that minimum degree reduces the time and
storage requirements by better than a factor of 2.8. The nonzero counts are
16777 and 5904, respectively.
spy(lu(A))
spy(lu(A(:,p)))
lu(A)
0
100
100
200
200
300
300
400
400
0
2-320
lu(A(:,p))
0
100
200
300
nz = 16777
400
0
100
200
300
nz = 5904
400
colmmd
See Also
colamd, colperm, lu, spparms, symamd, symmmd, symrcm
The arithmetic operator \
References
[1] George, Alan and Liu, Joseph, “The Evolution of the Minimum Degree
Ordering Algorithm,” SIAM Review, 1989, 31:1-19.
[2] Gilbert, John R., Cleve Moler, and Robert Schreiber, “Sparse Matrices in
MATLAB: Design and Implementation,” SIAM Journal on Matrix Analysis
and Applications 13, 1992, pp. 333-356.
2-321
colorbar
Purpose
2colorbar
Display colorbar showing the color scale
Syntax
colorbar
colorbar('vert')
colorbar('horiz')
colorbar(h)
h = colorbar(...)
colorbar(...,'peer',axes_handle)
Description
The colorbar function displays the current colormap in the current figure and
resizes the current axes to accommodate the colorbar.
colorbar updates the most recently created colorbar or, when the current axes
does not have a colorbar, colorbar adds a new vertical colorbar.
colorbar('vert') adds a vertical colorbar to the current axes.
colorbar('horiz') adds a horizontal colorbar to the current axes.
colorbar(h) uses the axes h to create the colorbar. The colorbar is horizontal
if the width of the axes is greater than its height, as determined by the axes
Position property.
h = colorbar(...) returns a handle to the colorbar, which is an axes graphics
object.
colorbar(...,'peer',axes_handle) creates a colorbar associated with the
axes axes_handle instead of the current axes.
Remarks
colorbar works with two-dimensional and three-dimensional plots.
Examples
Display a colorbar beside the axes.
surf(peaks(30))
colormap cool
2-322
colorbar
colorbar
8
6
10
8
4
6
4
2
2
0
−2
0
−4
−6
−2
−8
30
25
30
20
15
20
15
10
10
5
5
0
See Also
−4
25
−6
0
colormap
“Color Operations” for related functions
2-323
colordef
Purpose
2colordef
Sets default property values to display different color schemes
Syntax
colordef white
colordef black
colordef none
colordef(fig,color_option)
h = colordef('new',color_option)
Description
colordef enables you to select either a white or black background for graphics
display. It sets axis lines and labels to show up against the background color.
colordef white sets the axis background color to white, the axis lines and
labels to black, and the figure background color to light gray.
colordef black sets the axis background color to black, the axis lines and
labels to white, and the figure background color to dark gray.
colordef none sets the figure coloring to that used by MATLAB Version 4
(essentially a black background).
colordef(fig,color_option) sets the color scheme of the figure identified by
the handle fig to the color option 'white', 'black', or 'none'.
h = colordef('new',color_option) returns the handle to a new figure
created with the specified color options (i.e., 'white', 'black', or 'none').
Remarks
colordef affects only subsequently drawn figures, not those currently on the
display. This is because colordef works by setting default property values (on
the root or figure level). You can list the currently set default values on the root
level with the statement:
get(0,'defaults')
You can remove all default values using the reset command:
reset(0)
See the get and reset references pages for more information.
See Also
2-324
whitebg
colordef
“Color Operations” for related functions
2-325
colormap
Purpose
2colormap
Set and get the current colormap
Syntax
colormap(map)
colormap('default')
cmap = colormap
Description
A colormap is an m-by-3 matrix of real numbers between 0.0 and 1.0. Each row
is an RGB vector that defines one color. The kth row of the colormap defines the
k-th color, where map(k,:) = [r(k) g(k) b(k)]) specifies the intensity of red,
green, and blue.
colormap(map) sets the colormap to the matrix map. If any values in map are
outside the interval [0 1], MATLAB returns the error: Colormap must have
values in [0,1].
colormap('default') sets the current colormap to the default colormap.
cmap = colormap; retrieves the current colormap. The values returned are in
the interval [0 1].
Specifying Colormaps
M-files in the color directory generate a number of colormaps. Each M-file
accepts the colormap size as an argument. For example,
colormap(hsv(128))
creates an hsv colormap with 128 colors. If you do not specify a size, MATLAB
creates a colormap the same size as the current colormap.
Supported Colormaps
MATLAB supports a number of colormaps.
• autumn varies smoothly from red, through orange, to yellow.
• bone is a grayscale colormap with a higher value for the blue component.
This colormap is useful for adding an “electronic” look to grayscale images.
• colorcube contains as many regularly spaced colors in RGB colorspace as
possible, while attempting to provide more steps of gray, pure red, pure
green, and pure blue.
2-326
colormap
• cool consists of colors that are shades of cyan and magenta. It varies
smoothly from cyan to magenta.
• copper varies smoothly from black to bright copper.
• flag consists of the colors red, white, blue, and black. This colormap
completely changes color with each index increment.
• gray returns a linear grayscale colormap.
• hot varies smoothly from black, through shades of red, orange, and yellow,
to white.
• hsv varies the hue component of the hue-saturation-value color model. The
colors begin with red, pass through yellow, green, cyan, blue, magenta, and
return to red. The colormap is particularly appropriate for displaying
periodic functions. hsv(m) is the same as hsv2rgb([h ones(m,2)]) where h
is the linear ramp, h = (0:m–1)'/m.
• jet ranges from blue to red, and passes through the colors cyan, yellow, and
orange. It is a variation of the hsv colormap. The jet colormap is associated
with an astrophysical fluid jet simulation from the National Center for
Supercomputer Applications. See the “Examples” section.
• lines produces a colormap of colors specified by the axes ColorOrder
property and a shade of gray.
• pink contains pastel shades of pink. The pink colormap provides sepia tone
colorization of grayscale photographs.
• prism repeats the six colors red, orange, yellow, green, blue, and violet.
• spring consists of colors that are shades of magenta and yellow.
• summer consists of colors that are shades of green and yellow.
• white is an all white monochrome colormap.
• winter consists of colors that are shades of blue and green.
Examples
The images and colormaps demo, imagedemo, provides an introduction to
colormaps. Select Color Spiral from the menu. This uses the pcolor function
to display a 16-by-16 matrix whose elements vary from 0 to 255 in a rectilinear
spiral. The hsv colormap starts with red in the center, then passes through
yellow, green, cyan, blue, and magenta before returning to red at the outside
end of the spiral. Selecting Colormap Menu gives access to a number of other
colormaps.
2-327
colormap
The rgbplot function plots colormap values. Try rgbplot(hsv),
rgbplot(gray), and rgbplot(hot).
The following commands display the flujet data using the jet colormap.
load flujet
image(X)
colormap(jet)
The demos directory contains a CAT scan image of a human spine. To view the
image, type the following commands:
load spine
image(X)
2-328
colormap
colormap bone
Algorithm
Each figure has its own Colormap property. colormap is an M-file that sets and
gets this property.
See Also
brighten, caxis, colormapeditor, colorbar, contrast, hsv2rgb, pcolor,
rgb2hsv, rgbplot
The Colormap property of figure graphics objects.
“Color Operations” for related functions
Coloring Mesh and Surface Plots for more information about colormaps and
other coloring methods.
2-329
colormapeditor
Purpose
2colormapeditor
Start colormap editor
Syntax
colormapeditor
Description
colormapeditor displays the current figure’s colormap as a strip of
rectangular cells in the colormap editor. Node pointers are colored cells below
the colormap strip that indicate points in the colormap where the rate of the
variation of R, G, and B values change. You can also work in the HSV
colorspace by setting the Interpolating Colorspace selector to HSV.
You can also start the colormap editor by selecting Colormap from the Edit
menu.
Node Pointer Operations
You can select and move node pointers to change a range of colors in the
colormap. The color of a node pointer remains constant as you move it, but the
colormap changes by linearly interpolating the RGB values between nodes.
Change the color at a node by double-clicking the node pointer. MATLAB
displays a color picker from which you can select a new color. After you select
a new color at a node, MATLAB reinterpolates the colors in between nodes.
2-330
Operation
How to Perform
Add a node
Click below the corresponding cell in the colormap
strip
Select a node
Left-click on the node
Select multiple
nodes
Adjacent: left-click on first node, Shift+click on the
last node
Nonadjacent: left-click on first node, Ctrl+click on
subsequent nodes
Move a node
Select and drag with the mouse or select and use
the left and right arrow keys.
colormapeditor
Operation
How to Perform
Move multiple
nodes
Select multiple nodes and use the left and right
arrow keys to move nodes as a group. Movement
stops when one of the selected nodes hits an
unselected node or an end node.
Delete a node
Select the node and then press the Delete key, or
select Delete from the Edit menu, or type Ctrl+x.
Delete multiple
nodes
Select the nodes and then press the Delete key, or
select Delete from the Edit menu, or type Ctrl+x.
Display color picker
for a node
Double click on the node pointer.
Current Color Info
When you put the mouse over a color cell or node pointer, the colormap editor
displays the following information about that colormap element:
• The element’s index in the colormap
• The value from the graphics object color data that is mapped to the node’s
color (i.e., data from the CData property of any image, patch, or surface
objects in the figure)
• The color’s RGB and HSV color value
2-331
colormapeditor
Colormap index for
color cell
Object’s CData for
color cell
RGB and HSV
values of selected
colormap element
Interpolating Colorspace
The colorspace determines what values are used to calculate the colors of cells
between nodes. For example, in the RGB colorspace, internode colors are
calculated by linearly interpolating the red, green, and blue intensity values
from one node to the next. Switching to the HSV colorspace causes the
colormap editor to recalculate the colors between nodes using the hue,
saturation, and value components of the color definition.
Note that when you switch from one colorspace to another, the color editor
preserves the number, color, and location of the node pointers, which can cause
the colormap to change.
Interpolating in HSV: Since hue is conceptually mapped about a color circle,
the interpolation between hue values can be ambiguous. To minimize this
ambiguity, the interpolation uses the shortest distance around the circle. For
example, interpolating between two nodes, one with at hue of 2 (slightly orange
red) and another with a hue of 356 (slightly magenta red), does not result in
hues 3,4,5...353,354,355 (orange/red-yellow-green-cyan-blue-magenta/red).
2-332
colormapeditor
Taking the shortest distance around the circle gives 357,358,1,2
(orange/red-red-magenta/red).
Color Data Min and Max
The Color Data Min and Color Data Max text fields enable you to specify
values for the axes CLim property. These values change the mapping of object
color data (the CData property of images, patches, and surfaces) to the
colormap. See Axes Color Limits — The Clim Property for discussion and
examples of how to use this property.
Examples
This example modifies a default MATLAB colormap so that ranges of data
values are displayed in specific ranges of color. The graph is a slice plane
illustrating a cross section of fluid flow through a jet nozzle. See the slice
reference page for more information on this type of graph.
Example Objectives
The objectives are as follows:
• Regions of flow from left to right (positive data) are mapped to colors from
yellow through orange to dark red. Yellow is slowest and dark red is the
fastest moving fluid.
• Regions that have a speed close to zero are colored green.
• Regions where the fluid is actually moving right to left (negative data) are
shades of blue (darker blue is faster).
The following picture shows the desired coloring of the slice plane. The colorbar
shows the data to color mapping.
2-333
colormapeditor
Running the Example
Note If you are viewing this documentation in the MATLAB help browser,
you can display the graph used in this example by running this M-file from
the MATLAB editor (select Run from the Debug menu).
Click Run Demo if you want to run a demonstration of the example.
Initially, the default colormap (jet) colored the slice plane, as illustrated in the
following picture. Note that this example uses a colormap that is 48 elements
to display wider bands of color (the default is 64 elements).
2-334
colormapeditor
1 Start the colormap editor using the colormapeditor command. The color
map editor displays the current figure’ s colormap, as shown in the following
picture.
2-335
colormapeditor
2 Since we want the regions of left-to-right flow (positive speed) to range from
yellow to dark red, we can delete the cyan node pointer. To do this, first
select it by clicking with the left mouse button and press Delete. The
colormap now looks like this.
2-336
colormapeditor
The Immediate Apply box is checked so the graph displays the results of
the changes made to the colormap.
2-337
colormapeditor
3 We want the fluid speed values around zero to stand out, so we need to find
the color cell where the negative-to-positive transition occurs. Dragging the
cursor over the color strip enables you to read the data values in the
Current Color Info panel.
In this case, cell 10 is the first positive value, so we click below that cell and
create a node pointer. Double-clicking on the node pointer displays the color
picker. Set the color of this node to green.
2-338
colormapeditor
The graph continues to update to the modified colormap.
2-339
colormapeditor
4 In the current state, the colormap colors are interpolated from the green
node to the yellowish node about 20 cells away. We actually want only the
single cell that is centered around zero to be colored green. To limit the color
green to one cell, move the blue and yellow node pointers next to the green
pointer.
5 Before making further adjustments to the colormap, we need to move the
green cell so that it is centered around zero. Use the colorbar to locate the
green cell.
2-340
colormapeditor
Note that green cell is not
centered around zero.
To recenter the green cell around zero, select the blue, green, and yellow
node pointers (left-click on blue, Shift+click on yellow) and move them as a
group using the left arrow key. Watch the colorbar in the figure window to
see when the green color is centered around zero.
2-341
colormapeditor
The slice plane now has the desired range of colors for negative, zero, and
positive data.
2-342
colormapeditor
Green cell is now centered
around zero.
6 Increase the orange-red coloring in the slice by moving the red node pointer
towards the yellow node.
2-343
colormapeditor
7 Darken the end points to bring out more detail in the extremes of the data.
Double-click on the end nodes to display the color picker. Set the red end
point to the RGB value [50 0 0] and set the blue end point to the RGB value
[0 0 50].
The slice plane coloring now matches the example objectives.
2-344
colormapeditor
See Also
colormap
Color Operations for related functions.
2-345
ColorSpec
Purpose
2ColorSpec
Description
ColorSpec is not a command; it refers to the three ways in which you specify
color in MATLAB:
Color specification
• RGB triple
• Short name
• Long name
The short names and long names are MATLAB strings that specify one of eight
predefined colors. The RGB triple is a three-element row vector whose
elements specify the intensities of the red, green, and blue components of the
color; the intensities must be in the range [0 1]. The following table lists the
predefined colors and their RGB equivalents.
RGB Value
Short Name
Long Name
[1 1 0]
y
yellow
[1 0 1]
m
magenta
[0 1 1]
c
cyan
[1 0 0]
r
red
[0 1 0]
g
green
[0 0 1]
b
blue
[1 1 1]
w
white
[0 0 0]
k
black
Remarks
The eight predefined colors and any colors you specify as RGB values are not
part of a figure’s colormap, nor are they affected by changes to the figure’s
colormap. They are referred to as fixed colors, as opposed to colormap colors.
Examples
To change the background color of a figure to green, specify the color with a
short name, a long name, or an RGB triple. These statements generate
equivalent results:
whitebg('g')
2-346
ColorSpec
whitebg('green')
whitebg([0 1 0]);
You can use ColorSpec anywhere you need to define a color. For example, this
statement changes the figure background color to pink:
set(gcf,'Color',[1,0.4,0.6])
See Also
bar, bar3, colordef, colormap, fill, fill3, whitebg
“Color Operations” for related functions
2-347
colperm
Purpose
2colperm
Sparse column permutation based on nonzero count
Syntax
j = colperm(S)
Description
j = colperm(S) generates a permutation vector j such that the columns of
S(:,j) are ordered according to increasing count of nonzero entries. This is
sometimes useful as a preordering for LU factorization; in this case use
lu(S(:,j)).
If S is symmetric, then j = colperm(S) generates a permutation j so that both
the rows and columns of S(j,j) are ordered according to increasing count of
nonzero entries. If S is positive definite, this is sometimes useful as a
preordering for Cholesky factorization; in this case use chol(S(j,j)).
Algorithm
The algorithm involves a sort on the counts of nonzeros in each column.
Examples
The n-by-n arrowhead matrix
A = [ones(1,n); ones(n-1,1) speye(n-1,n-1)]
has a full first row and column. Its LU factorization, lu(A), is almost
completely full. The statement
j = colperm(A)
returns j = [2:n 1]. So A(j,j) sends the full row and column to the bottom
and the rear, and lu(A(j,j)) has the same nonzero structure as A itself.
On the other hand, the Bucky ball example,
B = bucky
has exactly three nonzero elements in each row and column, so
j = colperm(B) is the identity permutation and is no help at all for reducing
fill-in with subsequent factorizations.
See Also
2-348
chol, colamd, colmmd, lu, spparms, symamd, symmmd, symrcm
comet
Purpose
2comet
Two-dimensional comet plot
Syntax
comet(y)
comet(x,y)
comet(x,y,p)
Description
A comet plot is an animated graph in which a circle (the comet head) traces the
data points on the screen. The comet body is a trailing segment that follows the
head. The tail is a solid line that traces the entire function.
comet(y) displays a comet plot of the vector y.
comet(x,y) displays a comet plot of vector y versus vector x.
comet(x,y,p) specifies a comet body of length p*length(y). p defaults to 0.1.
Remarks
Note that the trace left by comet is created by using an EraseMode of none,
which means you cannot print the plot (you get only the comet head) and it
disappears if you cause a redraw (e.g., by resizing the window).
Examples
Create a simple comet plot:
t = 0:.01:2*pi;
x = cos(2∗t).*(cos(t).^2);
y = sin(2∗t).*(sin(t).^2);
comet(x,y);
See Also
comet3
“Direction and Velocity Plots” for related functions
2-349
comet3
Purpose
2comet3
Three-dimensional comet plot
Syntax
comet3(z)
comet3(x,y,z)
comet3(x,y,z,p)
Description
A comet plot is an animated graph in which a circle (the comet head) traces the
data points on the screen. The comet body is a trailing segment that follows the
head. The tail is a solid line that traces the entire function.
comet3(z) displays a three-dimensional comet plot of the vector z.
comet3(x,y,z) displays a comet plot of the curve through the points
[x(i),y(i),z(i)].
comet3(x,y,z,p) specifies a comet body of length p∗length(y).
Remarks
Note that the trace left by comet3 is created by using an EraseMode of none,
which means you cannot print the plot (you get only the comet head) and it
disappears if you cause a redraw (e.g., by resizing the window).
Examples
Create a three-dimensional comet plot.
t = -10*pi:pi/250:10*pi;
comet3((cos(2*t).^2).*sin(t),(sin(2*t).^2).*cos(t),t);
See Also
comet
“Direction and Velocity Plots” for related functions
2-350
compan
Purpose
2compan
Companion matrix
Syntax
A = compan(u)
Description
A = compan(u) returns the corresponding companion matrix whose first row is
-u(2:n)/u(1), where u is a vector of polynomial coefficients. The eigenvalues
of compan(u) are the roots of the polynomial.
Examples
The polynomial ( x – 1 ) ( x – 2 ) ( x + 3 ) = x 3 – 7x + 6 has a companion matrix
given by
u = [1 0 -7 6]
A = compan(u)
A =
0
7
-6
1
0
0
0
1
0
The eigenvalues are the polynomial roots:
eig(compan(u))
ans =
-3.0000
2.0000
1.0000
This is also roots(u).
See Also
eig, poly, polyval, roots
2-351
compass
Purpose
2compass
Plot arrows emanating from the origin
Syntax
compass(X,Y)
compass(Z)
compass(...,LineSpec)
h = compass(...)
Description
A compass plot displays direction or velocity vectors as arrows emanating from
the origin. X, Y, and Z are in Cartesian coordinates and plotted on a circular
grid.
compass(X,Y) displays a compass plot having n arrows, where n is the number
of elements in X or Y. The location of the base of each arrow is the origin. The
location of the tip of each arrow is a point relative to the base and determined
by [X(i),Y(i)].
compass(Z) displays a compass plot having n arrows, where n is the number of
elements in Z. The location of the base of each arrow is the origin. The location
of the tip of each arrow is relative to the base as determined by the real and
imaginary components of Z. This syntax is equivalent to
compass(real(Z),imag(Z)).
compass(...,LineSpec) draws a compass plot using the line type, marker
symbol, and color specified by LineSpec.
h = compass(...) returns handles to line objects.
Examples
Draw a compass plot of the eigenvalues of a matrix.
Z = eig(randn(20,20));
compass(Z)
2-352
compass
90
5.2689
60
120
4.2151
3.1613
30
150
2.1076
1.0538
180
0
210
330
240
300
270
See Also
feather, LineSpec, rose
“Direction and Velocity Plots” for related functions
Compass Plots for another example
2-353
complex
Purpose
2complex
Construct complex data from real and imaginary components
Syntax
c = complex(a,b)
c = complex(a)
Description
c = complex(a,b) creates a complex output, c, from the two real inputs.
c = a + bi
The output is the same size as the inputs, which must be scalars or equally
sized vectors, matrices, or multi-dimensional arrays of the same data type.
Note If b is all zeros, c is complex and the value of all its imaginary
components is 0. In contrast, the result of the addition a+0i returns a strictly
real result.
c = complex(a) for real a returns the complex result c with real part a and 0
as the value of all imaginary components. Even though the value of all
imaginary components is 0, c is complex and isreal(c) returns false.
The complex function provides a useful substitute for expressions such as
a + i*b
or
a + j*b
in cases when the names “i” and “j” may be used for other variables (and do
not equal – 1 ), when a and b are not double-precision, or when b is all zero.
Example
Create complex uint8 vector from two real uint8 vectors.
a = uint8([1;2;3;4])
b = uint8([2;2;7;7])
c = complex(a,b)
c =
1.0000
2.0000
3.0000
4.0000
2-354
+
+
+
+
2.0000i
2.0000i
7.0000i
7.0000i
complex
See Also
abs, angle, conj, i, imag, isreal, j, real
2-355
computer
Purpose
2computer
Identify information about computer on which MATLAB is running
Syntax
str = computer
[str,maxsize] = computer
[str,maxsize,endian] = computer
Description
str = computer returns the string str with the computer type on which
MATLAB is running.
[str,maxsize] = computer returns the integer maxsize, which contains the
maximum number of elements allowed in an array with this version of
MATLAB.
[str,maxsize,endian] = computer also returns either 'L' for little endian
byte ordering or 'B' for big endian byte ordering.
The list of supported computers changes as new computers are added and
others become obsolete. A typical list follows.
str
Computer
ALPHA
Compaq Alpha (OSF1)
HP700
HP 9000/700 (HP-UX 10.20)
HPUX
HP PA-RISC (HP-UX 11.00)
IBM_RS
IBM RS6000 workstation (AIX)
GLNX86
Linux on PC
PCWIN
Microsoft Windows
SGI
Silicon Graphics (IRIX/IRIX64)
SOL2
Sun Solaris 2 SPARC workstation
Remarks
SGI64 users prior to R12 must migrate to SGI with R12.
LNX86 users prior to R12 must migrate to GLNX86 with R12.
See Also
ispc, isunix
2-356
cond
Purpose
2cond
Condition number with respect to inversion
Syntax
c = cond(X)
c = cond(X,p)
Description
The condition number of a matrix measures the sensitivity of the solution of a
system of linear equations to errors in the data. It gives an indication of the
accuracy of the results from matrix inversion and the linear equation solution.
Values of cond(X) and cond(X,p) near 1 indicate a well-conditioned matrix.
c = cond(X) returns the 2-norm condition number, the ratio of the largest
singular value of X to the smallest.
c = cond(X,p) returns the matrix condition number in p-norm:
norm(X,p) * norm(inv(X),p
If p is...
Then cond(X,p) returns the...
1
1-norm condition number
2
2-norm condition number
'fro'
Frobenius norm condition number
inf
Infinity norm condition number
Algorithm
The algorithm for cond (when p = 2) uses the singular value decomposition,
svd.
See Also
condeig, condest, norm, normest, rank, rcond, svd
References
[1] Anderson, E., Z. Bai, C. Bischof, S. Blackford, J. Demmel, J. Dongarra,
J. Du Croz, A. Greenbaum, S. Hammarling, A. McKenney, and D. Sorensen,
LAPACK User’s Guide
(http://www.netlib.org/lapack/lug/lapack_lug.html), Third Edition,
SIAM, Philadelphia, 1999.
2-357
condeig
Purpose
2condeig
Condition number with respect to eigenvalues
Syntax
c = condeig(A)
[V,D,s] = condeig(A)
Description
c = condeig(A) returns a vector of condition numbers for the eigenvalues of A.
These condition numbers are the reciprocals of the cosines of the angles
between the left and right eigenvectors.
[V,D,s] = condeig(A) is equivalent to
[V,D] = eig(A);
s = condeig(A);
Large condition numbers imply that A is near a matrix with multiple
eigenvalues.
See Also
2-358
balance, cond, eig
condest
Purpose
2condest
1-norm condition number estimate
Syntax
c = condest(A)
[c,v] = condest(A)
Description
c = condest(A) computes a lower bound C for the 1-norm condition number of
a square matrix A.
c = condest(A,t) changes t, a positive integer parameter equal to the
number of columns in an underlying iteration matrix. Increasing the number
of columns usually gives a better condition estimate but increases the cost. The
default is t = 2, which almost always gives an estimate correct to within a
factor 2.
[c,v] = condest(A) also computes a vector v which is an approximate null
vector if c is large. v satisfies norm(A*v,1) = norm(A,1)*norm(v,1)/c.
Note condest invokes rand. If repeatable results are required then invoke
rand('state',j), for some j, before calling this function.
This function is particularly useful for sparse matrices.
condest uses block 1-norm power method of Higham and Tisseur [1].
See Also
cond, norm, normest
Reference
[1] Higham, N. J. and F. Tisseur, “A Block Algorithm for Matrix 1-Norm
Estimation, with an Application to 1-Norm Pseudospectra,” SIAM Journal
Matrix Anal. Appl., Vol. 21, No. 4, 2000, pp.1185-1201.
2-359
coneplot
Purpose
2coneplot
Plot velocity vectors as cones in a 3-D vector field
Syntax
coneplot(X,Y,Z,U,V,W,Cx,Cy,Cz)
coneplot(U,V,W,Cx,Cy,Cz)
coneplot(...,s)
coneplot(...,color)
coneplot(...,'quiver')
coneplot(...,'method')
coneplot(X,Y,Z,U,V,W,'nointerp')
h = coneplot(...)
Description
coneplot(X,Y,Z,U,V,W,Cx,Cy,Cz) plots velocity vectors as cones pointing in
the direction of the velocity vector and having a length proportional to the
magnitude of the velocity vector.
• X, Y, Z define the coordinates for the vector field.
• U, V, W define the vector field. These arrays must be the same size, monotonic,
and 3-D plaid (such as the data produced by meshgrid).
• Cx, Cy, Cz define the location of the cones in vector field. The section Starting
Points for Stream Plots in Visualization Techniques provides more
information on defining starting points.
coneplot(U,V,W,Cx,Cy,Cz) (omitting the X, Y, and Z arguments) assumes
[X,Y,Z] = meshgrid(1:n,1:m,1:p) where [m,n,p]= size(U).
coneplot(...,s) MATLAB automatically scales the cones to fit the graph and
then stretches them by the scale factor s. If you do not specify a value for s,
MATLAB uses a value of 1. Use s = 0 to plot the cones without automatic
scaling.
coneplot(...,color) interpolates the array color onto the vector field and
then colors the cones according to the interpolated values. The size of the color
array must be the same size as the U, V, W arrays. This option works only with
cones (i.e., not with the quiver option).
coneplot(...,'quiver') draws arrows instead of cones (see quiver3 for an
illustration of a quiver plot).
2-360
coneplot
coneplot(...,'method') specifies the interpolation method to use. method
can be: linear, cubic, nearest. linear is the default (see interp3 for a
discussion of these interpolation methods)
coneplot(X,Y,Z,U,V,W,'nointerp') does not interpolate the positions of the
cones into the volume. The cones are drawn at positions defined by X, Y, Z and
are oriented according to U, V, W. Arrays X, Y, Z, U, V, W must all be the same size.
h = coneplot(...) returns the handle to the patch object used to draw the
cones. You can use the set command to change the properties of the cones.
Remarks
coneplot automatically scales the cones to fit the graph, while keeping them
in proportion to the respective velocity vectors.
It is usually best to set the data aspect ratio of the axes before calling coneplot.
You can set the ratio using the daspect command,
daspect([1,1,1])
Examples
This example plots the velocity vector cones for vector volume data
representing the motion of air through a rectangular region of space. The final
graph employs a number of enhancements to visualize the data more
effectively. These include:
• Cone plots indicate the magnitude and direction of the wind velocity.
• Slice planes placed at the limits of the data range provide a visual context for
the cone plots within the volume.
• Directional lighting provides visual queues as to the orientation of the cones.
• View adjustments compose the scene to best reveal the information content
of the data by selecting the view point, projection type, and magnification.
1. Load and Inspect Data
The winds data set contains six 3-D arrays: u, v, and w specify the vector
components at each of the coordinate specified in x, y, and z. The coordinates
define a lattice grid structure where the data is sampled within the volume.
2-361
coneplot
It is useful to establish the range of the data to place the slice planes and to
specify where you want the cone plots (min, max).
load
xmin
xmax
ymin
ymax
zmin
wind
= min(x(:));
= max(x(:));
= min(y(:));
= max(y(:));
= min(z(:));
2. Create the Cone Plot
• Decide where in data space you want to plot cones. This example selects the
full range of x and y in eight steps and the range 3 to 15 in four steps in z
(linspace, meshgrid).
• Use daspect to set the data aspect ratio of the axes before calling coneplot
so MATLAB can determine the proper size of the cones.
• Draw the cones, setting the scale factor to 5 to make the cones larger than
the default size.
• Set the coloring of each cone (FaceColor, EdgeColor).
daspect([2,2,1])
xrange = linspace(xmin,xmax,8);
yrange = linspace(ymin,ymax,8);
zrange = 3:4:15;
[cx cy cz] = meshgrid(xrange,yrange,zrange);
hcones = coneplot(x,y,z,u,v,w,cx,cy,cz,5);
set(hcones,'FaceColor','red','EdgeColor','none')
2-362
coneplot
3. Add the Slice Planes
• Calculate the magnitude of the vector field (which represents wind speed) to
generate scalar data for the slice command.
• Create slice planes along the x-axis at xmin and xmax, along the y-axis at
ymax, and along the z-axis at zmin.
• Specify interpolated face color so the slice coloring indicates wind speed and
do not draw edges (hold, slice, FaceColor, EdgeColor).
hold on
wind_speed = sqrt(u.^2 + v.^2 + w.^2);
hsurfaces = slice(x,y,z,wind_speed,[xmin,xmax],ymax,zmin);
set(hsurfaces,'FaceColor','interp','EdgeColor','none')
hold off
4. Define the View
• Use the axis command to set the axis limits equal to the range of the data.
• Orient the view to azimuth = 30 and elevation = 40 (rotate3d is a useful
command for selecting the best view).
• Select perspective projection to provide a more realistic looking volume
(camproj).
• Zoom in on the scene a little to make the plot as large as possible (camzoom).
axis tight; view(30,40); axis off
camproj perspective; camzoom(1.5)
5. Add Lighting to the Scene
The light source affects both the slice planes (surfaces) and the cone plots
(patches). However, you can set the lighting characteristics of each
independently.
• Add a light source to the right of the camera and use Phong lighting give the
cones and slice planes a smooth, three-dimensional appearance (camlight,
lighting).
• Increase the value of the AmbientStrength property for each slice plane to
improve the visibility of the dark blue colors. (Note that you can also specify
a different colormap to change to coloring of the slice planes.)
2-363
coneplot
• Increase the value of the DiffuseStrength property of the cones to brighten
particularly those cones not showing specular reflections.
camlight right; lighting phong
set(hsurfaces,'AmbientStrength',.6)
set(hcones,'DiffuseStrength',.8)
See Also
isosurface, patch, reducevolume, smooth3, streamline, stream2, stream3,
subvolume
[2] “Volume Visualization” for related functions
2-364
conj
Purpose
2conj
Complex conjugate
Syntax
ZC = conj(Z)
Description
ZC = conj(Z) returns the complex conjugate of the elements of Z.
Algorithm
If Z is a complex array:
conj(Z) = real(Z) - i*imag(Z)
See Also
i, j, imag, real
2-365
continue
Purpose
2continue
Pass control to the next iteration of for or while loop
Syntax
continue
Description
continue passes control to the next iteration of the for or while loop in which
it appears, skipping any remaining statements in the body of the loop.
In nested loops, continue passes control to the next iteration of the for or
while loop enclosing it.
Examples
The example below shows a continue loop that counts the lines of code in the
file, magic.m, skipping all blank lines and comments. A continue statement is
used to advance to the next line in magic.m without incrementing the count
whenever a blank line or comment line is encountered.
fid = fopen('magic.m','r');
count = 0;
while ~feof(fid)
line = fgetl(fid);
if isempty(line) | strncmp(line,'%',1)
continue
end
count = count + 1;
end
disp(sprintf('%d lines',count));
See Also
2-366
for, while, end, break, return
contour
Purpose
2contour
Two-dimensional contour plot
Syntax
contour(Z)
contour(Z,n)
contour(Z,v)
contour(X,Y,Z)
contour(X,Y,Z,n)
contour(X,Y,Z,v)
contour(...,LineSpec)
[C,h] = contour(...)
Description
A contour plot displays isolines of matrix Z. Label the contour lines using
clabel.
contour(Z) draws a contour plot of matrix Z, where Z is interpreted as heights
with respect to the x-y plane. Z must be at least a 2-by-2 matrix. The number
of contour levels and the values of the contour levels are chosen automatically
based on the minimum and maximum values of Z. The ranges of the x- and
y-axis are [1:n] and [1:m], where [m,n] = size(Z).
contour(Z,n) draws a contour plot of matrix Z with n contour levels.
contour(Z,v) draws a contour plot of matrix Z with contour lines at the data
values specified in vector v. The number of contour levels is equal to length(v).
To draw a single contour of level i, use contour(Z,[i i]).
contour(X,Y,Z), contour(X,Y,Z,n), and contour(X,Y,Z,v) draw contour
plots of Z. X and Y specify the x- and y-axis limits. When X and Y are matrices,
they must be the same size as Z, in which case they specify a surface as surf
does.
contour(...,LineSpec) draws the contours using the line type and color
specified by LineSpec. contour ignores marker symbols.
[C,h] = contour(...) returns the contour matrix C (see contourc) and a
vector of handles to graphics objects. clabel uses the contour matrix C to create
the labels. contour creates patch graphics objects unless you specify LineSpec,
in which case contour creates line graphics objects.
2-367
contour
Remarks
If you do not specify LineSpec, colormap and caxis control the color.
If X or Y is irregularly spaced, contour calculates contours using a regularly
spaced contour grid, then transforms the data to X or Y.
Examples
To view a contour plot of the function
z = xe ( – x
2
– y2 )
over the range –2 ≤ x ≤ 2, –2 ≤ y ≤ 3, create matrix Z using the statements
[X,Y] = meshgrid(–2:.2:2,–2:.2:3);
Z = X.∗exp(–X.^2–Y.^2);
Then, generate a contour plot of Z.
[C,h] = contour(X,Y,Z);
clabel(C,h)
colormap cool
3
2.5
2
1.5
0.1
1
−0.
1
0
0.2
−0.1
2
−0.
0.5
0.4
0
0.3
.3
−0.5
0.1
−0
−0.2
0.2
0.1
−1
−0.1
0
−1.5
−2
−2
−1.5
−1
−0.5
0
0.5
1
1.5
2
View the same function over the same range with 20 evenly spaced contour
lines and colored with the default colormap jet.
2-368
contour
contour(X,Y,Z,20)
3
2.5
2
1.5
1
0.5
0
−0.5
−1
−1.5
−2
−2
−1.5
−1
−0.5
0
0.5
1
1.5
2
Use interp2 to create smoother contours. Also set the contour label text
BackgroundColor to a light yellow and the EdgeColor to light gray.
Z = magic(4);
[C,h] = contour(interp2(Z,4));
h = clabel(C,h);
set(h,'BackgroundColor',[1 1 .6],...
'Edgecolor',[.7 .7 .7])
2-369
contour
6
6
8
12
40
4
10
8
2
10
45
14
14
12
10
35
8
8
10
8
8
8
8
30
25
10
20
6
10
10
8
8
10
10
15
4
20
25
30
12
5
4
6
8
10
See Also
12
14
5
8
6
10
15
35
40
clabel, contour3, contourc, contourf, interp2, quiver
“Contour Plots” category for related functions
Contour Plots section for more examples
2-370
45
contour3
Purpose
2contour3
Three-dimensional contour plot
Syntax
contour3(Z)
contour3(Z,n)
contour3(Z,v)
contour3(X,Y,Z)
contour3(X,Y,Z,n)
contour3(X,Y,Z,v)
contour3(...,LineSpec)
[C,h] = contour3(...)
Description
contour3 creates a three-dimensional contour plot of a surface defined on a
rectangular grid.
contour3(Z) draws a contour plot of matrix Z in a three-dimensional view. Z is
interpreted as heights with respect to the x-y plane. Z must be at least a 2-by-2
matrix. The number of contour levels and the values of contour levels are
chosen automatically. The ranges of the x- and y-axis are [1:n] and [1:m],
where [m,n] = size(Z).
contour3(Z,n) draws a contour plot of matrix Z with n contour levels in a
three-dimensional view.
contour3(Z,v) draws a contour plot of matrix Z with contour lines at the
values specified in vector v. The number of contour levels is equal to length(v).
To draw a single contour of level i, use contour(Z,[i i]).
contour3(X,Y,Z), contour3(X,Y,Z,n), and contour3(X,Y,Z,v) use X and Y
to define the x- and y-axis limits. If X is a matrix, X(1,:) defines the x-axis. If
Y is a matrix, Y(:,1) defines the y-axis. When X and Y are matrices, they must
be the same size as Z, in which case they specify a surface as surf does.
contour3(...,LineSpec) draws the contours using the line type and color
specified by LineSpec.
[C,h] = contour3(...) returns the contour matrix C as described in the
function contourc and a column vector containing handles to graphics objects.
contour3 creates patch graphics objects unless you specify LineSpec, in which
case contour3 creates line graphics objects.
2-371
contour3
Remarks
If you do not specify LineSpec, colormap and caxis control the color.
If X or Y is irregularly spaced, contour3 calculates contours using a regularly
spaced contour grid, then transforms the data to X or Y.
Examples
Plot the three-dimensional contour of a function and superimpose a surface
plot to enhance visualization of the function.
[X,Y] = meshgrid([-2:.25:2]);
Z = X.*exp(-X.^2-Y.^2);
contour3(X,Y,Z,30)
surface(X,Y,Z,’EdgeColor’,[.8 .8 .8],’FaceColor’,’none’)
grid off
view(-15,25)
colormap cool
0.5
0
−0.5
2
1
0
−1
−2
See Also
−2
−1.5
−1
−0.5
0
contour, contourc, meshc, meshgrid, surfc
“Contour Plots” category for related functions
Contour Plots section for more examples
2-372
0.5
1
1.5
2
contourc
Purpose
2contourc
Low-level contour plot computation
Syntax
C
C
C
C
C
C
Description
contourc calculates the contour matrix C used by contour, contour3, and
contourf. The values in Z determine the heights of the contour lines with
=
=
=
=
=
=
contourc(Z)
contourc(Z,n)
contourc(Z,v)
contourc(x,y,Z)
contourc(x,y,Z,n)
contourc(x,y,Z,v)
respect to a plane. The contour calculations use a regularly spaced grid
determined by the dimensions of Z.
C = contourc(Z) computes the contour matrix from data in matrix Z, where Z
must be at least a 2-by-2 matrix. The contours are isolines in the units of Z. The
number of contour lines and the corresponding values of the contour lines are
chosen automatically.
C = contourc(Z,n) computes contours of matrix Z with n contour levels.
C = contourc(Z,v) computes contours of matrix Z with contour lines at the
values specified in vector v. The length of v determines the number of contour
levels. To compute a single contour of level i, use contourc(Z,[i i]).
C = contourc(x,y,Z), C = contourc(x,y,Z,n), and C = contourc(x,y,Z,v)
compute contours of Z using vectors x and y to determine the x- and y-axis
limits. x and y must be monotonically increasing.
Remarks
C is a two-row matrix specifying all the contour lines. Each contour line defined
in matrix C begins with a column that contains the value of the contour
(specified by v and used by clabel), and the number of (x,y) vertices in the
contour line. The remaining columns contain the data for the (x,y)pairs.
C = [ value1 xdata(1) xdata(2)...value2 xdata(1) xdata(2)...;
dim1
ydata(1) ydata(2)...dim2
ydata(1) ydata(2)...]
Specifying irregularly spaced x and y vectors is not the same as contouring
irregularly spaced data. If x or y is irregularly spaced, contourc calculates
2-373
contourc
contours using a regularly spaced contour grid, then transforms the data to x
or y.
See Also
clabel, contour, contour3, contourf
“Contour Plots” for related functions
The Contouring Algorithm for more information
2-374
contourf
Purpose
2contourf
Filled two-dimensional contour plot
Syntax
contourf(Z)
contourf(Z,n)
contourf(Z,v)
contourf(X,Y,Z)
contourf(X,Y,Z,n)
contourf(X,Y,Z,v)
[C,h,CF] = contourf(...)
Description
A filled contour plot displays isolines calculated from matrix Z and fills the
areas between the isolines using constant colors. The color of the filled areas
depends on the current figure’s colormap.
contourf(Z) draws a contour plot of matrix Z, where Z is interpreted as
heights with respect to a plane. Z must be at least a 2-by-2 matrix. The number
of contour lines and the values of the contour lines are chosen automatically.
contourf(Z,n) draws a contour plot of matrix Z with n contour levels.
contourf(Z,v) draws a contour plot of matrix Z with contour levels at the
values specified in vector v.
contourf(X,Y,Z), contourf(X,Y,Z,n), and contourf(X,Y,Z,v) produce
contour plots of Z using X and Y to determine the x- and y-axis limits. When X
and Y are matrices, they must be the same size as Z, in which case they specify
a surface as surf does.
[C,h,CF] = contourf(...) returns the contour matrix C as calculated by the
function contourc and used by clabel, a vector of handles h to patch graphics
objects, and a contour matrix CF for the filled areas.
Remarks
If X or Y is irregularly spaced, contourf calculates contours using a regularly
spaced contour grid, then transforms the data to X or Y.
Examples
Create a filled contour plot of the peaks function.
[C,h] = contourf(peaks(20),10);
2-375
contourf
colormap autumn
20
18
16
14
12
10
8
6
4
2
2
See Also
4
6
8
10
12
clabel, contour, contour3, contourc, quiver
“Contour Plots” for related functions
2-376
14
16
18
20
contourslice
Purpose
2contourslice
Draw contours in volume slice planes
Syntax
contourslice(X,Y,Z,V,Sx,Sy,Sz)
contourslice(X,Y,Z,V,Xi,Yi,Zi)
contourslice(V,Sx,Sy,Sz), contourslice(V,Xi,Yi,Zi)
contourslice(...,n)
contourslice(...,cvals)
contourslice(...,[cv cv])
contourslice(...,'method')
h = contourslice(...)
Description
contourslice(X,Y,Z,V,Sx,Sy,Sz) draws contours in the x-, y-, and z-axis
aligned planes at the points in the vectors Sx, Sy, Sz. The arrays X, Y, and Z
define the coordinates for the volume V and must be monotonic and 3-D plaid
(such as the data produced by meshgrid) The color at each contour is
determined by the volume V, which must be an m-by-n-by-p volume array.
contourslice(X,Y,Z,V,Xi,Yi,Zi) draws contours through the volume V
along the surface defined by the arrays Xi,Yi,Zi.
contourslice(V,Sx,Sy,Sz) and contourslice(V,Xi,Yi,Zi) (omitting the X,
Y, and Z arguments) assumes [X,Y,Z] = meshgrid(1:n,1:m,1:p) where
[m,n,p]= size(v).
contourslice(...,n) draws n contour lines per plane, overriding the
automatic value.
contourslice(...,cvals) draws length(cval) contour lines per plane at the
values specified in vector cvals.
contourslice(...,[cv cv]) computes a single contour per plane at the level
cv.
contourslice(...,'method') specifies the interpolation method to use.
method can be: linear, cubic, nearest. nearest is the default except when the
contours are being drawn along the surface defined by Xi, Yi, Zi, in which case
linear is the default (see interp3 for a discussion of these interpolation
methods).
h = contourslice(...) returns a vector of handles to patch objects that are
used to implement the contour lines.
2-377
contourslice
Examples
This example uses the flow data set to illustrate the use of contoured slice
planes (type doc flow for more information on this data set). Notice that this
example:
• Specifies a vector of length = 9 for Sx, an empty vector for the Sy, and a
scalar value (0) for Sz. This creates nine contour plots along the x direction
in the y-z plane, and one in the x-y plane at z = 0.
• Uses linspace to define a ten-element linearly spaced vector of values from
-8 to 2 that specifies the number of contour lines to draw at each interval.
• Defines the view and projection type (camva, camproj, campos)
• Sets figure (gcf) and axes (gca) characteristics.
[x y z v] = flow;
h = contourslice(x,y,z,v,[1:9],[],[0],linspace(-8,2,10));
axis([0,10,-3,3,-3,3]); daspect([1,1,1])
camva(24); camproj perspective;
campos([-3,-15,5])
set(gcf,'Color',[.5,.5,.5],'Renderer','zbuffer')
set(gca,'Color','black','XColor','white', ...
'YColor','white','ZColor','white')
box on
2-378
contourslice
3
2
1
0
−1
−2
−3
3
2
1
8
9
10
7
0
6
5
−1
4
3
−2
2
1
See Also
isosurface, smooth3, subvolume, reducevolume
“Volume Visualization” for related functions
2-379
contrast
Purpose
2contrast
Grayscale colormap for contrast enhancement
Syntax
cmap = contrast(X)
cmap = contrast(X,m)
Description
The contrast function enhances the contrast of an image. It creates a new gray
colormap, cmap, that has an approximately equal intensity distribution. All
three elements in each row are identical.
cmap = contrast(X) returns a gray colormap that is the same length as the
current colormap.
cmap = contrast(X,m) returns an m-by-3 gray colormap.
Examples
Add contrast to the clown image defined by X.
load clown;
cmap = contrast(X);
image(X);
colormap(cmap);
See Also
brighten, colormap, image
“Colormaps” for related functions
2-380
conv
Purpose
2conv
Convolution and polynomial multiplication
Syntax
w = conv(u,v)
Description
w = conv(u,v) convolves vectors u and v. Algebraically, convolution is the
same operation as multiplying the polynomials whose coefficients are the
elements of u and v.
Definition
Let m = length(u) and n = length(v). Then w is the vector of length m+n-1
whose kth element is
w(k) =
∑ u ( j )v ( k + 1 – j )
j
The sum is over all the values of j which lead to legal subscripts for u(j) and
v(k+1-j), specifically j = max(1,k+1-n): min(k,m). When m = n, this gives
w(1) = u(1)*v(1)
w(2) = u(1)*v(2)+u(2)*v(1)
w(3) = u(1)*v(3)+u(2)*v(2)+u(3)*v(1)
...
w(n) = u(1)*v(n)+u(2)*v(n-1)+ ... +u(n)*v(1)
...
w(2*n-1) = u(n)*v(n)
Algorithm
The convolution theorem says, roughly, that convolving two sequences is the
same as multiplying their Fourier transforms. In order to make this precise, it
is necessary to pad the two vectors with zeros and ignore roundoff error. Thus,
if
X = fft([x zeros(1,length(y)-1)])
and
Y = fft([y zeros(1,length(x)-1)])
then conv(x,y) = ifft(X.*Y)
See Also
conv2, convn, deconv, filter
convmtx and xcorr in the Signal Processing Toolbox
2-381
conv2
Purpose
2conv2
Two-dimensional convolution
Syntax
C = conv2(A,B)
C = conv2(hcol,hrow,A)
C = conv2(...,'shape')
Description
C = conv2(A,B) computes the two-dimensional convolution of matrices A and
B. If one of these matrices describes a two-dimensional finite impulse response
(FIR) filter, the other matrix is filtered in two dimensions.
The size of C in each dimension is equal to the sum of the corresponding
dimensions of the input matrices, minus one. That is, if the size of A is [ma,na]
and the size of B is [mb,nb], then the size of C is [ma+mb-1,na+nb-1].
C = conv2(hcol,hrow,A) convolves A first with the vector hcol along the rows
and then with the vector hrow along the columns. If hcol is a column vector and
hrow is a row vector, this case is the same as C = conv2(hcol*hrow,A).
C = conv2(...,'shape') returns a subsection of the two-dimensional
convolution, as specified by the shape parameter:
Algorithm
full
Returns the full two-dimensional convolution (default).
same
Returns the central part of the convolution of the same size as A.
valid
Returns only those parts of the convolution that are computed
without the zero-padded edges. Using this option, C has size
[ma-mb+1,na-nb+1] when all(size(A) >= size(B)). Otherwise
conv2 returns [].
conv2 uses a straightforward formal implementation of the two-dimensional
convolution equation in spatial form. If a and b are functions of two discrete
variables, n 1 and n 2 , then the formula for the two-dimensional convolution of
a and b is
c ( n 1, n 2 ) =
∞
∑
∞
∑
k1 = –∞ k2 = –∞
a ( k 1, k 2 ) b ( n 1 – k 1, n 2 – k 2 )
In practice however, conv2 computes the convolution for finite intervals.
2-382
conv2
Note that matrix indices in MATLAB always start at 1 rather than 0.
Therefore, matrix elements A(1,1), B(1,1), and C(1,1) correspond to
mathematical quantities a(0,0), b(0,0), and c(0,0).
Examples
Example 1. For the 'same' case, conv2 returns the central part of the
convolution. If there are an odd number of rows or columns, the "center" leaves
one more at the beginning than the end.
This example first computes the convolution of A using the default ('full')
shape, then computes the convolution using the 'same' shape. Note that the
array returned using 'same' corresponds to the underlined elements of the
array returned using the default shape.
A = rand(3);
B = rand(4);
C = conv2(A,B)
% C is 6-by-6
C =
0.1838
0.6929
0.5627
0.9986
0.3089
0.3287
0.2374
1.2019
1.5150
2.3811
1.1419
0.9347
0.9727
1.5499
2.3576
3.4302
1.8229
1.6464
1.2644
2.1733
3.1553
3.5128
2.1561
1.7928
0.7890
1.3325
2.5373
2.4489
1.6364
1.2422
0.3750
0.3096
1.0602
0.8462
0.6841
0.5423
Cs = conv2(A,B,'same')
% Cs is the same size as A: 3-by-3
Cs =
2.3576 3.1553 2.5373
3.4302 3.5128 2.4489
1.8229 2.1561 1.6364
Example 2. In image processing, the Sobel edge finding operation is a
two-dimensional convolution of an input array with the special matrix
s = [1 2 1; 0 0 0; -1 -2 -1];
These commands extract the horizontal edges from a raised pedestal.
A = zeros(10);
A(3:7,3:7) = ones(5);
H = conv2(A,s);
mesh(H)
2-383
conv2
4
2
0
−2
−4
15
15
10
10
5
5
0
0
Transposing the filter s extracts the vertical edges of A.
V = conv2(A,s');
figure, mesh(V)
4
2
0
−2
−4
15
15
10
10
5
5
0
2-384
0
conv2
This figure combines both horizontal and vertical edges.
figure
mesh(sqrt(H.^2 + V.^2))
5
4
3
2
1
0
15
15
10
10
5
5
0
See Also
0
conv, convn, filter2
xcorr2 in the Signal Processing Toolbox
2-385
convhull
Purpose
Syntax
Description
2convhull
Convex hull
K = convhull(x,y)
[K,a] = convhull(x,y)
K = convhull(x,y) returns indices into the x and y vectors of the points on the
convex hull.
[K,a] = convhull(x,y) also returns the area of the convex hull.
Visualization
Examples
Use plot to plot the output of convhull.
xx = -1:.05:1; yy = abs(sqrt(xx));
[x,y] = pol2cart(xx,yy);
k = convhull(x,y);
plot(x(k),y(k),'r-',x,y,'b+')
1
0.8
0.6
0.4
0.2
0
−0.2
−0.4
−0.6
−0.8
−1
0
Algorithm
0.1
0.2
0.3
0.4
0.5
0.6
0.7
convhull is based on Qhull [2]. It uses the Qhull joggle option ('QJ'). For
information about qhull, see http://www.geom.umn.edu/software/qhull/.
For copyright information, see
http://www.geom.umn.edu/software/download/COPYING.html.
2-386
convhull
See Also
convhulln, delaunay, plot, polyarea, voronoi
Reference
[1] Barber, C. B., D.P. Dobkin, and H.T. Huhdanpaa, "The Quickhull Algorithm for
Convex Hulls," ACM Transactions on Mathematical Software, Vol. 22, No. 4,
Dec. 1996, p. 469-483. Available in HTML format at
http://www.acm.org/pubs/citations/journals/toms/1996-22-4/p469-bar
ber/ and in PostScript format at
ftp://geom.umn.edu/pub/software/qhull-96.ps.
[2] National Science and Technology Research Center for Computation and
Visualization of Geometric Structures (The Geometry Center), University of
Minnesota. 1993.
2-387
convhulln
Purpose
2convhulln
n-D convex hull
Syntax
K = convhulln(X)
[K,v] = convhulln(X)
Description
K = convhulln(X) returns the indices K of the points in X that comprise the
facets of the convex hull of X. X is an m-by-n array representing m points in n-D
space. If the convex hull has p facets then K is p-by-n.
[K,v] = convhulln(X) also returns the volume v of the convex hull.
Visualization
Plotting the output of convhulln depends on the value of n:
• For n = 2, use plot as you would for convhull.
• For n = 3, you can use trisurf to plot the output. The calling sequence is
K = convhulln(X);
trisurf(K,(X(:,1),X(:,2),X(:,3))
For more control over the color of the facets, use patch to plot the output. For
an example, see “Tessellation and Interpolation of Scattered Data in Higher
Dimensions” in the MATLAB documentation.
• You cannot plot convhulln output for n > 3.
Algorithm
convhulln is based on Qhull [2]. It uses the Qhull joggle option ('QJ'). For
information about qhull, see http://www.geom.umn.edu/software/qhull/.
For copyright information, see
http://www.geom.umn.edu/software/download/COPYING.html.
See Also
convhull, delaunayn, dsearchn, tsearchn, voronoin
Reference
[1] Barber, C. B., D.P. Dobkin, and H.T. Huhdanpaa, "The Quickhull Algorithm for
Convex Hulls," ACM Transactions on Mathematical Software, Vol. 22, No. 4,
Dec. 1996, p. 469-483. Available in HTML format at
http://www.acm.org/pubs/citations/journals/toms/1996-22-4/p469-bar
ber/ and in PostScript format at
ftp://geom.umn.edu/pub/software/qhull-96.ps.
2-388
convhulln
[2] National Science and Technology Research Center for Computation and
Visualization of Geometric Structures (The Geometry Center), University of
Minnesota. 1993.
2-389
convn
Purpose
2convn
N-dimensional convolution
Syntax
C = convn(A,B)
C = convn(A,B,'shape')
Description
C = convn(A,B) computes the N-dimensional convolution of the arrays A and
B. The size of the result is size(A)+size(B)-1.
C = convn(A,B,'shape') returns a subsection of the N-dimensional
convolution, as specified by the shape parameter:
'full'
Returns the full N-dimensional convolution (default).
'same'
Returns the central part of the result that is the same size as A.
'valid'
Returns only those parts of the convolution that can be computed
without assuming that the array A is zero-padded. The size of the
result is
max(size(A)-size(B) + 1, 0)
See Also
2-390
conv, conv2
copyfile
Purpose
2copyfile
Graphical
Interface
As an alternative to the copyfile function, use the Current Directory browser.
Select the files and then select copy and paste commands from the Edit menu.
Syntax
copyfile('source','destination')
copyfile('source','destination','f')
[status,message,messageid] = copyfile('source','destination','f')
Description
copyfile('source','destination') copies the file or directory, source (and
all its contents) to the file or directory, destination, where source and
destination are the absolute or relative pathnames for the directory or file. If
source is a directory, destination cannot be a file. If source is a directory,
copyfile copies the contents of source, not the directory itself. To rename a
file or directory when copying it, make destination a different name than
source. If destination already exists, copyfile replaces it without warning.
Use the wildcard * at the end of source to copy all matching files. Note that the
read-only and archive attributes of source are not preserved in destination.
Copy file or directory
copyfile('source','destination','f') copies source to destination,
regardless of the read-only attribute of destination.
[status,message,messageid] = copyfile('source','destination','f')
copies source to destination, returning the status, a message, and the
MATLAB error message ID (see error and lasterr). Here, status is 1 for
success and is 0 for no error. Only one output argument is required and the f
input argument is optional.
Examples
Copy File in Current Directory, Assigning a New Name to It
To make a copy of a file myfun.m in the current directory, assigning it the name
myfun2.m, type
copyfile('myfun.m','myfun2.m')
Copy File to Another Directory
To copy myfun.m to the directory d:/work/myfiles, keeping the same filename,
type
copyfile('myfun.m','d:/work/myfiles')
2-391
copyfile
Copy All Matching Files by Using a Wildcard
To copy all files in the directory myfiles whose names begin with my to the
directory newprojects, where newprojects is at the same level as the current
directory, type
copyfile('myfiles/my*','../newprojects')
Copy Directory and Return Status
In this example, all files and subdirectories in the current directory’s myfiles
directory are copied to the directory d:/work/myfiles. Note that before
running the copyfile function, d:/work does not contain the directory
myfiles. It is created because myfiles is appended to destination in the
copyfile function:
[s,mess,messid]=copyfile('myfiles','d:/work/myfiles')
s =
1
mess =
''
messid =
''
The message returned indicates that copyfile was successful.
Copy File to Read-Only Directory
Copy myfile.m from the current directory to d:/work/restricted, where
restricted is a read-only directory:
copyfile('myfile.m','d:/work/restricted','f')
After the copy, myfile.m exists in d:/work/restricted.
See Also
2-392
delete, dir, fileattrib, filebrowser, mkdir, movefile, rmdir
copyobj
Purpose
2copyobj
Copy graphics objects and their descendants
Syntax
new_handle = copyobj(h,p)
Description
copyobj creates copies of graphics objects. The copies are identical to the
original objects except the copies have different values for their Parent
property and a new handle. The new parent must be appropriate for the copied
object (e.g., you can copy a line object only to another axes object).
new_handle = copyobj(h,p) copies one or more graphics objects identified by
h and returns the handle of the new object or a vector of handles to new objects.
The new graphics objects are children of the graphics objects specified by p.
Remarks
h and p can be scalars or vectors. When both are vectors, they must be the same
length and the output argument, new_handle, is a vector of the same length.
In this case, new_handle(i) is a copy of h(i) with its Parent property set to
p(i).
When h is a scalar and p is a vector, h is copied once to each of the parents in p.
Each new_handle(i) is a copy of h with its Parent property set to p(i), and
length(new_handle) equals length(p).
When h is a vector and p is a scalar, each new_handle(i) is a copy of h(i) with
its Parent property set to p. The length of new_handle equals length(h).
Graphics objects are arranged as a hierarchy. Here, each graphics object is
shown connected below its appropriate parent object.
Root
Figure
Axes
Uicontrol
Uimenu
Image
Light
Line
Uicontextmenu
Patch
Rectangle
Surface
Text
2-393
copyobj
Examples
Copy a surface to a new axes within a different figure.
h = surf(peaks);
colormap hot
figure
% Create a new figure
axes
% Create an axes object in the figure
new_handle = copyobj(h,gca);
colormap hot
view(3)
grid on
Note that while the surface is copied, the colormap (figure property), view, and
grid (axes properties) are not copies.
See Also
findobj, gcf, gca, gco, get, set
Parent property for all graphics objects
“Finding and Identifying Graphics Objects” for related functions
2-394
corrcoef
Purpose
2corrcoef
Correlation coefficients
Syntax
R = corrcoef(X)
R = corrcoef(x,y)
[R,P]=corrcoef(...)
[R,P,RLO,RUP]=corrcoef(...)
[...]=corrcoef(...,'param1',val1,'param2',val2,...)
Description
R = corrcoef(X) returns a matrix R of correlation coefficients calculated from
an input matrix X whose rows are observations and whose columns are
variables. The matrix R = corrcoef(X) is related to the covariance
matrix C = cov(X) by
C ( i, j )
R ( i, j ) = --------------------------------------C ( i, i )C ( j, j )
corrcoef(X) is the zeroth lag of the covariance function, that is, the zeroth lag
of xcov(x,'coeff') packed into a square array.
R = corrcoef(x,y) where x and y are column vectors is the same as
corrcoef([x y]).
[R,P]=corrcoef(...) also returns P, a matrix of p-values for testing the
hypothesis of no correlation. Each p-value is the probability of getting a
correlation as large as the observed value by random chance, when the true
correlation is zero. If P(i,j) is small, say less than 0.05, then the correlation
R(i,j) is significant.
[R,P,RLO,RUP]=corrcoef(...) also returns matrices RLO and RUP, of the same
size as R, containing lower and upper bounds for a 95% confidence interval for
each coefficient.
[...]=corrcoef(...,'param1',val1,'param2',val2,...) specifies
additional parameters and their values. Valid parameters are the following.
2-395
corrcoef
'alpha'
A number between 0 and 1 to specify a confidence level of
100*(1 - alpha)%. Default is 0.05 for 95% confidence intervals.
'rows'
Either 'all' (default) to use all rows, 'complete' to use rows
with no NaN values, or 'pairwise' to compute R(i,j) using
rows with no NaN values in either column i or j.
The p-value is computed by transforming the correlation to create a t statistic
having n-2 degrees of freedom, where n is the number of rows of X. The
confidence bounds are based on an asymptotic normal distribution of
0.5*log((1+R)/(1-R)), with an approximate variance equal to 1/(n-3).
These bounds are accurate for large samples when X has a multivariate normal
distribution. The 'pairwise' option can produce an R matrix that is not
positive definite.
Examples
Generate random data having correlation between column 4 and the other
columns.
x = randn(30,4);
%
x(:,4) = sum(x,2);
%
[r,p] = corrcoef(x) %
[i,j] = find(p<0.05);
[i,j]
%
Uncorrelated data
Introduce correlation.
Compute sample correlation and p-values.
% Find significant correlations.
Display their (row,col) indices.
r =
1.0000
-0.3566
0.1929
0.3457
-0.3566
1.0000
-0.1429
0.4461
0.1929
-0.1429
1.0000
0.5183
0.3457
0.4461
0.5183
1.0000
0.0531
1.0000
0.4511
0.0135
0.3072
0.4511
1.0000
0.0033
0.0613
0.0135
0.0033
1.0000
p =
1.0000
0.0531
0.3072
0.0613
ans =
4
4
2
2-396
2
3
4
corrcoef
3
See Also
4
cov, mean, std
xcorr, xcov in the Signal Processing Toolbox
2-397
cos
Purpose
2cos
Cosine
Syntax
Y = cos(X)
Description
The cos function operates element-wise on arrays. The function’s domains and
ranges include complex values. All angles are in radians.
Y = cos(X) returns the circular cosine for each element of X.
Examples
Graph the cosine function over the domain – π ≤ x ≤ π .
x = -pi:0.01:pi;
plot(x,cos(x)), grid on
1
0.8
0.6
0.4
0.2
0
−0.2
−0.4
−0.6
−0.8
−1
−4
−3
−2
−1
0
1
2
3
4
The expression cos(pi/2) is not exactly zero but a value the size of the
floating-point accuracy, eps, because pi is only a floating-point approximation
to the exact value of π .
Definition
The cosine can be defined as
cos ( x + iy ) = cos ( x ) cosh ( y ) – i sin ( x )sinh ( y )
e iz + e – iz
cos ( z ) = ----------------------2
2-398
cos
Algorithm
cos uses FDLIBM, which was developed at SunSoft, a Sun Microsystems, Inc.
business, by Kwok C. Ng, and others. For information about FDLIBM, see
http://www.netlib.org.
See Also
acos, acosh, cosh
2-399
cosh
Purpose
2cosh
Hyperbolic cosine
Syntax
Y = cosh(X)
Description
The cosh function operates element-wise on arrays. The function’s domains
and ranges include complex values. All angles are in radians.
Y = cosh(X) returns the hyperbolic cosine for each element of X.
Examples
Graph the hyperbolic cosine function over the domain – 5 ≤ x ≤ 5 .
x = -5:0.01:5;
plot(x,cosh(x)), grid on
80
70
60
50
40
30
20
10
0
−5
Definition
0
5
The hyperbolic cosine can be defined as
z
–z
e +e
cosh( z) = ------------------2
Algorithm
cosh uses FDLIBM, which was developed at SunSoft, a Sun Microsystems, Inc.
business, by Kwok C. Ng, and others. For information about FDLIBM, see
http://www.netlib.org.
2-400
cosh
See Also
acos, acosh, cos
2-401
cot
Purpose
2cot
Cotangent
Syntax
Y = cot(X)
Description
The cot function operates element-wise on arrays. The function’s domains and
ranges include complex values. All angles are in radians.
Y = cot(X) returns the cotangent for each element of X.
Examples
Graph the cotangent the domains – π < x < 0 and 0 < x < π.
x1 = -pi+0.01:0.01:-0.01;
x2 = 0.01:0.01:pi-0.01;
plot(x1,cot(x1),x2,cot(x2)), grid on
100
80
60
40
20
0
−20
−40
−60
−80
−100
−4
Definition
−3
−2
−1
0
1
2
3
4
The cotangent can be defined as
1
cot ( z ) = -----------------tan ( z )
Algorithm
cot uses FDLIBM, which was developed at SunSoft, a Sun Microsystems, Inc.
business, by Kwok C. Ng, and others. For information about FDLIBM, see
http://www.netlib.org.
2-402
cot
See Also
acot, acoth, coth
2-403
coth
Purpose
2 coth
Hyperbolic cotangent
Syntax
Y = coth(X)
Description
The coth function operates element-wise on arrays. The function’s domains
and ranges include complex values. All angles are in radians.
Y = coth(X) returns the hyperbolic cotangent for each element of X.
Examples
Graph the hyperbolic cotangent over the domains – π < x < 0 and 0 < x < π.
x1 = -pi+0.01:0.01:-0.01;
x2 = 0.01:0.01:pi-0.01;
plot(x1,coth(x1),x2,coth(x2)), grid on
150
100
50
0
−50
−100
−4
Definition
−3
−2
−1
0
1
2
3
4
The hyperbolic cotangent can be defined as
1
coth ( z ) = --------------------tanh ( z )
Algorithm
coth uses FDLIBM, which was developed at SunSoft, a Sun Microsystems, Inc.
business, by Kwok C. Ng, and others. For information about FDLIBM, see
http://www.netlib.org.
2-404
coth
See Also
acot, acoth, cot
2-405
cov
Purpose
2cov
Covariance matrix
Syntax
C = cov(X)
C = cov(x,y)
Description
C = cov(x) where x is a vector returns the variance of the vector elements. For
matrices where each row is an observation and each column a variable, cov(x)
is the covariance matrix. diag(cov(x)) is a vector of variances for each
column, and sqrt(diag(cov(x))) is a vector of standard deviations.
C = cov(x,y), where x and y are column vectors of equal length, is equivalent
to cov([x y]).
Remarks
cov removes the mean from each column before calculating the result.
The covariance function is defined as
cov ( x 1 ,x 2 ) = E [ ( x 1 – µ 1 ) ( x 2 – µ 2 ) ]
where E is the mathematical expectation and µ i = Ex i .
Examples
Consider A = [-1 1 2 ; -2 3 1 ; 4 0 3]. To obtain a vector of variances for
each column of A:
v = diag(cov(A))'
v =
10.3333
2.3333
1.0000
Compare vector v with covariance matrix C:
C =
10.3333
-4.1667
3.0000
-4.1667
2.3333
-1.5000
3.0000
-1.5000
1.0000
The diagonal elements C(i,i) represent the variances for the columns of A.
The off-diagonal elements C(i,j) represent the covariances of columns i and
j.
See Also
corrcoef, mean, std
xcorr, xcov in the Signal Processing Toolbox
2-406
cplxpair
Purpose
2cplxpair
Sort complex numbers into complex conjugate pairs
Syntax
B
B
B
B
Description
B = cplxpair(A) sorts the elements along different dimensions of a complex
=
=
=
=
cplxpair(A)
cplxpair(A,tol)
cplxpair(A,[],dim)
cplxpair(A,tol,dim)
array, grouping together complex conjugate pairs.
The conjugate pairs are ordered by increasing real part. Within a pair, the
element with negative imaginary part comes first. The purely real values are
returned following all the complex pairs. The complex conjugate pairs are
forced to be exact complex conjugates. A default tolerance of 100*eps relative
to abs(A(i)) determines which numbers are real and which elements are
paired complex conjugates.
If A is a vector, cplxpair(A) returns A with complex conjugate pairs grouped
together.
If A is a matrix, cplxpair(A) returns A with its columns sorted and complex
conjugates paired.
If A is a multidimensional array, cplxpair(A) treats the values along the first
non-singleton dimension as vectors, returning an array of sorted elements.
B = cplxpair(A,tol) overrides the default tolerance.
B = cplxpair(A,[],dim) sorts A along the dimension specified by scalar dim.
B = cplxpair(A,tol,dim) sorts A along the specified dimension and overrides
the default tolerance.
Diagnostics
If there are an odd number of complex numbers, or if the complex numbers
cannot be grouped into complex conjugate pairs within the tolerance, cplxpair
generates the error message
Complex numbers can't be paired.
2-407
cputime
Purpose
2cputime
Elapsed CPU time
Syntax
cputime
Description
cputime returns the total CPU time (in seconds) used by MATLAB from the
time it was started. This number can overflow the internal representation and
wrap around.
Examples
The following code returns the CPU time used to run surf(peaks(40)).
t = cputime; surf(peaks(40)); e = cputime-t
e =
0.4667
See Also
2-408
clock, etime, tic, toc
cross
Purpose
2cross
Vector cross product
Syntax
C = cross(A,B)
C = cross(A,B,dim)
Description
C = cross(A,B) returns the cross product of the vectors A and B. That is,
C = A x B. A and B must be 3-element vectors. If A and B are multidimensional
arrays, cross returns the cross product of A and B along the first dimension of
length 3.
C = cross(A,B,dim) where A and B are multidimensional arrays, returns the
cross product of A and B in dimension dim . A and B must have the same size,
and both size(A,dim) and size(B,dim) must be 3.
Remarks
To perform a dot (scalar) product of two vectors of the same size, use
c = dot(a,b).
Examples
The cross and dot products of two vectors are calculated as shown:
a = [1 2 3];
b = [4 5 6];
c = cross(a,b)
c =
-3
6
-3
d = dot(a,b)
d =
32
See Also
dot
2-409
csc
Purpose
2csc
Cosecant
Syntax
Y = csc(x)
Description
The csc function operates element-wise on arrays. The function’s domains and
ranges include complex values. All angles are in radians.
Y = csc(x) returns the cosecant for each element of x.
Examples
Graph the cosecant over the domains – π < x < 0 and 0 < x < π .
x1 = -pi+0.01:0.01:-0.01;
x2 = 0.01:0.01:pi-0.01;
plot(x1,csc(x1),x2,csc(x2)), grid on
150
100
50
0
−50
−100
−150
−4
Definition
−3
−2
−1
0
1
2
3
4
The cosecant can be defined as
1
csc ( z ) = ----------------sin ( z )
Algorithm
csc uses FDLIBM, which was developed at SunSoft, a Sun Microsystems, Inc.
business, by Kwok C. Ng, and others. For information about FDLIBM, see
http://www.netlib.org.
2-410
csc
See Also
acsc, acsch, csch
2-411
csch
Purpose
2 csch
Hyperbolic cosecant
Syntax
Y = csch(x)
Description
The csch function operates element-wise on arrays. The function’s domains
and ranges include complex values. All angles are in radians.
Y = csch(x) returns the hyperbolic cosecant for each element of x.
Examples
Graph the hyperbolic cosecant over the domains – π < x < 0 and 0 < x < π .
x1 = -pi+0.01:0.01:-0.01;
x2 = 0.01:0.01:pi-0.01;
plot(x1,csch(x1),x2,csch(x2)), grid on
100
80
60
40
20
0
−20
−40
−60
−80
−100
−4
Definition
−3
−2
−1
0
1
2
3
4
The hyperbolic cosecant can be defined as
1
csch ( z ) = -------------------sinh ( z )
Algorithm
csch uses FDLIBM, which was developed at SunSoft, a Sun Microsystems, Inc.
business, by Kwok C. Ng, and others. For information about FDLIBM, see
http://www.netlib.org.
2-412
csch
See Also
acsc, acsch, csc
2-413
csvread
Purpose
2csvread
Read a comma-separated value file
Syntax
M = csvread('filename')
M = csvread('filename',row,col)
M = csvread('filename',row,col,range)
Description
M = csvread('filename') reads a comma-separated value formatted file,
filename. The result is returned in M. The file can only contain numeric values.
M = csvread('filename',row,col) reads data from the comma-separated
value formatted file starting at the specified row and column. The row and
column arguments are zero-based, so that row=0 and col=0 specifies the first
value in the file.
M = csvread('filename',row,col,range) reads only the range specified.
Specify the range using the notation, [R1 C1 R2 C2] where (R1,C1) is the
upper-left corner of the data to be read and (R2,C2) is the lower-right corner.
The range can also be specified using spreadsheet notation as in range =
'A1..B7'.
Remarks
csvread fills empty delimited fields with zero. Data files having lines that end
with a nonspace delimiter, such as a semicolon, produce a result that has an
additional last column of zeros.
Examples
Given the file, csvlist.dat that contains the comma-separated values
02,
03,
05,
07,
11,
04,
06,
10,
14,
22,
06,
09,
15,
21,
33,
08,
12,
20,
28,
44,
10,
15,
25,
35,
55,
12
18
30
42
66
To read the entire file, use
csvread('csvlist.dat')
ans =
2
3
2-414
4
6
6
9
8
12
10
15
12
18
csvread
5
7
11
10
14
22
15
21
33
20
28
44
25
35
55
30
42
66
To read the matrix starting with zero-based row 2, column 0 and assign it to
the variable, m,
m = csvread('csvlist.dat', 2, 0)
m =
5
7
11
10
14
22
15
21
33
20
28
44
25
35
55
30
42
66
To read the matrix bounded by zero-based (2,0) and (3,3) and assign it to m,
m = csvread('csvlist.dat', 2, 0, [2,0,3,3])
m =
5
7
See Also
10
14
15
21
20
28
csvwrite, dlmread, textread, wk1read, file formats, importdata, uiimport
2-415
csvwrite
Purpose
2csvwrite
Write a comma-separated value file
Syntax
csvwrite('filename',M)
csvwrite('filename',M,row,col)
Description
csvwrite('filename',M) writes matrix M into filename as comma-separated
values.
csvwrite('filename',M,row,col) writes matrix M into filename starting at
the specified row and column offset. The row and column arguments are
zero-based, so that row=0 and C=0 specifies the first value in the file.
Examples
The following example creates a comma-separated value file from the matrix,
m.
m = [3 6 9 12 15; 5 10 15 20 25; 7 14 21 28 35; 11 22 33 44 55];
csvwrite('csvlist.dat',m)
type csvlist.dat
3,6,9,12,15
5,10,15,20,25
7,14,21,28,35
11,22,33,44,55
The next example writes the matrix to the file, starting at a column offset of 2.
csvwrite('csvlist.dat',m,0,2)
type csvlist.dat
,,3,6,9,12,15
,,5,10,15,20,25
,,7,14,21,28,35
,,11,22,33,44,55
See Also
2-416
csvread, dlmwrite, textread, wk1write, file formats, importdata, uiimport
cumprod
Purpose
2cumprod
Cumulative product
Syntax
B = cumprod(A)
B = cumprod(A,dim)
Description
B = cumprod(A) returns the cumulative product along different dimensions of
an array.
If A is a vector, cumprod(A) returns a vector containing the cumulative product
of the elements of A.
If A is a matrix, cumprod(A) returns a matrix the same size as A containing the
cumulative products for each column of A.
If A is a multidimensional array, cumprod(A) works on the first nonsingleton
dimension.
B = cumprod(A,dim) returns the cumulative product of the elements along the
dimension of A specified by scalar dim. For example, cumprod(A,1) increments
the first (row) index, thus working along the rows of A.
Examples
cumprod(1:5)
ans =
1 2 6
24
120
A = [1 2 3; 4 5 6];
See Also
cumprod(A)
ans =
1
2
4
10
3
18
cumprod(A,2)
ans =
1
2
4
20
6
120
cumsum, prod, sum
2-417
cumsum
Purpose
2cumsum
Cumulative sum
Syntax
B = cumsum(A)
B = cumsum(A,dim)
Description
B = cumsum(A) returns the cumulative sum along different dimensions of an
array.
If A is a vector, cumsum(A) returns a vector containing the cumulative sum of
the elements of A.
If A is a matrix, cumsum(A) returns a matrix the same size as A containing the
cumulative sums for each column of A.
If A is a multidimensional array, cumsum(A) works on the first nonsingleton
dimension.
B = cumsum(A,dim) returns the cumulative sum of the elements along the
dimension of A specified by scalar dim. For example, cumsum(A,1) works across
the first dimension (the rows).
Examples
cumsum(1:5)
ans =
[1 3
6
10
A = [1 2 3; 4 5 6];
See Also
2-418
cumsum(A)
ans =
1
5
2
7
3
9
cumsum(A,2)
ans =
1
4
3
9
6
15
cumprod, prod, sum
15]
cumtrapz
Purpose
2cumtrapz
Cumulative trapezoidal numerical integration
Syntax
Z = cumtrapz(Y)
Z = cumtrapz(X,Y)
Z = cumtrapz(... dim)
Description
Z = cumtrapz(Y) computes an approximation of the cumulative integral of Y
via the trapezoidal method with unit spacing. To compute the integral with
other than unit spacing, multiply Z by the spacing increment.
For vectors, cumtrapz(Y) is a vector containing the cumulative integral of Y.
For matrices, cumtrapz(Y) is a matrix the same size as Y with the cumulative
integral over each column.
For multidimensional arrays, cumtrapz(Y) works across the first nonsingleton
dimension.
Z = cumtrapz(X,Y) computes the cumulative integral of Y with respect to X
using trapezoidal integration. X and Y must be vectors of the same length, or X
must be a column vector and Y an array whose first nonsingleton dimension is
length(X). cumtrapz operates across this dimension.
If X is a column vector and Y an array whose first nonsingleton dimension is
length(X), cumtrapz(X,Y) operates across this dimension.
Z = cumtrapz(X,Y,dim) or cumtrapz(Y,DIM) integrates across the
dimension of Y specified by scalar dim. The length of X must be the same as
size(Y,dim).
Example
Y = [0 1 2; 3 4 5];
cumtrapz(Y,1)
ans =
0
0
1.5000
2.5000
0
3.5000
cumtrapz(Y,2)
ans =
0
0.5000
0
3.5000
2.0000
8.0000
2-419
cumtrapz
See Also
2-420
cumsum, trapz
curl
Purpose
2curl
Computes the curl and angular velocity of a vector field
Syntax
[curlx,curly,curlz,cav] = curl(X,Y,Z,U,V,W)
[curlx,curly,curlz,cav] = curl(U,V,W)
[curlz,cav]= curl(X,Y,U,V)
[curlz,cav]= curl(U,V)
[curlx,curly,curlz] = curl(...), [curlx,curly] = curl(...)
cav = curl(...)
Description
[curlx,curly,curlz,cav] = curl(X,Y,Z,U,V,W) computes the curl and
angular velocity perpendicular to the flow (in radians per time unit) of a 3-D
vector field U, V, W. The arrays X, Y, Z define the coordinates for U, V, W and must
be monotonic and 3-D plaid (as if produced by meshgrid).
[curlx,curly,curlz,cav] = curl(U,V,W) assumes X, Y, and Z are
determined by the expression:
[X Y Z] = meshgrid(1:n,1:m,1:p)
where [m,n,p] = size(U).
[curlz,cav]= curl(X,Y,U,V) computes the curl z-component and the
angular velocity perpendicular to z (in radians per time unit) of a 2-D vector
field U, V. The arrays X, Y define the coordinates for U, V and must be monotonic
and 2-D plaid (as if produced by meshgrid).
[curlz,cav]= curl(U,V) assumes X and Y are determined by the expression:
[X Y] = meshgrid(1:n,1:m)
where [m,n] = size(U).
[curlx,curly,curlz] = curl(...), curlx,curly] = curl(...) returns
only the curl.
cav = curl(...) returns only the curl angular velocity.
Examples
This example uses colored slice planes to display the curl angular velocity at
specified locations in the vector field.
2-421
curl
load wind
cav = curl(x,y,z,u,v,w);
slice(x,y,z,cav,[90 134],[59],[0]);
shading interp
daspect([1 1 1]); axis tight
colormap hot(16)
camlight
This example views the curl angular velocity in one plane of the volume and
plots the velocity vectors (quiver) in the same plane.
load wind
k = 4;
x = x(:,:,k); y = y(:,:,k); u = u(:,:,k); v = v(:,:,k);
cav = curl(x,y,u,v);
pcolor(x,y,cav); shading interp
hold on;
quiver(x,y,u,v,'y')
hold off
colormap copper
2-422
curl
See Also
streamribbon, divergence
“Volume Visualization” for related functions
Displaying Curl with Stream Ribbons for another example
2-423
customverctrl
Purpose
2customverctrl
Allow custom source control system
Syntax
customverctrl(filename, arguments)
Description
This function is supplied for customers who want to integrate a version control
system that is not supported with MATLAB. This function must conform to the
structure of one of the supported version control systems, for example RCS. See
the files clearcase.m, pvcs.m, rcs.m, and sourcesafe.m in
$matlabroot\toolbox\matlab\verctrl as examples.
See Also
checkin, checkout, cmopts, undocheckout
2-424
cylinder
Purpose
2cylinder
Generate cylinder
Syntax
[X,Y,Z] = cylinder
[X,Y,Z] = cylinder(r)
[X,Y,Z] = cylinder(r,n)
cylinder(...)
Description
cylinder generates x, y, and z coordinates of a unit cylinder. You can draw the
cylindrical object using surf or mesh, or draw it immediately by not providing
output arguments.
[X,Y,Z] = cylinder returns the x, y, and z coordinates of a cylinder with a
radius equal to 1. The cylinder has 20 equally spaced points around its
circumference.
[X,Y,Z] = cylinder(r) returns the x, y, and z coordinates of a cylinder using
r to define a profile curve. cylinder treats each element in r as a radius at
equally spaced heights along the unit height of the cylinder. The cylinder has
20 equally spaced points around its circumference.
[X,Y,Z] = cylinder(r,n) returns the x, y, and z coordinates of a cylinder
based on the profile curve defined by vector r. The cylinder has n equally
spaced points around its circumference.
cylinder(...), with no output arguments, plots the cylinder using surf.
Remarks
cylinder treats its first argument as a profile curve. The resulting surface
graphics object is generated by rotating the curve about the x-axis, and then
aligning it with the z-axis.
Examples
Create a cylinder with randomly colored faces.
cylinder
axis square
h = findobj('Type','surface');
2-425
cylinder
set(h,'CData',rand(size(get(h,'CData'))))
1
0.8
0.6
0.4
0.2
0
1
1
0.5
0.5
0
0
−0.5
−0.5
−1
−1
Generate a cylinder defined by the profile function 2+sin(t).
t = 0:pi/10:2*pi;
[X,Y,Z] = cylinder(2+cos(t));
surf(X,Y,Z)
axis square
2-426
cylinder
1
0.8
0.6
0.4
0.2
0
4
4
2
2
0
0
−2
−2
−4
See Also
−4
sphere, surf
“Polygons and Surfaces” for related functions
2-427
daspect
Purpose
2daspect
Set or query the axes data aspect ratio
Syntax
daspect
daspect([aspect_ratio])
daspect('mode')
daspect('auto')
daspect('manual')
daspect(axes_handle,...)
Description
The data aspect ratio determines the relative scaling of the data units along the
x-, y-, and z-axes.
daspect with no arguments returns the data aspect ratio of the current axes.
daspect([aspect_ratio]) sets the data aspect ratio in the current axes to the
specified value. Specify the aspect ratio as three relative values representing
the ratio of the x-, y-, and z-axis scaling (e.g., [1 1 3] means one unit in x is
equal in length to one unit in y and three unit in z).
daspect('mode') returns the current value of the data aspect ratio mode,
which can be either auto (the default) or manual. See Remarks.
daspect('auto') sets the data aspect ratio mode to auto.
daspect('manual') sets the data aspect ratio mode to manual.
daspect(axes_handle,...) performs the set or query on the axes identified by
the first argument, axes_handle. When you do not specify an axes handle,
daspect operates on the current axes.
Remarks
daspect sets or queries values of the axes object DataAspectRatio and
DataAspectRatioMode properties.
When the data aspect ratio mode is auto, MATLAB adjusts the data aspect
ratio so that each axis spans the space available in the figure window. If you
are displaying a representation of a real-life object, you should set the data
aspect ratio to [1 1 1] to produce the correct proportions.
Setting a value for data aspect ratio or setting the data aspect ratio mode to
manual disables the MATLAB stretch-to-fill feature (stretching of the axes to
2-428
daspect
fit the window). This means setting the data aspect ratio to a value, including
its current value,
daspect(daspect)
can cause a change in the way the graphs look. See the Remarks section of the
axes description for more information.
Examples
The following surface plot of the function z = xe ( – x – y ) is useful to illustrate
the data aspect ratio. First plot the function over the range –2 ≤ x ≤ 2, –2 ≤ y ≤ 2,
2
2
[x,y] = meshgrid([-2:.2:2]);
z = x.*exp(-x.^2 - y.^2);
surf(x,y,z)
0.5
0
−0.5
2
1
2
1
0
0
−1
−1
−2
−2
Querying the data aspect ratio shows how MATLAB has drawn the surface.
daspect
ans =
4 4
1
Setting the data aspect ratio to [1 1 1] produces a surface plot with equal
scaling along each axis.
2-429
daspect
daspect([1 1 1])
0.5
0
−0.5
2
1.5
2
1
0.5
1
0
−0.5
0
−1
−1
−1.5
−2
See Also
−2
axis, pbaspect, xlim, ylim, zlim
The axes properties DataAspectRatio, PlotBoxAspectRatio, XLim, YLim, ZLim
“Setting the Aspect Ratio and Axis Limits” for related functions
Axes Aspect Ratio for more information.
2-430
date
Purpose
2date
Current date string
Syntax
str = date
Description
str = date returns a string containing the date in dd-mmm-yyyy format.
See Also
clock, datenum, now
2-431
datenum
Examples
Convert a date string to a serial date number.
n = datenum('19-May-2001')
n =
730990
Specifying year, month, and day, convert a date to a serial date number.
n = datenum(2001,12,19)
n =
731204
Convert a date vector to a serial date number.
format bank
n = datenum([2001 5 19 18 0 0])
n =
730990.75
Convert a date string to a serial date number using the default pivot year
n = datenum('12-june-12')
n =
735032
Convert the same date string to a serial date number using 1900 as the pivot
year.
n = datenum('12-june-12', 1900)
n =
698507
See Also
datestr, datevec, now
2-433
datestr
Purpose
2datestr
Date string format
Syntax
str = datestr(DT,dateform)
str = datestr(DT,dateform,P)
Description
The datestr function converts serial date numbers (defined by datenum) and
date vectors (defined by datevec) into date strings.
str = datestr(DT,dateform) converts a single date vector, or each element of
an array of serial date numbers to a date string. Date strings with
two-character years, e.g., 12-june-12, are assumed to lie within the 100-year
period centered about the current year.
str = datestr(DT,dateform,P) uses the specified pivot year as the starting
year of the 100-year range in which a two-character year resides. The default
pivot year is the current year minus 50 years.
The optional argument dateform specifies the date format of the result.
dateform can be either a number or a string:
2-434
dateform
(number)
dateform (string)
Example
0
'dd-mmm-yyyy HH:MM:SS'
01-Mar-2000 15:45:17
1
'dd-mmm-yyyy'
01-Mar-2000
2
'mm/dd/yy'
03/01/00
3
'mmm'
Mar
4
'm'
M
5
'mm'
03
6
'mm/dd'
03/01
7
'dd'
01
8
'ddd'
Wed
9
'd'
W
datestr
dateform
(number)
dateform (string)
Example
10
'yyyy'
2000
11
'yy'
00
12
'mmmyy'
Mar00
13
'HH:MM:SS'
15:45:17
14
'HH:MM:SS PM'
3:45:17 PM
15
'HH:MM'
15:45
16
'HH:MM PM'
3:45 PM
17
'QQ-YY'
Q1-01
18
'QQ'
Q1
19
'dd/mm'
01/03
20
'dd/mm/yy'
01/03/00
21
'mmm.dd.yyyy HH:MM:SS'
Mar.01,2000 15:45:17
22
'mmm.dd.yyyy'
Mar.01.2000
23
'mm/dd/yyyy'
03/01/2000
24
'dd/mm/yyyy'
01/03/2000
25
'yy/mm/dd'
00/03/01
26
'yyyy/mm/dd'
2000/03/01
27
'QQ-YYYY’
Q1-2001
28
'mmmyyyy'
Mar2000
29 (ISO
8601)
'yyyy-mm-dd'
2000-03-01
30 (ISO
8601)
'yyyymmddTHHMMSS'
20000301T154517
31
'yyyy-mm-dd HH:MM:SS'
2000-03-01 15:45:17
2-435
datestr
NOTE dateform numbers 0, 1, 2, 6, 13, 14, 15, 16, and 23 produce a string
suitable for input to datenum or datevec. Other date string formats will not
work with these functions.
Time formats like 'h:m:s', 'h:m:s.s', 'h:m pm', ... can also be part of the
input array DT. If you do not specify dateform, or if you specify dateform as -1,
the date string format defaults to
See Also
2-436
1
if DT contains date information only, e.g., 01-Mar-1995
16
if DT contains time information only e.g., 03:45 PM
0
if DT is a date vector, or a string that contains both date and time
information e.g., 01-Mar-1995 03:45
date, datetick, datenum, datevec
datetick
Purpose
2datetick
Label tick lines using dates
Syntax
datetick(tickaxis)
datetick(tickaxis,dateform)
Description
datetick(tickaxis) labels the tick lines of an axis using dates, replacing the
default numeric labels. tickaxis is the string 'x', 'y', or 'z'. The default is
'x'. datetick selects a label format based on the minimum and maximum
limits of the specified axis.
datetick(tickaxis,dateform) formats the labels according to the integer
dateform (see table). To produce correct results, the data for the specified axis
must be serial date numbers (as produced by datenum).
dateform (number)
dateform (string)
Example
0
'dd-mmm-yyyy HH:MM:SS'
01-Mar-2000
15:45:17
1
'dd-mmm-yyyy'
01-Mar-2000
2
'mm/dd/yy'
03/01/00
3
'mmm'
Mar
4
'm'
M
5
'mm'
03
6
'mm/dd'
03/01
7
'dd'
01
8
'ddd'
Wed
9
'd'
W
10
'yyyy'
2000
11
'yy'
00
12
'mmmyy'
Mar00
13
'HH:MM:SS'
15:45:17
2-437
datetick
Remarks
dateform (number)
dateform (string)
Example
14
'HH:MM:SS PM'
3:45:17 PM
15
'HH:MM'
15:45
16
'HH:MM PM'
3:45 PM
17
'QQ-YY'
Q1–01
18
'QQ'
Q1
19
'dd/mm'
01/03
20
'dd/mm/yy'
01/03/00
21
'mmm.dd.yyyy HH:MM:SS'
Mar.01,2000
15:45:17
22
'mmm.dd.yyyy'
Mar.01.2000
23
'mm/dd/yyyy'
03/01/2000
24
'dd/mm/yyyy'
01/03/2000
25
'yy/mm/dd'
00/03/01
26
'yyyy/mm/dd'
2000/03/01
27
'QQ-YYYY’
Q1-2001
28
'mmmyyyy'
Mar2000
datetick calls datestr to convert date numbers to date strings.
To change the tick spacing and locations, set the appropriate axes property
(i.e., XTick, YTick, or ZTick) before calling datetick.
Example
Consider graphing population data based on the 1990 U.S. census:
t = (1900:10:1990)';
% Time interval
p = [75.995 91.972 105.711 123.203 131.669 ...
150.697 179.323 203.212 226.505 249.633]'; % Population
plot(datenum(t,1,1),p) % Convert years to date numbers and plot
grid on
2-438
datetick
datetick('x',11)
% Replace x-axis ticks with 2-digit year labels
260
240
220
200
180
160
140
120
100
80
60
00
See Also
20
40
60
80
00
The axes properties XTick, YTick, and ZTick.
datenum, datestr
“Annotating Plots” for related functions
2-439
datevec
Purpose
2datevec
Date components
C = datevec(A)
C = datevec(A,P)
[Y,M,D,H,MI,S] = datevec(A)
Description
C = datevec(A) splits its input into an n-by-6 array with each row containing
the vector [Y,M,D,H,MI,S]. The first five date vector elements are integers.
Input A can either consist of strings of the sort produced by the datestr
function, or scalars of the sort produced by the datenum and now functions. Date
strings with two-character years, e.g., 12-june-12, are assumed to lie within
the 100-year period centered about the current year.
C = datevec(A,P) uses the specified pivot year as the starting year of the
100-year range in which a two-character year resides. The default pivot year is
the current year minus 50 years.
[Y,M,D,H,MI,S] = datevec(A) returns the components of the date vector as
individual variables.
When creating your own date vector, you need not make the components
integers. Any components that lie outside their conventional ranges affect the
next higher component (so that, for instance, the anomalous June 31 becomes
July 1). A zeroth month, with zero days, is allowed.
Examples
An example of using a string as input:
datevec('12/24/1984')
ans =
1984
12
24
An example of using a serial date number as input:
t = datenum('12/24/1984')
t =
725000
datevec(t)
2-440
0
0
0
datevec
ans =
1984
See Also
12
24
0
0
0
clock, datenum, datestr, now
2-441
dbclear
Purpose
2dbclear
Graphical
Interface
As an alternative to the dbclear function, there are various ways to clear
breakpoints using the Editor/Debugger.
Syntax
dbclear
dbclear
dbclear
dbclear
dbclear
dbclear
dbclear
dbclear
dbclear
Description
dbclear all removes all breakpoints in all M-files, as well as pauses set for
error, warning, and naninf/infnan using dbstop.
Clear breakpoints
all
all in mfile
in mfile
in mfile at lineno
in mfile at subfun
if error
if warning
if naninf
if infnan
dbclear all in mfile removes breakpoints in mfile.
dbclear in mfile removes the breakpoint set at the first executable line in
mfile.
dbclear in mfile at lineno removes the breakpoint set at the line number
lineno in mfile.
dbclear in mfile at subfun removes the breakpoint set at the subfunction
subfun in mfile.
dbclear if error removes the pause set using dbstop if error.
dbclear if warning removes the pause set using dbstop if warning.
dbclear if naninf removes the pause set using dbstop if naninf.
dbclear if infnan removes the pause set using dbstop if infnan.
Remarks
2-442
The at, in, and if keywords, familiar to users of the UNIX debugger dbx, are
optional.
dbclear
See Also
dbcont, dbdown, dbquit, dbstack, dbstatus, dbstep, dbstop, dbtype, dbup,
partialpath
2-443
dbcont
Purpose
2dbcont
Graphical
Interface
As an alternative to the dbcont function, you can select Continue from the
Debug menu in the Editor/Debugger.
Syntax
dbcont
Description
dbcont resumes execution of an M-file from a breakpoint. Execution continues
Resume execution
until another breakpoint is encountered, an error occurs, or MATLAB returns
to the base workspace prompt.
See Also
2-444
dbclear, dbdown, dbquit, dbstack, dbstatus, dbstep, dbstop, dbtype, dbup
dbdown
Purpose
2dbdown
Graphical
Interface
As an alternative to the dbdown function, you can select a different workspace
from the Stack field in the Editor/Debugger toolbar.
Syntax
dbdown
Description
dbdown changes the current workspace context to the workspace of the called
M-file when a breakpoint is encountered. You must have issued the dbup
function at least once before you issue this function. dbdown is the opposite of
dbup.
Change local workspace context
Multiple dbdown functions change the workspace context to each successively
executed M-file on the stack until the current workspace context is the current
breakpoint. It is not necessary, however, to move back to the current
breakpoint to continue execution or to step to the next line.
See Also
dbclear, dbcont, dbquit, dbstack, dbstatus, dbstep, dbstop, dbtype, dbup
2-445
dblquad
Purpose
2dblquad
Numerically evaluate double integral
Syntax
q
q
q
q
Description
q = dblquad(fun,xmin,xmax,ymin,ymax) calls the quad function to evaluate
the double integral fun(x,y) over the rectangle xmin <= x <= xmax,
ymin <= y <= ymax. fun(x,y) must accept a vector x and a scalar y and return
a vector of values of the integrand.
=
=
=
=
dblquad(fun,xmin,xmax,ymin,ymax)
dblquad(fun,xmin,xmax,ymin,ymax,tol)
dblquad(fun,xmin,xmax,ymin,ymax,tol,method)
dblquad(fun,xmin,xmax,ymin,ymax,tol,method,p1,p2,...)
q = dblquad(fun,xmin,xmax,ymin,ymax,tol) uses a tolerance tol instead of
the default, which is 1.0e-6.
q = dblquad(fun,xmin,xmax,ymin,ymax,tol,method) uses the quadrature
function specified as method, instead of the default quad. Valid values for
method are @quadl or the function handle of a user-defined quadrature method
that has the same calling sequence as quad and quadl.
dblquad(fun,xmin,xmax,ymin,ymax,tol,method,p1,p2,...) passes the
additional parameters p1,p2,... to fun(x,y,p1,p2,...). Use [] as a
placeholder if you do not specify tol or method.
dblquad(fun,xmin,xmax,ymin,ymax,[],[],p1,p2,...) is the same as
dblquad(fun,xmin,xmax,ymin,ymax,1.e-6,@quad,p1,p2,...)
Example
fun can be an inline object
Q = dblquad(inline('y*sin(x)+x*cos(y)'), pi, 2*pi, 0, pi)
or a function handle
Q = dblquad(@integrnd, pi, 2*pi, 0, pi)
where integrnd.m is an M-file.
function z = integrnd(x, y)
z = y*sin(x)+x*cos(y);
2-446
dblquad
The integrnd function integrates y*sin(x)+x*cos(y) over the square
pi <= x <= 2*pi, 0 <= y <= pi. Note that the integrand can be evaluated
with a vector x and a scalar y .
Nonsquare regions can be handled by setting the integrand to zero outside of
the region. For example, the volume of a hemisphere is
dblquad(inline('sqrt(max(1-(x.^2+y.^2),0))'),-1,1,-1,1)
or
dblquad(inline('sqrt(1-(x.^2+y.^2)).*(x.^2+y.^2<=1)'),-1,1,-1,1
)
See Also
inline, quad, quadl, triplequad, @ (function handle)
2-447
dbmex
Purpose
2dbmex
Enable MEX-file debugging
Syntax
dbmex
dbmex
dbmex
dbmex
Description
dbmex on enables MEX-file debugging for UNIX platforms. It is not supported
on
off
stop
print
on the Sun Solaris platform. To use this option, first start MATLAB from
within a debugger by typing: matlab -Ddebugger, where debugger is the name
of the debugger.
dbmex off disables MEX-file debugging.
dbmex stop returns to the debugger prompt.
dbmex print displays MEX-file debugging information.
Remarks
On Sun Solaris platforms, dbmex is not supported. See the Technical Support
solution 23388 at
http://www.mathworks.com/support/solutions/data/23388.shtml for an
alternative method of debugging.
See Also
dbclear, dbcont, dbdown, dbquit, dbstack, dbstatus, dbstep, dbstop, dbtype,
dbup
2-448
dbquit
Purpose
2dbquit
Graphical
Interface
As an alternative to the dbquit function, you can select Exit Debug Mode from
the Debug menu in the Editor/Debugger.
Syntax
dbquit
Description
dbquit immediately terminates the debugger and returns control to the base
Quit debug mode
workspace prompt. The M-file being processed is not completed and no results
are returned.
All breakpoints remain in effect.
See Also
dbclear, dbcont, dbdown, dbstack, dbstatus, dbstep, dbstop, dbtype, dbup
2-449
dbstack
Purpose
2dbstack
Graphical
Interface
As an alternative to the dbstack function, you can view the Stack field in the
Editor/Debugger toolbar.
Syntax
dbstack
[ST,I] = dbstack
Description
dbstack displays the line numbers and M-file names of the function calls that
Display function call stack
led to the current breakpoint, listed in the order in which they were executed.
The line number of the most recently executed function call (at which the
current breakpoint occurred) is listed first, followed by its calling function,
which is followed by its calling function, and so on, until the topmost M-file
function is reached.
[ST,I] = dbstack returns the stack trace information in an m-by-1 structure
ST with the fields
name
Function name
line
Function line number
The current workspace index is returned in I.
Examples
dbstack
In /usr/local/matlab/toolbox/matlab/cond.m at line 13
In test1.m at line 2
In test.m at line 3
See Also
2-450
dbclear, dbcont, dbdown, dbquit, dbstatus, dbstep, dbstop, dbtype, dbup
dbstatus
Purpose
2dbstatus
Graphical
Interface
As an alternative to the dbstatus function, you can see breakpoint icons for a
file that is open in the Editor/Debugger.
Syntax
dbstatus
dbstatus function
s = dbstatus(...)
Description
dbstatus lists all breakpoints in effect including error, warning, and naninf.
List all breakpoints
dbstatus function displays a list of the line numbers for which breakpoints
are set in the specified M-file.
s = dbstatus(...) returns the breakpoint information in an m-by-1
structure with the fields
name
Function name
line
Function line number
cond
Condition string (error, warning, or
naninf)
Use dbstatus class/function or dbstatus private/function or
dbstatus class/private/function to determine the status for methods,
private functions, or private methods (for a class named class). In all these
forms you can further qualify the function name with a subfunction name as in
dbstatus function/subfunction.
See Also
dbclear, dbcont, dbdown, dbquit, dbstack, dbstep, dbstop, dbtype, dbup
2-451
dbstep
Purpose
2dbstep
Graphical
Interface
As an alternative to the dbstep function, you can select Step or Step In from
the Debug menu in the Editor/Debugger.
Syntax
dbstep
dbstep nlines
dbstep in
Description
This function allows you to debug an M-file by following its execution from the
current breakpoint. At a breakpoint, the dbstep function steps through
execution of the current M-file one line at a time or at the rate specified by
nlines.
Execute one or more lines from current breakpoint
dbstep, by itself, executes the next executable line of the current M-file. dbstep
steps over the current line, skipping any breakpoints set in functions called by
that line.
dbstep nlines executes the specified number of executable lines.
dbstep in steps to the next executable line. If that line contains a call to
another M-file, execution resumes with the first executable line of the called
file. If there is no call to an M-file on that line, dbstep in is the same as dbstep.
See Also
2-452
dbclear, dbcont, dbdown, dbquit, dbstack, dbstatus, dbstop, dbtype, dbup
dbstop
Purpose
2dbstop
Graphical
Interface
As an alternative to the dbstop function, you can use the Breakpoints menu
or the breakpoint alley in the Editor/Debugger.
Syntax
dbstop
dbstop
dbstop
dbstop
dbstop
dbstop
dbstop
dbstop
Description
dbstop in mfile temporarily stops execution of mfile when you run it, at the
first executable line, putting MATLAB in debug mode. mfile must be in a
directory that is on the search path or in the current directory. If you have
graphical debugging enabled, the MATLAB Debugger opens with a breakpoint
at the first executable line of mfile. You can then use the debugging utilities,
review the workspace, or issue any valid MATLAB function. Use dbcont or
dbstep to resume execution of mfile. Use dbquit to exit from the Debugger.
Set breakpoints in M-file function
in
in
in
if
if
if
if
if
mfile
mfile at lineno
mfile at subfun
error
all error
warning
naninf
infnan
dbstop in mfile at lineno temporarily stops execution of mfile when you
run it, just prior to execution of the line whose number is lineno, putting
MATLAB in debug mode. mfile must be in a directory that is on the search
path or in the current directory. If you have graphical debugging enabled, the
MATLAB Debugger opens mfile with a breakpoint at line lineno. If that line
is not executable, execution stops and the breakpoint is set at the next
executable line following lineno. When execution stops, you can use the
debugging utilities, review the workspace, or issue any valid MATLAB
function. Use dbcont or dbstep to resume execution of mfile. Use dbquit to
exit from the Debugger.
dbstop in mfile at subfun temporarily stops execution of mfile when you
run it, just prior to execution of the subfunction subfun, putting MATLAB in
debug mode. mfile must be in a directory that is on the search path or in the
current directory. If you have graphical debugging enabled, the MATLAB
Debugger opens mfile with a breakpoint at the subfunction specified by
2-453
dbstop
subfun. You can then use the debugging utilities, review the workspace, or
issue any valid MATLAB function. Use dbcont or dbstep to resume execution
of mfile. Use dbquit to exit from the Debugger.
dbstop if error stops execution when any M-file you subsequently run
produces a run-time error, putting MATLAB in debug mode, paused at the line
that generated the error. The M-file must be in a directory that is on the search
path or in the current directory. The errors that stop execution do not include
run-time errors that are detected within a try...catch block. You cannot
resume execution after an error. Use dbquit to exit from the Debugger.
dbstop if all error is the same as dbstop if error, except that it stops
execution on any type of run-time error, including errors that are detected
within a try...catch block.
dbstop if warning stops execution when any M-file you subsequently run
produces a run-time warning, putting MATLAB in debug mode, paused at the
line that generated the warning. The M-file must be in a directory that is on
the search path or in the current directory. Use dbcont or dbstep to resume
execution.
dbstop if naninf or dbstop if infnan stops execution when any M-file you
subsequently run encounters an infinite value (Inf) or a value that is not a
number (NaN), putting MATLAB in debug mode, paused at the line where Inf
or NaN was encountered. For convenience, you can use either naninf or
infnan—they perform in exactly the same manner. The M-file must be in a
directory that is on the search path or in the current directory. Use dbcont or
dbstep to resume execution. Use dbquit to exit from the Debugger.
Remarks
2-454
The at, in, and if keywords, familiar to users of the UNIX debugger dbx, are
optional.
dbstop
Examples
The file buggy, used in these examples, consists of three lines.
function z = buggy(x)
n = length(x);
z = (1:n)./x;
Stop at First Executable Line
The statements
dbstop in buggy
buggy(2:5)
stop execution at the first executable line in buggy
n = length(x);
The function
dbstep
advances to the next line, at which point you can examine the value of n.
Stop if Error
Because buggy only works on vectors, it produces an error if the input x is a full
matrix. The statements
dbstop if error
buggy(magic(3))
produce
??? Error using ==> ./
Matrix dimensions must agree.
Error in ==> c:\buggy.m
On line 3 ==> z = (1:n)./x;
K»
and put MATLAB in debug mode.
2-455
dbstop
Stop if InfNaN
In buggy, if any of the elements of the input x is zero, a division by zero occurs.
The statements
dbstop if naninf
buggy(0:2)
produce
Warning: Divide by zero.
> In c:\buggy.m at line 3
K»
and put MATLAB in debug mode.
See Also
2-456
break, dbclear, dbcont, dbdown, dbquit, dbstack, dbstatus, dbstep, dbtype,
dbup, keyboard, partialpath, return
dbtype
Purpose
2dbtype
Graphical
Interface
As an alternative to the dbtype function, you can see an M-file with line
numbers by opening it in the Editor/Debugger.
Syntax
dbtype function
dbtype function start:end
Description
dbtype function displays the contents of the specified M-file function with
line numbers preceding each line. function must be the name of an M-file
function or a MATLABPATH relative partial pathname.
List M-file with line numbers
dbtype function start:end displays the portion of the file specified by a
range of line numbers.
You cannot use dbtype for built-in functions.
Examples
To see only the input and output arguments for a function, that is, the first line
of the M-file, type
dtype function 1
For example,
dbtype fileparts 1
returns
1
See Also
function [path, fname, extension,version] = fileparts(name)
dbclear, dbcont, dbdown, dbquit, dbstack, dbstatus, dbstep, dbstop, dbup,
partialpath
2-457
dbup
Purpose
2dbup
Graphical
Interface
As an alternative to the dbup function, you can select a different workspace
from the Stack field in the toolbar of the Editor/Debugger.
Syntax
dbup
Description
This function allows you to examine the calling M-file by using any other
MATLAB function. In this way, you determine what led to the arguments’
being passed to the called function.
Change local workspace context
dbup changes the current workspace context (at a breakpoint) to the workspace
of the calling M-file.
Multiple dbup functions change the workspace context to each previous calling
M-file on the stack until the base workspace context is reached. (It is not
necessary, however, to move back to the current breakpoint to continue
execution or to step to the next line.)
See Also
2-458
dbclear, dbcont, dbdown, dbquit, dbstack, dbstatus, dbstep, dbstop, dbtype
dde23
Purpose
2dde23
Solve delay differential equations (DDEs) with constant delays
Syntax
sol = dde23(ddefun,lags,history,tspan)
sol = dde23(ddefun,lags,history,tspan,options)
sol = dde23(ddefun,lags,history,tspan,options,p1,p2,...)
Arguments
ddefun
Function that evaluates the right side of the differential
equations y′ ( t ) = f ( t, y ( t ), y ( t – τ 1 ), …, y ( t – τ k ) ). The function
must have the form
dydt = ddefun(t,y,Z)
where t corresponds to the current t , y is a column vector that
approximates y ( t ) , and Z(:,j) approximates y ( t – τ j ) for
delay τ j = lags(j). The output is a column vector
corresponding to f ( t, y ( t ), y ( t – τ 1 ), …, y ( t – τ k ) ).
lags
Vector of constant, positive delays τ 1, …, τ k .
history
Specify history in one of three ways:
• A function of t such that y = history(t) returns the
solution y ( t ) for t ≤ t0 as a column vector
• A constant column vector, if y ( t ) is constant
• The solution sol from a previous integration, if this call
continues that integration
Description
tspan
Interval of integration as a vector [t0,tf] with t0 < tf.
options
Optional integration argument. A structure you create using
the ddeset function. See ddeset for details.
p1,p2,...
Optional parameters that dde23 passes to ddefun, history if
it is a function, and any functions you specify in options.
sol = dde23(ddefun,lags,history,tspan) integrates the system of DDEs
y′ ( t ) = f ( t, y ( t ), y ( t – τ 1 ), …, y ( t – τ k ) )
on the interval [ t 0, t f ] , where τ 1, …, τ k are constant, positive delays and
t0 < t f .
2-459
dde23
dde23 returns the solution as a structure sol. Use the auxiliary function deval
and the output sol to evaluate the solution at specific points tint in the
interval tspan = [t0,tf].
yint = deval(sol,tint)
The structure sol returned by dde23 has the following fields.
sol.x
Mesh selected by dde23
sol.y
Approximation to y ( x ) at the mesh points in sol.x.
sol.yp
Approximation to y′ ( x ) at the mesh points in sol.x
sol.solver
Solver name, 'dde23'
sol = dde23(ddefun,lags,history,tspan,options) solves as above with
default integration properties replaced by values in options, an argument
created with ddeset. See ddeset and “Initial Value Problems for DDEs” in the
MATLAB documentation for details.
Commonly used options are scalar relative error tolerance 'RelTol' (1e-3 by
default) and vector of absolute error tolerances 'AbsTol' (all components are
1e-6 by default).
Use the 'Jumps' option to solve problems with discontinuities in the history or
solution. Set this option to a vector that contains the locations of
discontinuities in the solution prior to t0 (the history) or in coefficients of the
equations at known values of t after t0.
Use the 'Events' option to specify a function that dde23 calls to find where
functions g ( t, y ( t ), y ( t – τ 1 ), …, y ( t – τ k ) ) vanish. This function must be of the
form
[value,isterminal,direction] = events(t,y,Z)
and contain an event function for each event to be tested. For the kth event
function in events:
• value(k) is the value of the kth event function.
• isterminal(k) = 1 if you want the integration to terminate at a zero of this
event function and 0 otherwise.
2-460
dde23
• direction(k) = 0 if you want dde23 to compute all zeros of this event
function, +1 if only zeros where the event function increases, and -1 if only
zeros where the event function decreases.
If you specify the 'Events' option and events are detected, the output
structure sol also includes fields:
sol.xe
Row vector of locations of all events, i.e., times when an event
function vanished
sol.ye
Matrix whose columns are the solution values corresponding to
times in sol.xe
sol.ie
Vector containing indices that specify which event occurred at
the corresponding time in sol.xe
sol = dde23(ddefun,lags,history,tspan,options,p1,p2,...) passes the
parameters p1,p2,... to the DDE function as ddefun(t,y,z,p1,p2,...), to
the history function, if there is one, as history (t,p1,p2,...), and similarly
to all functions specified in options. Use options = [] as a place holder if no
options are set.
Examples
This example solves a DDE on the interval [0, 5] with lags 1 and 0.2. The
function ddex1de computes the delay differential equations, and ddex1hist
computes the history for t <= 0.
Note The demo ddex1 contains the complete code for this example. To see the
code in an editor, click the example name, or type edit ddex1 at the command
line. To run the example type ddex1 at the command line.
sol = dde23(@ddex1de,[1, 0.2],@ddex1hist,[0, 5]);
This code evaluates the solution at 100 equally spaced points in the interval
[0,5], then plots the result.
tint = linspace(0,5);
yint = deval(sol,tint);
plot(tint,yint);
2-461
dde23
ddex1 shows how you can code this problem using subfunctions. For more
examples see ddex2.
Algorithm
dde23 tracks discontinuities and integrates with the explicit Runge-Kutta (2,3)
pair and interpolant of ode23. It uses iteration to take steps longer than the
lags.
See Also
ddeget, ddeset, deval, @ (function_handle)
References
L.F. Shampine and S. Thompson, “Solving DDEs in MATLAB,” Applied
Numerical Mathematics, Vol. 37, 2001, pp. 441-458.
2-462
ddeadv
Purpose
2ddeadv
Set up advisory link
Syntax
rc
rc
rc
rc
Description
ddeadv sets up an advisory link between MATLAB and a server application.
When the data identified by the item argument changes, the string specified
by the callback argument is passed to the eval function and evaluated. If the
advisory link is a hot link, DDE modifies upmtx, the update matrix, to reflect
the data in item.
=
=
=
=
ddeadv(channel,'item','callback')
ddeadv(channel,'item','callback','upmtx')
ddeadv(channel,'item','callback','upmtx',format)
ddeadv(channel,'item','callback','upmtx',format,timeout)
If you omit optional arguments that are not at the end of the argument list, you
must substitute the empty matrix for the missing argument(s).
If successful, ddeadv returns 1 in variable, rc. Otherwise it returns 0.
Arguments
channel
Conversation channel from ddeinit.
item
String specifying the DDE item name for the advisory link.
Changing the data identified by item at the server triggers the
advisory link.
callback
String specifying the callback that is evaluated on update
notification. Changing the data identified by item at the server
causes callback to get passed to the eval function to be
evaluated.
upmtx
String specifying the name of a matrix that holds data sent
with an update notification. If upmtx is included, changing
item at the server causes upmtx to be updated with the revised
data. Specifying upmtx creates a hot link. Omitting upmtx or
specifying it as an empty string creates a warm link. If upmtx
exists in the workspace, its contents are overwritten. If upmtx
does not exist, it is created.
(optional)
2-463
ddeadv
format
(optional)
timeout
(optional)
Examples
Two-element array specifying the format of the data to be sent
on update. The first element specifies the Windows clipboard
format to use for the data. The only currently supported format
is cf_text, which corresponds to a value of 1. The second
element specifies the type of the resultant matrix. Valid types
are numeric (the default, which corresponds to a value of 0)
and string (which corresponds to a value of 1). The default
format array is [1 0].
Scalar specifying the time-out limit for this operation. timeout
is specified in milliseconds. (1000 milliseconds = 1 second). If
advisory link is not established within timeout milliseconds,
the function fails. The default value of timeout is three
seconds.
Set up a hot link between a range of cells in Excel (Row 1, Column 1 through
Row 5, Column 5) and the matrix x. If successful, display the matrix:
rc = ddeadv(channel, 'r1c1:r5c5', 'disp(x)', 'x');
Communication with Excel must have been established previously with a
ddeinit command.
See Also
2-464
ddeexec, ddeinit, ddepoke, ddereq, ddeterm, ddeunadv
ddeexec
Purpose
2ddeexec
Send string for execution
Syntax
rc = ddeexec(channel,'command')
rc = ddeexec(channel,'command','item')
rc = ddeexec(channel,'command','item',timeout)
Description
ddeexec sends a string for execution to another application via an established
DDE conversation. Specify the string as the command argument.
If you omit optional arguments that are not at the end of the argument list, you
must substitute the empty matrix for the missing argument(s).
If successful, ddeexec returns 1 in variable, rc. Otherwise it returns 0.
Arguments
channel
Conversation channel from ddeinit.
command
String specifying the command to be executed.
item
String specifying the DDE item name for execution. This
argument is not used for many applications. If your application
requires this argument, it provides additional information for
command. Consult your server documentation for more
information.
(optional)
timeout
(optional)
Examples
Scalar specifying the time-out limit for this operation. timeout
is specified in milliseconds. (1000 milliseconds = 1 second). The
default value of timeout is three seconds.
Given the channel assigned to a conversation, send a command to Excel:
rc = ddeexec(channel,'[formula.goto("r1c1")]')
Communication with Excel must have been established previously with a
ddeinit command.
See Also
ddeadv, ddeinit, ddepoke, ddereq, ddeterm, ddeunadv
2-465
ddeget
Purpose
2ddeget
Extract properties from options structure created with ddeset
Syntax
val = ddeget(options,'name')
val = ddeget(options,'name',default)
Description
val = ddeget(options,'name') extracts the value of the named property
from the structure options, returning an empty matrix if the property value is
not specified in options. It is sufficient to type only the leading characters that
uniquely identify the property. Case is ignored for property names. [] is a valid
options argument.
val = ddeget(options,'name',default) extracts the named property as
above, but returns val = default if the named property is not specified in
options. For example,
val = ddeget(opts,'RelTol',1e-4);
returns val = 1e-4 if the RelTol is not specified in opts.
See Also
2-466
dde23, ddeset
ddeinit
Purpose
2ddeinit
Initiate DDE conversation
Syntax
channel = ddeinit('service','topic')
Description
channel = ddeinit('service','topic') returns a channel handle assigned
to the conversation, which is used with other MATLAB DDE functions.
'service' is a string specifying the service or application name for the
conversation. 'topic' is a string specifying the topic for the conversation.
Examples
To initiate a conversation with Excel for the spreadsheet 'stocks.xls':
channel = ddeinit('excel','stocks.xls')
channel =
0.00
See Also
ddeadv, ddeexec, ddepoke, ddereq, ddeterm, ddeunadv
2-467
ddepoke
Purpose
2ddepoke
Send data to application
Syntax
rc = ddepoke(channel,'item',data)
rc = ddepoke(channel,'item',data,format)
rc = ddepoke(channel,'item',data,format,timeout)
Description
ddepoke sends data to an application via an established DDE conversation.
ddepoke formats the data matrix as follows before sending it to the server
application:
• String matrices are converted, element by element, to characters and the
resulting character buffer is sent.
• Numeric matrices are sent as tab-delimited columns and carriage-return,
line-feed delimited rows of numbers. Only the real part of nonsparse
matrices are sent.
If you omit optional arguments that are not at the end of the argument list, you
must substitute the empty matrix for the missing argument(s).
If successful, ddepoke returns 1 in variable, rc. Otherwise it returns 0.
Arguments
channel
Conversation channel from ddeinit.
item
String specifying the DDE item for the data sent. Item is the
server data entity that is to contain the data sent in the data
argument.
data
Matrix containing the data to send.
format
Scalar specifying the format of the data requested. The value
indicates the Windows clipboard format to use for the data
transfer. The only format currently supported is cf_text,
which corresponds to a value of 1.
(optional)
timeout
(optional)
2-468
Scalar specifying the time-out limit for this operation. timeout
is specified in milliseconds. (1000 milliseconds = 1 second). The
default value of timeout is three seconds.
ddepoke
Examples
Assume that a conversation channel with Excel has previously been
established with ddeinit. To send a 5-by-5 identity matrix to Excel, placing the
data in Row 1, Column 1 through Row 5, Column 5:
rc = ddepoke(channel, 'r1c1:r5c5', eye(5));
See Also
ddeadv, ddeexec, ddeinit, ddereq, ddeterm, ddeunadv
2-469
ddereq
Purpose
2ddereq
Request data from application
Syntax
data = ddereq(channel,'item')
data = ddereq(channel,'item',format)
data = ddereq(channel,'item',format,timeout)
Description
ddereq requests data from a server application via an established DDE
conversation. ddereq returns a matrix containing the requested data or an
empty matrix if the function is unsuccessful.
If you omit optional arguments that are not at the end of the argument list, you
must substitute the empty matrix for the missing argument(s).
If successful, ddereq returns a matrix containing the requested data in
variable, data. Otherwise, it returns an empty matrix.
Arguments
channel
Conversation channel from ddeinit.
item
String specifying the server application's DDE item name for
the data requested.
format
Two-element array specifying the format of the data requested.
The first element specifies the Windows clipboard format to
use. The only currently supported format is cf_text, which
corresponds to a value of 1. The second element specifies the
type of the resultant matrix. Valid types are numeric (the
default, which corresponds to 0) and string (which
corresponds to a value of 1). The default format array is [1 0].
(optional)
timeout
(optional)
Examples
Scalar specifying the time-out limit for this operation. timeout
is specified in milliseconds. (1000 milliseconds = 1 second). The
default value of timeout is three seconds.
Assume that we have an Excel spreadsheet stocks.xls. This spreadsheet
contains the prices of three stocks in row 3 (columns 1 through 3) and the
number of shares of these stocks in rows 6 through 8 (column 2). Initiate
conversation with Excel with the command:
channel = ddeinit('excel','stocks.xls')
2-470
ddereq
DDE functions require the rxcy reference style for Excel worksheets. In Excel
terminology the prices are in r3c1:r3c3 and the shares in r6c2:r8c2.
To request the prices from Excel:
prices = ddereq(channel,'r3c1:r3c3')
prices =
42.50
15.00
78.88
To request the number of shares of each stock:
shares = ddereq(channel, 'r6c2:r8c2')
shares =
100.00
500.00
300.00
See Also
ddeadv, ddeexec, ddeinit, ddepoke, ddeterm, ddeunadv
2-471
ddeset
Purpose
2ddeset
Create/alter delay differential equations (DDE) options structure
Syntax
options = ddeset('name1',value1,'name2',value2,...)
options = ddeset(oldopts,'name1',value1,...)
options = ddeset(oldopts,newopts)
ddeset
Description
options = ddeset('name1',value1,'name2',value2,...) creates an
integrator options structure options in which the named properties have the
specified values. Any unspecified properties have default values. It is sufficient
to type only the leading characters that uniquely identify the property. Case is
ignored for property names.
options = ddeset(oldopts,'name1',value1,...) alters an existing options
structure oldopts.
options = ddeset(oldopts,newopts) combines an existing options structure
oldopts with a new options structure newopts. Any new properties overwrite
corresponding old properties.
ddeset with no input arguments displays all property names and their possible
values.
DDE Properties
These properties are available:
Property
Value
Description
RelTol
Positive scalar
{1e-3}
Relative error tolerance that applies to all components
of the solution vector. The estimated error in each
integration step satisfies
|e(i)| <= max(RelTol*abs(y(i)),AbsTol(i)).
AbsTol
Positive scalar or
vector {1e-6}
Absolute error tolerance that applies to all components
of the solution vector. Elements of a vector of tolerances
apply to corresponding components of the solution
vector.
2-472
ddeset
Property
Value
Description
NormControl
on | {off}
Control error relative to norm of solution. Set this
property on to request that dde23 control the error in
each integration step with
norm(e) <= max(RelTol*norm(y),AbsTol). By default
dde23 uses a more stringent component-wise error
control.
Stats
on | {off}
Display computational cost statistics.
Events
Function
The solver uses the specified function to locate where
functions of t, y, Z vanish. See dde23 for details.
MaxStep
Positive scalar
{0.1*tspan}
Upper bound on the magnitude of the step size. The
default is one-tenth of the tspan interval.
InitialStep
Positive scalar
Suggested initial step size. The solver tries this first. By
default the solver determines an initial step size
automatically.
OutputFcn
Function
Installable output function. This output function is
called by the solver after each time step. When a solver
is called with no output arguments, OutputFcn defaults
to the function odeplot. Otherwise, OutputFcn defaults
to [].
To create or modify an output function, see ODE Solver
Output Properties in the “Differential Equations”
section of the MATLAB documentation.
OutputSel
Vector of integers
Output selection indices. Specifies the components of
the solution vector that dde23 passes to the OutputFcn.
The default is all components.
2-473
ddeset
Property
Value
Description
Jumps
Vector
Location of discontinuities in solution. Points t where
the history or solution may have a jump discontinuity in
a low-order derivative. See dde23 for details.
InitialY
Vector
Initial value of solution. By default the initial value of
the solution is the value returned by history at the
initial point. A different initial value can be supplied as
the value of the InitialY property.
See Also
2-474
dde23, ddeget, @ (function_handle)
ddeterm
Purpose
2ddeterm
Terminate DDE conversation
Syntax
rc = ddeterm(channel)
Description
rc = ddeterm(channel) accepts a channel handle returned by a previous call
to ddeinit that established the DDE conversation. ddeterm terminates this
conversation. rc is a return code where 0 indicates failure and 1 indicates
success.
Examples
To close a conversation channel previously opened with ddeinit:
rc = ddeterm(channel)
rc =
1.00
See Also
ddeadv, ddeexec, ddeinit, ddepoke, ddereq, ddeunadv
2-475
ddeunadv
Purpose
2ddeunadv
Release advisory link
Syntax
rc = ddeunadv(channel,'item')
rc = ddeunadv(channel,'item',format)
rc = ddeunadv(channel,'item',format,timeout)
Description
ddeunadv releases the advisory link between MATLAB and the server
application established by an earlier ddeadv call. The channel, item, and
format must be the same as those specified in the call to ddeadv that initiated
the link. If you include the timeout argument but accept the default format,
you must specify format as an empty matrix.
If successful, ddeunadv returns 1 in variable, rc. Otherwise it returns 0.
Arguments
channel
Conversation channel from ddeinit.
item
String specifying the DDE item name for the advisory link.
Changing the data identified by item at the server triggers the
advisory link.
format
Two-element array. This must be the same as the format
argument for the corresponding ddeadv call.
(optional)
timeout
(optional)
Example
Scalar specifying the time-out limit for this operation. timeout
is specified in milliseconds. (1000 milliseconds = 1 second). The
default value of timeout is three seconds.
To release an advisory link established previously with ddeadv:
rc = ddeunadv(channel, 'r1c1:r5c5')
rc =
1.00
See Also
2-476
ddeadv, ddeexec, ddeinit, ddepoke, ddereq, ddeterm
deal
Purpose
2deal
Deal inputs to outputs
Syntax
[Y1,Y2,Y3,...] = deal(X)
[Y1,Y2,Y3,...] = deal(X1,X2,X3,...)
Description
[Y1,Y2,Y3,...] = deal(X) copies the single input to all the requested
outputs. It is the same as Y1 = X, Y2 = X, Y3 = X, ...
[Y1,Y2,Y3,...] = deal(X1,X2,X3,...) is the same as Y1 = X1; Y2 = X2;
Y3 = X3; ...
Remarks
deal is most useful when used with cell arrays and structures via comma
separated list expansion. Here are some useful constructions:
[S.field] = deal(X) sets all the fields with the name field in the structure
array S to the value X. If S doesn't exist, use [S(1:m).field] = deal(X).
[X{:}] = deal(A.field) copies the values of the field with name field to
the cell array X. If X doesn't exist, use [X{1:m}] = deal(A.field).
[Y1,Y2,Y3,...] = deal(X{:}) copies the contents of the cell array X to the
separate variables Y1,Y2,Y3,...
[Y1,Y2,Y3,...] = deal(S.field) copies the contents of the fields with the
name field to separate variables Y1,Y2,Y3,...
Examples
Use deal to copy the contents of a 4-element cell array into four separate
output variables.
C = {rand(3) ones(3,1) eye(3) zeros(3,1)};
[a,b,c,d] = deal(C{:})
a =
0.9501
0.2311
0.6068
0.4860
0.8913
0.7621
0.4565
0.0185
0.8214
b =
2-477
deal
1
1
1
c =
1
0
0
0
1
0
0
0
1
d =
0
0
0
Use deal to obtain the contents of all the name fields in a structure array:
A.name = 'Pat'; A.number = 176554;
A(2).name = 'Tony'; A(2).number = 901325;
[name1,name2] = deal(A(:).name)
name1 =
Pat
name2 =
Tony
2-478
deblank
Purpose
2deblank
Strip trailing blanks from the end of a string
Syntax
str = deblank(str)
c = deblank(c)
Description
str = deblank(str) removes the trailing blanks from the end of a character
string str.
c = deblank(c), when c is a cell array of strings, applies deblank to each
element of c.
The deblank function is useful for cleaning up the rows of a character array.
Examples
A{1,1}
A{1,2}
A{2,1}
A{2,2}
=
=
=
=
'MATLAB
';
'SIMULINK
';
'Toolboxes
';
'The MathWorks
';
A =
'MATLAB
'
'Toolboxes
'
'SIMULINK
'
'The MathWorks
'
deblank(A)
ans =
'MATLAB'
'Toolboxes'
'SIMULINK'
'The MathWorks'
2-479
dec2base
Purpose
2dec2base
Decimal number to base conversion
Syntax
str = dec2base(d,base)
str = dec2base(d,base,n)
Description
str = dec2base(d,base) converts the nonnegative integer d to the specified
base.d must be a nonnegative integer smaller than 2^52, and base must be an
integer between 2 and 36. The returned argument str is a string.
str = dec2base(d,base,n) produces a representation with at least n digits.
Examples
The expression dec2base(23,2) converts 2310 to base 2, returning the string
'10111'.
See Also
base2dec
2-480
dec2bin
Purpose
2dec2bin
Decimal to binary number conversion
Syntax
str = dec2bin(d)
str = dec2bin(d,n)
Description
str = dec2bin(d) returns the binary representation of d as a string. d must
be a nonnegative integer smaller than 2^52.
str = dec2bin(d,n) produces a binary representation with at least n bits.
Examples
ans =
10111
See Also
bin2dec, dec2hex
2-481
dec2hex
Purpose
2dec2hex
Decimal to hexadecimal number conversion
Syntax
str = dec2hex(d)
str = dec2hex(d,n)
Description
str = dec2hex(d) converts the decimal integer d to its hexadecimal
representation stored in a MATLAB string. d must be a nonnegative integer
smaller than 2^52.
str = dec2hex(d,n) produces a hexadecimal representation with at least n
digits.
Examples
To convert decimal 1023 to hexadecimal,
dec2hex(1023)
ans =
3FF
See Also
2-482
dec2bin, format, hex2dec, hex2num
deconv
Purpose
2deconv
Deconvolution and polynomial division
Syntax
[q,r] = deconv(v,u)
Description
[q,r] = deconv(v,u) deconvolves vector u out of vector v, using long division.
The quotient is returned in vector q and the remainder in vector r such that v
= conv(u,q)+r.
If u and v are vectors of polynomial coefficients, convolving them is equivalent
to multiplying the two polynomials, and deconvolution is polynomial division.
The result of dividing v by u is quotient q and remainder r.
Examples
If
u = [1
v = [10
2
3
20
4]
30]
the convolution is
c = conv(u,v)
c =
10
40
100
160
170
120
Use deconvolution to recover u:
[q,r] = deconv(c,u)
q =
10
20
30
r =
0
0
0
0
0
0
This gives a quotient equal to v and a zero remainder.
Algorithm
deconv uses the filter primitive.
See Also
conv, residue
2-483
del2
Purpose
2del2
Discrete Laplacian
Syntax
L
L
L
L
Definition
If the matrix U is regarded as a function u ( x, y ) evaluated at the point on a
square grid, then 4*del2(U) is a finite difference approximation of Laplace’s
differential operator applied to u , that is:
=
=
=
=
del2(U)
del2(U,h)
del2(U,hx,hy)
del2(U,hx,hy,hz,...)
2
2
2
∇ u 1  d u d u
l = ----------- = ---  ---------- + ----------
4
4  dx 2 d y 2
where:
1
l ij = --- ( u i + 1, j + u i – 1, j + u i,
4
j+1
+ u i,
j – 1 ) – u i,
in the interior. On the edges, the same formula is applied to a cubic
extrapolation.
For functions of more variables u ( x, y, z, … ) , del2(U) is an approximation,
2
2
2
2

∇ u
1 d u d u d u
l = ----------- = ---------  ---------- + ---------- + ---------- + …
2 N 2 N  dx 2 d y 2 dz 2

where N is the number of variables in u .
Description
L = del2(U) where U is a rectangular array is a discrete approximation of
2
2
2
∇ u 1  d u d u
l = ----------- = ---  ---------- + ----------
4
4  dx 2 d y 2
The matrix L is the same size as U with each element equal to the difference
between an element of U and the average of its four neighbors.
2-484
del2
-L = del2(U) when U is an multidimensional array, returns an
approximation of
2
∇ u
----------2N
where N is ndims(u).
L = del2(U,h) where H is a scalar uses H as the spacing between points in each
direction (h=1 by default).
L = del2(U,hx,hy) when U is a rectangular array, uses the spacing specified
by hx and hy. If hx is a scalar, it gives the spacing between points in the
x-direction. If hx is a vector, it must be of length size(u,2) and specifies the
x-coordinates of the points. Similarly, if hy is a scalar, it gives the spacing
between points in the y-direction. If hy is a vector, it must be of length
size(u,1) and specifies the y-coordinates of the points.
L = del2(U,hx,hy,hz,...) where U is multidimensional uses the spacing
given by hx, hy, hz, ...
Examples
The function
u ( x, y ) = x 2 + y 2
has
∇2u = 4
For this function, 4*del2(U) is also 4.
[x,y] = meshgrid(-4:4,-3:3);
U = x.*x+y.*y
U =
25
18
13
10
20
13
8
5
17
10
5
2
16
9
4
1
17
10
5
2
20
13
8
5
25
18
13
10
9
4
1
0
1
4
9
10
5
2
1
2
5
10
13
8
5
4
5
8
13
18
13
10
9
10
13
18
25
20
17
16
17
20
25
2-485
del2
V = 4*del2(U)
V =
4
4
4
4
4
4
4
4
4
4
4
4
4
4
See Also
2-486
diff, gradient
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
delaunay
Purpose
2delaunay
Delaunay triangulation
Syntax
TRI = delaunay(x,y)
Definition
Given a set of data points, the Delaunay triangulation is a set of lines
connecting each point to its natural neighbors. The Delaunay triangulation is
related to the Voronoi diagram— the circle circumscribed about a Delaunay
triangle has its center at the vertex of a Voronoi polygon.
x
Delaunay triangle
Voronoi polygon
Description
TRI = delaunay(x,y) for the data points defined by vectors x and y, returns a
set of triangles such that no data points are contained in any triangle's
circumscribed circle. Each row of the m-by-3 matrix TRI defines one such
triangle and contains indices into x and y. If the original data points are
collinear or x is empty, the triangles cannot be computed and delaunay returns
an empty matrix.
Remarks
The Delaunay triangulation is used by: griddata (to interpolate scattered
data), voronoi (to compute the voronoi diagram), and is useful by itself to
create a triangular grid for scattered data points.
The functions dsearch and tsearch search the triangulation to find nearest
neighbor points or enclosing triangles, respectively.
Visualization
Use one of these functions to plot the output of delaunay:
2-487
delaunay
triplot
Displays the triangles defined in the m-by-3 matrix TRI. See
Example 1.
trisurf
Displays each triangle defined in the m-by-3 matrix TRI as a
surface in 3-D space. To see a 2-D surface, you can supply a
vector of some constant value for the third dimension. For
example
trisurf(TRI,x,y,zeros(size(x)))
See Example 2.
trimesh
Displays each triangle defined in the m-by-3 matrix TRI as a
mesh in 3-D space. To see a 2-D surface, you can supply a vector
of some constant value for the third dimension. For example,
trimesh(TRI,x,y,zeros(size(x)))
produces almost the same result as triplot, except in 3-D
space. See Example 2.
Examples
Example 1. Plot the Delaunay triangulation for 10 randomly generated points.
rand('state',0);
x = rand(1,10);
y = rand(1,10);
TRI = delaunay(x,y);
subplot(1,2,1),...
triplot(TRI,x,y)
axis([0 1 0 1]);
hold on;
plot(x,y,'or');
hold off
Compare the Voronoi diagram of the same points:
[vx, vy] = voronoi(x,y,TRI);
subplot(1,2,2),...
plot(x,y,'r+',vx,vy,'b-'),...
axis([0 1 0 1])
2-488
delaunay
Delaunay
triangulation
1
1
0.9
0.9
0.8
0.8
0.7
0.7
0.6
0.6
0.5
0.5
0.4
0.4
0.3
0.3
0.2
0.2
0.1
0.1
0
0
0.2
0.4
0.6
0.8
1
0
Voronoi
diagram
0
0.2
0.4
0.6
0.8
1
Example 2. Create a 2-D grid then use trisurf to plot its Delaunay
triangulation in 3-D space by using 0s for the third dimension.
[x,y] = meshgrid(1:15,1:15);
tri = delaunay(x,y);
trisurf(tri,x,y,zeros(size(x)))
2-489
delaunay
1
0.5
0
−0.5
−1
15
15
10
10
5
5
0
0
Next, generate peaks data as a 15-by-15 matrix, and use that data with the
Delaunay triangulation to produce a surface in 3-D space.
z = peaks(15);
trisurf(tri,x,y,z)
10
5
0
−5
−10
15
15
10
10
5
5
0
2-490
0
delaunay
You can use the same data with trimesh to produce a mesh in 3-D space.
trimesh(tri,x,y,z)
10
5
0
−5
−10
15
15
10
10
5
5
0
0
Algorithm
delaunay is based on Qhull . It uses the Qhull joggle option ('QJ'). For
information about qhull, see http://www.geom.umn.edu/software/qhull/.
For copyright information, see
http://www.geom.umn.edu/software/download/COPYING.html.
See Also
delaunay3, delaunayn, dsearch, griddata, plot, triplot, trimesh, trisurf,
tsearch, voronoi
References
[1] Barber, C. B., D.P. Dobkin, and H.T. Huhdanpaa, "The Quickhull Algorithm for
Convex Hulls," ACM Transactions on Mathematical Software, Vol. 22, No. 4,
Dec. 1996, p. 469-483. Available in HTML format at
http://www.acm.org/pubs/citations/journals/toms/1996-22-4/p469-bar
ber/ and in PostScript format at
ftp://geom.umn.edu/pub/software/qhull-96.ps.
[2] National Science and Technology Research Center for Computation and
Visualization of Geometric Structures (The Geometry Center), University of
Minnesota. 1993.
2-491
delaunay3
Purpose
2delaunay3
3-D Delaunay tessellation
Syntax
TES = delaunay3(x,y,z)
Description
TES = delaunay3(x,y,z) returns an array TES, each row of which contains the
indices of the points in (x,y,z) that make up a tetrahedron in the tessellation
of (x,y,z). TES is a numtes-by-4 array where numtes is the number of facets in
the tessellation. x, y, and z are vectors of equal length. If the original data
points are collinear or x, y, and z define an insufficient number of points, the
triangles cannot be computed and delaunay3 returns an empty matrix.
Visualization
Use tetramesh to plot delaunay3 output. tetramesh displays the tetrahedrons
defined in TES as mesh. tetramesh uses the default tranparency parameter
value 'FaceAlpha' = 0.9.
Example
This example generates a 3-D Delaunay tessellation, then uses tetramesh to
plot the tetrahedrons that form the corresponding simplex. camorbit rotates
the camera position to provide a meaningful view of the figure.
d = [-1 1];
[x,y,z] = meshgrid(d,d,d); % A cube
x = [x(:);0];
y = [y(:);0];
z = [z(:);0];
% [x,y,z] are corners of a cube plus the center.
Tes = delaunay3(x,y,z)
Tes =
9
3
2
2
2
7
7
8
8
8
2-492
1
9
9
3
3
9
3
7
2
2
5
1
1
9
9
5
9
9
9
9
6
5
6
4
1
6
5
6
6
4
delaunay3
8
8
3
7
9
3
4
9
X = [x(:) y(:) z(:)];
tetramesh(Tes,X);camorbit(20,0)
Algorithm
delaunay3 is based on Qhull [2]. It uses the Qhull joggle option ('QJ'). For
information about qhull, see http://www.geom.umn.edu/software/qhull/.
For copyright information, see
http://www.geom.umn.edu/software/download/COPYING.html.
See Also
delaunay, delaunayn
Reference
[1] Barber, C. B., D.P. Dobkin, and H.T. Huhdanpaa, "The Quickhull Algorithm for
Convex Hulls," ACM Transactions on Mathematical Software, Vol. 22, No. 4,
Dec. 1996, p. 469-483. Available in HTML format at
http://www.acm.org/pubs/citations/journals/toms/1996-22-4/p469-bar
ber/ and in PostScript format at
ftp://geom.umn.edu/pub/software/qhull-96.ps.
2-493
delaunay3
[2] National Science and Technology Research Center for Computation and
Visualization of Geometric Structures (The Geometry Center), University of
Minnesota. 1993.
2-494
delaunayn
Purpose
2delaunayn
n-D Delaunay tessellation
Syntax
T = delaunayn(X)
Description
T = delaunayn(X) computes a set of simplices such that no data points of X are
contained in any circumspheres of the simplices. The set of simplices forms the
Delaunay tessellation. X is an m-by-n array representing m points in n-D space.
T is a numt-by-(n+1) array where each row contains the indices into X of the
vertices of the corresponding simplex.
Visualization
Plotting the output of delaunayn depends of the value of n:
• For n = 2, use triplot, trisurf, or trimesh as you would for delaunay.
• For n = 3, use tetramesh as you would for delaunay3.
For more control over the color of the facets, use patch to plot the output. For
an example, see “Tessellation and Interpolation of Scattered Data in Higher
Dimensions” in the MATLAB documentation.
• You cannot plot delaunayn output for n > 3.
Example
This example generates an n-D Delaunay tessellation, where n = 3.
d = [-1 1];
[x,y,z] = meshgrid(d,d,d); % A cube
x = [x(:);0];
y = [y(:);0];
z = [z(:);0];
% [x,y,z] are corners of a cube plus the center.
X = [x(:) y(:) z(:)];
Tes = delaunayn(X)
Tes =
9
3
2
2
2
7
7
8
1
9
9
3
3
9
3
7
5
1
1
9
9
5
9
9
6
5
6
4
1
6
5
6
2-495
delaunayn
8
8
8
8
2
2
3
7
9
9
9
3
6
4
4
9
You can use tetramesh to visualize the tetrahedrons that form the
corresponding simplex. camorbit rotates the camera position to provide a
meaningful view of the figure.
tetramesh(Tes,X);camorbit(20,0)
Algorithm
delaunayn is based on Qhull [2],. It uses the Qhull joggle option ('QJ'). For
information about qhull, see http://www.geom.umn.edu/software/qhull/.
For copyright information, see
http://www.geom.umn.edu/software/download/COPYING.html.
See Also
convhulln, delaunayn, delaunay3, tetramesh, voronoin
Reference
[1] Barber, C. B., D.P. Dobkin, and H.T. Huhdanpaa, "The Quickhull Algorithm for
Convex Hulls," ACM Transactions on Mathematical Software, Vol. 22, No. 4,
Dec. 1996, p. 469-483. Available in HTML format at
2-496
delaunayn
http://www.acm.org/pubs/citations/journals/toms/1996-22-4/p469-bar
ber/ and in PostScript format at
ftp://geom.umn.edu/pub/software/qhull-96.ps.
[2] National Science and Technology Research Center for Computation and
Visualization of Geometric Structures (The Geometry Center), University of
Minnesota. 1993.
2-497
delete
Purpose
2delete
Graphical
Interface
As an alternative to the delete function, you can delete files using the Current
Directory browser.
Syntax
delete filename
delete(h)
delete('filename')
Description
delete filename deletes the named file from the disk. The filename may
Delete files or graphics objects
include an absolute pathname or a pathname relative to the current directory.
The filename may also include wildcards, (*).
delete(h) deletes the graphics object with handle h. The function deletes the
object without requesting verification even if the object is a window.
delete('filename') is the function form of delete. Use this form when the
filename is stored in a string.
Note MATLAB does not ask for confirmation when you enter the delete
command. To avoid accidentally losing files or graphics objects that you need,
make sure that you have accurately specified the items you want deleted.
Examples
To delete all files with a .mat extension in the ../mytests/ directory, type
delete('../mytests/*.mat')
To delete a directory, use rmdir rather than delete:
rmdir mydirectory
See Also
2-498
dir, edit, mkdir, rmdir, type
delete (COM)
Purpose
2delete (COM)
Delete a COM control or server
Syntax
delete(h)
Arguments
h
Handle for a COM object previously returned from actxcontrol, actxserver,
get, or invoke.
Description
Release all interfaces derived from the specified COM server or control, and
then delete the server or control itself. This is different from releasing an
interface, which releases and invalidates only that interface.
Examples
Create a Microsoft Calender application. Then create a TitleFont interface
and use it to change the appearance of the font of the calendar’s title:
f = figure('pos',[300 300 500 500]);
cal = actxcontrol('mscal.calendar', [0 0 500 500], f);
TFont = get(cal, 'TitleFont')
TFont =
Interface.mscal.calendar.TitleFont
set(TFont, 'Name', 'Viva BoldExtraExtended');
set(TFont, 'Bold', 0);
When you’re finished working with the title font, release the TitleFont
interface:
release(TFont);
Now create a GridFont interface and use it to modify the size of the calendar’s
date numerals:
GFont = get(cal, 'GridFont')
GFont =
Interface.mscal.calendar.GridFont
set(GFont, 'Size', 16);
When you’re done, delete the cal object and the figure window. Deleting the
cal object also releases all interfaces to the object (e.g., GFont):
2-499
delete (COM)
delete(cal);
delete(f);
clear f;
Note that, although the object and interfaces themselves have been destroyed,
the variables assigned to them still reside in the MATLAB workspace until you
remove them with clear.
whos
Name
GFont
TFone
cal
Size
Bytes
1x1
1x1
1x1
Grand total is 3 elements using 0 bytes
See Also
2-500
release, save, load, actxcontrol, actxserver
0
0
0
Class
handle
handle
handle
delete (serial)
Purpose
2delete (serial)
Remove a serial port object from memory
Syntax
delete(obj)
Arguments
obj
Description
delete(obj) removes obj from memory.
Remarks
When you delete obj, it becomes an invalid object. Because you cannot connect
an invalid serial port object to the device, you should remove it from the
workspace with the clear command. If multiple references to obj exist in the
workspace, then deleting one reference invalidates the remaining references.
A serial port object or an array of serial port objects.
If obj is connected to the device, it has a Status property value of open. If you
issue delete while obj is connected, then the connection is automatically
broken. You can also disconnect obj from the device with the fclose function.
If you use the help command to display help for delete, then you need to
supply the pathname shown below.
help serial/delete
Example
This example creates the serial port object s, connects s to the device, writes
and reads text data, disconnects s from the device, removes s from memory
using delete, and then removes s from the workspace using clear.
s = serial('COM1');
fopen(s)
fprintf(s,'*IDN?')
idn = fscanf(s);
fclose(s)
delete(s)
clear s
See Also
Functions
clear, fclose, isvalid
Properties
Status
2-501
delete (timer)
Purpose
2delete (timer)
Remove a timer object from memory
Syntax
delete(obj)
Description
delete(obj) removes timer object, obj, from memory. If obj is an array of
timer objects, delete removes all the objects from memory.
When you delete a timer object, it becomes invalid and cannot be reused. Use
the clear command to remove invalid timer objects from the workspace.
If multiple references to a timer object exist in the workspace, deleting the
timer object invalidates the remaining references. Use the clear command to
remove the remaining references to the object from the workspace.
See Also
2-502
clear, isvalid, timer
deleteproperty (COM)
Purpose
2deleteproperty (COM)
Remove custom property from COM object
Syntax
deleteproperty(h, 'propertyname')
Arguments
h
Handle for a COM object previously returned from actxcontrol, actxserver,
get, or invoke.
propertyname
A string specifying the name of the custom property to delete.
Description
Delete a property, propertyname, from the custom properties belonging to
object or interface, h. You can only delete properties that have been created
with addproperty.
Examples
Create an mwsamp control and add a new property named Position to it. Assign
an array value to the property:
f = figure('pos', [100 200 200 200]);
h = actxcontrol('mwsamp.mwsampctrl.2', [0 0 200 200], f);
get(h)
Label: 'Label'
Radius: 20
addproperty(h, 'Position');
set(h, 'Position', [200 120]);
get(h)
Label: 'Label'
Radius: 20
Position: [200 120]
Delete the custom Position property:
deleteproperty(h, 'Position');
get(h)
Label: 'Label'
Radius: 20
See Also
addproperty, get, set, inspect
2-503
demo
Purpose
2demo
Access product demos via Help browser
Syntax
demo
demo subtopic
demo subtopic category
Description
demo opens the Demos panel in the Help browser. In the left pane, expand the
listing for a product area (for example, MATLAB). Within that product area,
expand the listing for a product or product category (for example, MATLAB
Graphics). Select a specific demo from the list (for example, Visualizing Sound).
In the right pane, view instructions for using the demo. For more information,
see Running Demonstrations. For platforms that do not support Java GUIs,
the demos are presented in a non-Java interface. To run a demo from the
command line, type the demo name. For playshow demos, that is those demos
in which the H1 line begins with two comment symbols (%%), type playshow
followed by the demo name.
demo subtopic opens the Demos panel in the Help browser with the specified
subtopic expanded. Subtopics are matlab, toolbox, simulink, and blockset.
demo subtopic product opens the Demos panel in the Help browser to the
specified product or category within the subtopic.
2-504
demo
Type demo to access the Demos panel in the Help browser.
View the demos for products installed on your system. When you choose a
demo, information about it appears in the display pane.
Examples
To run an M-file demo, click this link.
When you click this link, the M-file source code
for the demo appears in your editor.
Accessing Toolbox Demos
To find the demos relating to the Communications Toolbox, type
demo toolbox communication
The Help browser opens to the Demos panel with the Toolbox subtopic
expanded and with the Communications product highlighted and expanded to
show the available demos.
Accessing the Simulink Automotive Demos
To accesses the automotive demos within Simulink, type
demo simulink automotive
2-505
demo
The Demos panel opens with the Simulink subtopic and Automotive category
expanded.
Running a Demo from the Command Line
Type
vibes
to run a visualization demonstration showing an animated L-shaped
membrane.
Running a Playshow Demo from the Command Line
Type
quake
to run an earthquake data demo. Not much appears to happen. This is because
quake is a playshow demo. Verify this by viewing the M-file, quake.m, for
example, by typing
edit quake
The first line, that is, the H1 line for quake is
%% Loma Prieta Earthquake
The %% indicates that quake is a playshow demo. So to run it, type
playshow quake
and the earthquake demo runs.
See Also
2-506
help, helpbrowser, helpwin, lookfor
depdir
Purpose
2depdir
List the dependent directories of an M-file or P-file
Syntax
list = depdir('file_name');
[list,prob_files,prob_sym,prob_strings] = depdir('file_name');
[...] = depdir('file_name1','file_name2',...);
Description
The depdir function lists the directories of all of the functions that a specified
M-file or P-file needs to operate. This function is useful for finding all of the
directories that need to be included with a runtime application and for
determining the runtime path.
list = depdir('file_name') creates a cell array of strings containing the
directories of all the M-files and P-files that file_name.m or file_name.p uses.
This includes the second-level files that are called directly by file_name, as
well as the third-level files that are called by the second-level files, and so on.
[list,prob_files,prob_sym,prob_strings] = depdir('file_name')
creates three additional cell arrays containing information about any problems
with the depdir search. prob_files contains filenames that depdir was
unable to parse. prob_sym contains symbols that depdir was unable to find.
prob_strings contains callback strings that depdir was unable to parse.
[...] = depdir('file_name1','file_name2',...) performs the same
operation for multiple files. The dependent directories of all files are listed
together in the output cell arrays.
Example
See Also
list = depdir('mesh')
depfun
2-507
depfun
Purpose
2depfun
List the dependent functions of an M-file or P-file
Syntax
list = depfun('file_name');
[list,builtins,classes] = depfun('file_name');
[list,builtins,classes,prob_files,prob_sym,eval_strings,...
called_from,java_classes] = depfun('file_name');
[...] = depfun('file_name1','file_name2',...);
[...] = depfun('fig_file_name');
[...] = depfun(...,'-toponly');
Description
The depfun function lists all of the functions and scripts, as well as built-in
functions, that a specified M-file needs to operate. This is useful for finding all
of the M-files that you need to compile for a MATLAB runtime application.
list = depfun('file_name') creates a cell array of strings containing the
paths of all the files that file_name.m uses. This includes the second-level files
that are called directly by file_name.m, as well as the third-level files that are
called by the second-level files, and so on.
Note If depfun reports that “These files could not be parsed:” or if the
prob_files output below is nonempty, then the rest of the output of depfun
might be incomplete. You should correct the problematic files and invoke
depfun again.
[list,builtins,classes] = depfun('file_name') creates three cell arrays
containing information about dependent functions. list contains the paths of
all the files that file_name and its subordinates use. builtins contains the
built-in functions that file_name and its subordinates use. classes contains
the MATLAB classes that file_name and its subordinates use.
[list,builtins,classes,prob_files,prob_sym,eval_strings,...
called_from,java_classes] = depfun('file_name') creates additional cell
arrays or structure arrays containing information about any problems with the
depfun search and about where the functions in list are invoked. The
additional outputs are:
2-508
depfun
• prob_files, which indicates which files depfun was unable to parse, find, or
access. Parsing problems can arise from MATLAB syntax errors. prob_files
is a structure array whose fields are:
- name, which gives the names of the files
- listindex, which tells where the files appeared in list
- errmsg, which describes the problems
• prob_sym, which indicates which symbols depfun was unable to resolve as
functions or variables. It is a structure array whose fields are:
- fcn_id, which tells where the files appeared in list
- name, which gives the names of the problematic symbols
• eval_strings, which indicates usage of these evaluation functions: eval,
evalc, evalin, feval. When preparing a runtime application, you should
examine this output to determine whether an evaluation function invokes a
function that does not appear in list. The output eval_strings is a
structure array whose fields are:
- fcn_name, which give the names of the files that use evaluation functions
- lineno, which gives the line numbers in the files where the evaluation
functions appear
• called_from, a cell array of the same length as list. This cell array is
arranged so that
list(called_from{i})
returns all functions in file_name that invoke the function list{i}.
• java_classes, a cell array of Java class names that file_name and its
subordinates use
[...] = depfun('file_name1','file_name2',...) performs the same
operation for multiple files. The dependent functions of all files are listed
together in the output arrays.
[...] = depfun('fig_file_name') looks for dependent functions among the
callback strings of the GUI elements that are defined in the .fig or .mat file
named fig_file_name.
[...] = depfun(...,'-toponly') differs from the other syntaxes of depfun
in that it examines only the files listed explicitly as input arguments. It does
2-509
depfun
not examine the files on which they depend. In this syntax, the flag '-toponly'
must be the last input argument.
Notes
1 If depfun does not find a file called hginfo.mat on the path, then it creates
one. This file contains information about Handle Graphics callbacks.
2 If your application uses toolbar items from the MATLAB default figure
window, then you must include 'FigureToolBar.fig' in your input to
depfun.
3 If your application uses menu items from the MATLAB default figure
window, then you must include 'FigureMenuBar.fig' in your input to
depfun.
4 Because many built-in Handle Graphics functions invoke newplot, the list
produced by depfun always includes the functions on which newplot is
dependent:
- 'matlabroot\toolbox\matlab\graphics\newplot.m'
- 'matlabroot\toolbox\matlab\graphics\closereq.m'
- 'matlabroot\toolbox\matlab\graphics\gcf.m'
- 'matlabroot\toolbox\matlab\graphics\gca.m'
- 'matlabroot\toolbox\matlab\graphics\private\clo.m'
- 'matlabroot\toolbox\matlab\general\@char\delete.m'
- 'matlabroot\toolbox\matlab\lang\nargchk.m'
- 'matlabroot\toolbox\matlab\uitools\allchild.m'
- 'matlabroot\toolbox\matlab\ops\setdiff.m'
- 'matlabroot\toolbox\matlab\ops\@cell\setdiff.m'
- 'matlabroot\toolbox\matlab\iofun\filesep.m'
- 'matlabroot\toolbox\matlab\ops\unique.m'
- 'matlabroot\toolbox\matlab\elmat\repmat.m'
- 'matlabroot\toolbox\matlab\datafun\sortrows.m'
- 'matlabroot\toolbox\matlab\strfun\deblank.m'
- 'matlabroot\toolbox\matlab\ops\@cell\unique.m'
- 'matlabroot\toolbox\matlab\strfun\@cell\deblank.m'
- 'matlabroot\toolbox\matlab\datafun\@cell\sort.m'
- 'matlabroot\toolbox\matlab\strfun\cellstr.m'
- 'matlabroot\toolbox\matlab\datatypes\iscell.m'
- 'matlabroot\toolbox\matlab\strfun\iscellstr.m'
2-510
depfun
- 'matlabroot\toolbox\matlab\datatypes\cellfun.dll'
Examples
See Also
list = depfun('mesh'); % Files mesh.m depends on
list = depfun('mesh','-toponly') % Files mesh.m depends on
directly
[list,builtins,classes] = depfun('gca');
depdir, profile
2-511
det
Purpose
2det
Matrix determinant
Syntax
d = det(X)
Description
d = det(X) returns the determinant of the square matrix X. If X contains only
integer entries, the result d is also an integer.
Remarks
Using det(X) == 0 as a test for matrix singularity is appropriate only for
matrices of modest order with small integer entries. Testing singularity using
abs(det(X)) <= tolerance is not recommended as it is difficult to choose the
correct tolerance. The function cond(X) can check for singular and nearly
singular matrices.
Algorithm
The determinant is computed from the triangular factors obtained by Gaussian
elimination
[L,U] = lu(A)
s = det(L)
% This is always +1 or -1
det(A) = s*prod(diag(U))
Examples
The statement A = [1
2
3;
4
5
6;
7
8
9]
produces
A =
1
4
7
2
5
8
3
6
9
This happens to be a singular matrix, so d = det(A) produces d = 0.
Changing A(3,3) with A(3,3) = 0 turns A into a nonsingular matrix. Now
d = det(A) produces d = 27.
See Also
cond, condest, inv, lu, rref
The arithmetic operators \, /
2-512
detrend
Purpose
2detrend
Remove linear trends.
Syntax
y = detrend(x)
y = detrend(x,'constant')
y = detrend(x,'linear',bp)
Description
detrend removes the mean value or linear trend from a vector or matrix,
usually for FFT processing.
y = detrend(x) removes the best straight-line fit from vector x and returns it
in y. If x is a matrix, detrend removes the trend from each column.
y = detrend(x,'constant') removes the mean value from vector x or, if x is
a matrix, from each column of the matrix.
y = detrend(x,'linear',bp) removes a continuous, piecewise linear trend
from vector x or, if x is a matrix, from each column of the matrix. Vector bp
contains the indices of the breakpoints between adjacent linear segments. The
breakpoint between two segments is defined as the data point that the two
segments share.
breakpoints
detrend(x,'linear'), with no breakpoint vector specified, is the same as
detrend(x).
Example
sig = [0 1 -2 1 0 1 -2 1 0];
trend = [0 1 2 3 4 3 2 1 0];
x = sig+trend;
y = detrend(x,'linear',5)
%
%
%
%
signal with no linear trend
two-segment linear trend
signal with added trend
breakpoint at 5th element
2-513
detrend
y =
-0.0000
1.0000
-2.0000
1.0000
0.0000
1.0000
-2.0000
1.0000
-0.0000
Note that the breakpoint is specified to be the fifth element, which is the data
point shared by the two segments.
Algorithm
detrend computes the least-squares fit of a straight line (or composite line for
piecewise linear trends) to the data and subtracts the resulting function from
the data. To obtain the equation of the straight-line fit, use polyfit.
See Also
2-514
polyfit
deval
Purpose
2deval
Evaluate the solution of a differential equation problem
Syntax
sxint
sxint
sxint
sxint
Description
sxint = deval(sol,xint) and sxint = deval(xint,sol) evaluate the
solution of a differential equation problem. sol is a structure returned by one
=
=
=
=
deval(sol,xint)
deval(xint,sol)
deval(sol,xint,idx)
deval(xint,sol,idx)
of these solvers:
• An initial value problem solver (ode45, ode23, ode113, ode15s, ode23s,
ode23t, ode23tb),
• The delay differential equations solver (dde23),
• The boundary value problem solver (bvp4c).
xint is a point or a vector of points at which you want the solution. The
elements of xint must be in the interval [sol.x(1),sol.x(end)]. For each i,
sxint(:,i) is the solution at xint(i).
sxint = deval(sol,xint,idx) and sxint = deval(xint,sol,idx) evaluate
as above but return only the solution components with indices listed in idx.
Example
This example solves the system y′ = vdp1 ( t, y ) using ode45, and evaluates
and plots the first component of the solution at 100 points in the interval
[0,20].
sol = ode45(@vdp1,[0 20],[2 0]);
x = linspace(0,20,100);
y = deval(sol,x,1);
plot(x,y);
2-515
deval
2.5
2
1.5
1
0.5
0
−0.5
−1
−1.5
−2
−2.5
0
See Also
5
15
20
ODE solvers: ode45, ode23, ode113, ode15s, ode23s, ode23t, ode23tb
DDE solver: dde23
BVP solver: bvp4c
2-516
10
diag
Purpose
2diag
Diagonal matrices and diagonals of a matrix
Syntax
X
X
v
v
Description
X = diag(v,k) when v is a vector of n components, returns a square matrix X
of order n+abs(k), with the elements of v on the kth diagonal. k = 0 represents
the main diagonal, k > 0 above the main diagonal, and k < 0 below the main
=
=
=
=
diag(v,k)
diag(v)
diag(X,k)
diag(X)
diagonal.
k=0
k>0
k<0
X = diag(v) puts v on the main diagonal, same as above with k = 0.
v = diag(X,k) for matrix X, returns a column vector v formed from the
elements of the kth diagonal of X.
v = diag(X) returns the main diagonal of X, same as above with k = 0.
Examples
diag(diag(X)) is a diagonal matrix.
sum(diag(X)) is the trace of X.
The statement
diag(-m:m)+diag(ones(2*m,1),1)+diag(ones(2*m,1),-1)
produces a tridiagonal matrix of order 2*m+1.
2-517
diag
See Also
2-518
spdiags, tril, triu
dialog
Purpose
2dialog
Create and display dialog box
Syntax
h = dialog('PropertyName',PropertyValue,...)
Description
h = dialog('PropertyName',PropertyValue,...) returns a handle to a
dialog box. This function creates a figure graphics object and sets the figure
properties recommended for dialog boxes. You can specify any valid figure
property value.
See Also
errordlg, figure, helpdlg, inputdlg, pagedlg, printdlg, questdlg, uiwait,
uiresume, warndlg
“Predefined Dialog Boxes” for related functions
2-519
diary
Purpose
2diary
Save session to a file
Syntax
diary
diary('filename')
diary off
diary on
diary filename
Description
The diary function creates a log of keyboard input and the resulting output
(except it does not include graphics). The output of diary is an ASCII file,
suitable for printing or for inclusion in reports and other documents. If you do
not specify filename, MATLAB creates a file named diary in the current
directory.
diary toggles diary mode on and off. To see the status of diary, type
get(0,'Diary'). MATLAB returns either on or off indicating the diary
status.
diary('filename') writes a copy of all subsequent keyboard input and the
resulting output (except it does not include graphics) to the named file, where
filename is the full pathname or filename is in the current MATLAB
directory. If the file already exists, output is appended to the end of the file. You
cannot use a filename called off or on. To see the name of the diary file, use
get(0,'DiaryFile').
diary off suspends the diary.
diary on resumes diary mode using the current filename, or the default
filename diary if none has yet been specified.
diary filename is the unquoted form of the syntax.
See Also
2-520
Command History window in MATLAB Development Environment
documentation
diff
Purpose
2diff
Differences and approximate derivatives
Syntax
Y = diff(X)
Y = diff(X,n)
Y = diff(X,n,dim)
Description
Y = diff(X) calculates differences between adjacent elements of X.
If X is a vector, then diff(X) returns a vector, one element shorter than X, of
differences between adjacent elements:
[X(2)-X(1) X(3)-X(2) ... X(n)-X(n-1)]
If X is a matrix, then diff(X) returns a matrix of row differences:
[X(2:m,:)-X(1:m-1,:)]
In general, diff(X) returns the differences calculated along the first
non-singleton (size(X,dim) > 1) dimension of X.
Y = diff(X,n) applies diff recursively n times, resulting in the nth
difference. Thus, diff(X,2) is the same as diff(diff(X)).
Y = diff(X,n,dim) is the nth difference function calculated along the
dimension specified by scalar dim. If order n equals or exceeds the length of
dimension dim, diff returns an empty array.
Remarks
Since each iteration of diff reduces the length of X along dimension dim, it is
possible to specify an order n sufficiently high to reduce dim to a singleton
(size(X,dim) = 1) dimension. When this happens, diff continues calculating
along the next nonsingleton dimension.
Examples
The quantity diff(y)./diff(x) is an approximate derivative.
x = [1 2 3 4 5];
y = diff(x)
y =
1
1
1
1
z = diff(x,2)
z =
2-521
diff
0
0
0
Given,
A = rand(1,3,2,4);
diff(A) is the first-order difference along dimension 2.
diff(A,3,4) is the third-order difference along dimension 4.
See Also
2-522
gradient, prod, sum
dir
Purpose
2dir
Graphical
Interface
As an alternative to the dir function, use the Current Directory browser.
Syntax
dir
dir name
files = dir('name')
Description
dir lists the files in the current working directory.
Display directory listing
dir name lists the specified files. The name argument can be a pathname,
filename, or can include both. You can use absolute and relative pathnames
and wildcards (*).
files = dir('directory') returns the list of files in the specified directory
(or the current directory, if dirname is not specified) to an m-by-1 structure with
the fields
Examples
name
Filename
date
Modification date
bytes
Number of bytes allocated to the file
isdir
1 if name is a directory; 0 if not
List Directory Contents
To view the contents of the matlab/audio directory, type
dir $matlabroot/toolbox/matlab/audio
Using Wildcard and File Extension
To view the MAT files in your current working directory that include the term
java, type
dir *java*.mat
MATLAB returns
java_array.mat
javafrmobj.mat
testjava.mat
2-523
dir
Using Relative Pathname
To view the M-files in the MATLAB audio directory, type
dir(fullfile(matlabroot,'toolbox/matlab/audio/*.m'))
MATLAB returns
Contents.m
audiodevinfo.m
audioplayer.m
audioplayerreg.m
audiorecorder.m
audiouniquename.m
auread.m
auwrite.m
lin2mu.m
mu2lin.m
prefspanel.m
sound.m
soundsc.m
wavplay.m
wavread.m
wavrecord.m
wavwrite.m
Returning File List to Structure
To return the list of files to the variable audio_files, type
audio_files=dir(fullfile(matlabroot,'toolbox/matlab/audio/*.m')
)
MATLAB returns the information in a structure array.
audio_files =
19x1 struct array with fields:
name
date
bytes
isdir
Index into the structure to access a particular item. For example,
audio_files(3).name
ans =
audioplayer.m
See Also
2-524
cd, copyfile, delete, fileattrib, filebrowser, ls, mkdir, movefile, rmdir,
type, what
disp
Purpose
2disp
Display text or array
Syntax
disp(X)
Description
disp(X) displays an array, without printing the array name. If X contains a
text string, the string is displayed.
Another way to display an array on the screen is to type its name, but this
prints a leading “X =,” which is not always desirable.
Note that disp does not display empty arrays.
Examples
One use of disp in an M-file is to display a matrix with column labels:
disp('
Corn
disp(rand(5,3))
Oats
Hay')
which results in
Corn
0.2113
0.0820
0.7599
0.0087
0.8096
See Also
Oats
0.8474
0.4524
0.8075
0.4832
0.6135
Hay
0.2749
0.8807
0.6538
0.4899
0.7741
format, int2str, num2str, rats, sprintf
2-525
disp (serial)
Purpose
2disp (serial)
Display serial port object summary information
Syntax
obj
disp(obj)
Arguments
obj
Description
obj or disp(obj) displays summary information for obj.
Remarks
In addition to the syntax shown above, you can display summary information
for obj by excluding the semicolon when:
A serial port object or an array of serial port objects.
• Creating a serial port object
• Configuring property values using the dot notation
Use the display summary to quickly view the communication settings,
communication state information, and information associated with read and
write operations.
Example
The following commands display summary information for the serial port
object s.
s = serial('COM1')
s.BaudRate = 300
s
2-526
disp (timer)
Purpose
2disp (timer)
Display information about timer object
Syntax
obj
disp(obj)
Description
obj or disp(obj) displays summary information for timer object, obj.
If obj is an array of timer objects, disp outputs a table of summary information
about the timer objects in the array.
In addition to the syntax shown above, you can display summary information
for obj by excluding the semicolon when:
• Creating a timer object, using the timer function
• Configuring property values using the dot notation
Example
The following commands display summary information for the timer object t.
t = timer
Timer Object: timer-1
Timer Settings
ExecutionMode:
Period:
BusyMode:
Running:
singleShot
1
drop
off
Callbacks
TimerFcn:
ErrorFcn:
StartFcn:
StopFcn:
[]
[]
[]
[]
This example shows the summary information displayed for an array of timer
objects, t_arr.
disp(t_arr)
Timer Object Array
2-527
disp (timer)
Index:
1
2
See Also
2-528
timer, get
ExecutionMode:
singleShot
singleShot
Period:
1
1
TimerFcn:
[]
[]
Name:
timer-1
timer-2
display
Purpose
2display
Overloaded method to display an object
Syntax
display(X)
Description
display(X) prints the value of a variable or expression, X. MATLAB calls
display(X) when it interprets a variable or expression, X, that is not
terminated by a semicolon. For example, sin(A) calls display, while sin(A);
does not.
If X is an instance of a MATLAB class, then MATLAB calls the display method
of that class, if such a method exists. If the class has no display method or if X
is not an instance of a MATLAB class, then the MATLAB builtin display
function is called.
Examples
A typical implementation of display calls disp to do most of the work and looks
like this.
function display(X)
if isequal(get(0,'FormatSpacing'),'compact')
disp([inputname(1) ' =']);
disp(X)
else
disp(' ')
disp([inputname(1) ' =']);
disp(' ');
disp(X)
end
The expression magic(3), with no terminating semicolon, calls this function as
display(magic(3)).
magic(3)
ans =
8
3
4
1
5
9
6
7
2
As an example of a class display method, the function below implements the
display method for objects of the MATLAB class, polynom.
2-529
display
function display(p)
% POLYNOM/DISPLAY Command window display of a polynom
disp(' ');
disp([inputname(1),' = '])
disp(' ');
disp(['
' char(p)])
disp(' ');
The statement
p = polynom([1 0 -2 -5])
creates a polynom object. Since the statement is not terminated with a
semicolon, the MATLAB interpreter calls display(p), resulting in the output
p =
x^3 - 2*x - 5
See Also
2-530
disp, ans, sprintf, special characters
divergence
Purpose
2divergence
Computes the divergence of a vector field
Syntax
div
div
div
div
Description
div = divergence(X,Y,Z,U,V,W) computes the divergence of a 3-D vector
field U, V, W. The arrays X, Y, Z define the coordinates for U, V, W and must be
monotonic and 3-D plaid (as if produced by meshgrid).
=
=
=
=
divergence(X,Y,Z,U,V,W)
divergence(U,V,W)
divergence(X,Y,U,V)
divergence(U,V)
div = divergence(U,V,W) assumes X, Y, and Z are determined by the
expression:
[X Y Z] = meshgrid(1:n,1:m,1:p)
where [m,n,p] = size(U).
div = divergence(X,Y,U,V) computes the divergence of a 2-D vector field U,
V. The arrays X, Y define the coordinates for U, V and must be monotonic and
2-D plaid (as if produced by meshgrid).
div = divergence(U,V) assumes X and Y are determined by the expression:
[X Y] = meshgrid(1:n,1:m)
where [m,n] = size(U).
Examples
This example displays the divergence of vector volume data as slice planes
using color to indicate divergence.
load wind
div = divergence(x,y,z,u,v,w);
slice(x,y,z,div,[90 134],[59],[0]);
shading interp
daspect([1 1 1])
camlight
2-531
divergence
See Also
streamtube, curl, isosurface
“Volume Visualization” for related functions
Displaying Divergence with Stream Tubes for another example
2-532
dlmread
Purpose
2dlmread
Graphical
Interface
As an alternative to dlmread, use the Import Wizard. To activate the Import
Wizard, select Import data from the File menu.
Syntax
M = dlmread(filename,delimiter)
M = dlmread(filename,delimiter,R,C)
M = dlmread(filename,delimiter,range)
Description
M = dlmread(filename,delimiter) reads numeric data from the ASCII
delimited file filename, using the specified delimiter. A comma (,) is the
default delimiter. Use '\t' to specify a tab delimiter.
Read an ASCII delimited file into a matrix
M = dlmread(filename,delimiter,R,C) reads numeric data from the ASCII
delimited file filename, using the specified delimiter. The values R and C
specify the row and column where the upper-left corner of the data lies in the
file. R and C are zero based so that R=0, C=0 specifies the first value in the file,
which is the upper left corner.
M = dlmread(filename,delimiter,range) reads the range specified by
range = [R1 C1 R2 C2] where (R1,C1) is the upper-left corner of the data to
be read and (R2,C2) is the lower-right corner. range can also be specified using
spreadsheet notation as in range = 'A1..B7'.
Remarks
dlmread fills empty delimited fields with zero. Data files having lines that end
with a non-space delimiter, such as a semi-colon, produce a result that has an
additional last column of zeros.
See Also
dlmwrite, textread, csvread, csvwrite, wk1read, wk1write
2-533
dlmwrite
Purpose
2dlmwrite
Write a matrix to an ASCII delimited file
Syntax
dlmwrite(filename,M,delimiter)
dlmwrite(filename,M,delimiter,R,C)
Description
dlmwrite(filename,M,delimiter) writes matrix M into an ASCII-format file,
using delimiter to separate matrix elements. The data is written to the upper
left-most cell of the spreadsheet filename. A comma (,) is the default delimiter.
Use '\t' to produce tab-delimited files.
dlmwrite(filename,M,delimiter,R,C) writes matrix A into an ASCII-format
file, using delimiter to separate matrix elements. The data is written to the
spreadsheet filename, starting at spreadsheet cell R and C, where R is the row
offset and C is the column offset. R and C are zero based so that R=0, C=0
specifies the first value in the file, which is the upper left corner.
Remarks
The resulting file is readable by spreadsheet programs.
See Also
dlmread, csvwrite, csvread, wk1write, wk1read
2-534
dmperm
Purpose
Syntax
Description
2dmperm
Dulmage-Mendelsohn decomposition
p = dmperm(A)
[p,q,r,s] = dmperm(A)
p = dmperm(A) if A is square and has full rank, returns a row permutation p so
that A(p,:) has nonzero diagonal elements. This permutation is also called a
perfect matching. If A is not square or not full rank, p is a vector that identifies
a matching of maximum size: for each column j of A, either p(j)=0 or
A(p(j),j) is nonzero.
[p,q,r,s] = dmperm(A), where A need not be square or full rank, finds
permutations p and q and index vectors r and s so that A(p,q) is block upper
triangular. The kth block has indices (r(k):r(k+1)-1, s(k):s(k+1)-1).
When A is square and has full rank, r = s.
If A is not square or not full rank, the first block may have more columns and
the last block may have more rows. All other blocks are square and irreducible.
dmperm permutes nonzeros to the diagonals of square blocks, but does not do
this for non-square blocks.
Remarks
If A is a reducible matrix, the linear system Ax = b can be solved by permuting
A to a block upper triangular form, with irreducible diagonal blocks, and then
performing block backsubstitution. Only the diagonal blocks of the permuted
matrix need to be factored, saving fill and arithmetic in the blocks above the
diagonal.
In graph theoretic terms, dmperm finds a maximum-size matching in the
bipartite graph of A, and the diagonal blocks of A(p,q) correspond to the strong
Hall components of that graph. The output of dmperm can also be used to find
the connected or strongly connected components of an undirected or directed
graph. For more information see Pothen and Fan [].
See Also
sprank
References
Pothen, Alex and Chin-Ju Fan, "Computing the Block Triangular Form of a
Sparse Matrix," ACM Transactions on Mathematical Software, Vol. 16, No. 4,
Dec. 1990, pp. 303-324.
2-535
doc
Purpose
2doc
Graphical
Interface
As an alternative to the doc function, use the Help browser Search tab. Set the
Search type to Function Name, type the function name, and click Go.
Syntax
doc
doc function
doc toolbox/
doc toolbox/function
Description
doc opens the Help browser, if it is not already running.
Display online documentation in MATLAB Help browser
doc function displays the reference page for the MATLAB function function
in the Help browser. If function is overloaded, doc displays the reference page
for the first function on the search path and lists the overloaded functions in
the MATLAB Command Window. If a reference page for the function does not
exist, doc displays M-file help in the Help browser.
doc toolbox/ displays the Roadmap page, a summary of the most pertinent
documentation for toolbox, in the Help browser.
doc toolbox/function displays the reference page for function that belongs
to the specified toolbox, in the Help browser.
See Also
2-536
help, helpbrowser, lookfor, type, web
docopt
Purpose
2docopt
Display location of help file directory for UNIX platforms
Syntax
docopt
[doccmd,options,docpath] = docopt
Description
docopt displays the location of the online help files directory (online
documentation location) for UNIX platforms if the web function is used with the
-browser option. It is also used for UNIX platforms that do not support Java
GUIs—see the “Release 13 Release Notes” for more information about these
platforms. You specify where the online help directory will be located when you
install MATLAB. It can be on a disk or CD-ROM drive in your local system. If
you relocate your online help file directory, edit the docopt.m file, changing the
location in it. (For Windows and the UNIX platforms that support Java GUIs,
select File -> Preferences -> Help to view or change the documentation
location.)
[doccmd,options,docpath] = docopt displays three strings: doccmd,
options, and docpath.
Remarks
doccmd
The function that doc uses to display MATLAB documentation.
The default is netscape.
options
Additional configuration options for use with doccmd.
docpath
The path to the MATLAB online help files. If docpath is empty,
the doc function assumes the help files are in the default
location.
To globally replace the online help file directory location, update
$matlabroot/toolbox/local/docopt.m.
To override the global setting, copy $matlabroot/toolbox/local/docopt.m to
$HOME/matlab/docopt.m and make changes there. For the changes to take
effect in the current MATLAB session, $HOME/matlab must be on your
MATLAB path.
See Also
doc, help, helpbrowser, helpdesk, lookfor, type
2-537
docroot
Purpose
2docroot
Graphical
Interface
As an alternative to the docroot function, select File -> Preferences -> Help
and set the Documentation location.
Syntax
docroot
docroot('newdocroot')
docroot(newdocroot, 'cdrom')
Description
docroot displays the current value for docroot, the root directory for MATLAB
Get or set root directory for MATLAB help files
help files. This is the directory where the MATLAB Help browser looks for the
online documentation to display.
docroot('newdocroot') sets the root directory for MATLAB help files to
newdocroot, where newdocroot is the full pathname to the help directory. For
example, type docroot('d:/matlabr13/help'). One useful application is
setting docroot in your startup.m file.
docroot('newdocroot', 'cdrom') sets the root directory for MATLAB help
files on the MATLAB documentation CD to newdocroot, where newdocroot is
the full pathname to the help directory on your MATLAB documentation CD.
For example, type docroot('z:/help', 'cdrom').
Examples
You can include a docroot statement in your startup.m file.
See Also
doc, helpbrowser
2-538
dos
Purpose
2dos
Execute a DOS command and return result
Syntax
dos command
status = dos('command')
[status,result] = dos('command')
[status,result] = dos('command','-echo')
Description
dos command calls upon the shell to execute the given command for Windows
systems.
status = dos('command') returns completion status to the status variable.
[status,result] = dos('command') in addition to completion status, returns
the result of the command to the result variable.
[status,result] = dos('command','-echo') forces the output to the
Command Window, even though it is also being assigned into a variable.
Both console (DOS) programs and Windows programs may be executed, but the
syntax causes different results based on the type of programs. Console
programs have stdout and their output is returned to the result variable. They
are always run in an iconified DOS or Command Prompt Window except as
noted below. Console programs never execute in the background. Also,
MATLAB will always wait for the stdout pipe to close before continuing
execution. Windows programs may be executed in the background as they have
no stdout.
The ampersand, &, character has special meaning. For console programs this
causes the console to open. Omitting this character will cause console programs
to run iconically. For Windows programs, appending this character will cause
the application to run in the background. MATLAB will continue processing.
Examples
The following example performs a directory listing, returning a zero (success)
in s and the string containing the listing in w.
[s, w] = dos('dir');
To open the DOS 5.0 editor in a DOS window
dos('edit &')
2-539
dos
To open the notepad editor and return control immediately to MATLAB
dos('notepad file.m &')
The next example returns a one in s and an error message in w because foo is
not a valid shell command.
[s, w] = dos('foo')
This example echoes the results of the dir command to the Command Window
as it executes as well as assigning the results to w.
[s, w] = dos('dir', '-echo');
See Also
2-540
! (exclamation point), perl, system, unix
dot
Purpose
2dot
Vector dot product
Syntax
C = dot(A,B)
C = dot(A,B,dim)
Description
C = dot(A,B) returns the scalar product of the vectors A and B. A and B must
be vectors of the same length. When A and B are both column vectors, dot(A,B)
is the same as A'*B.
For multidimensional arrays A and B, dot returns the scalar product along the
first non-singleton dimension of A and B. A and B must have the same size.
C = dot(A,B,dim) returns the scalar product of A and B in the dimension dim.
Examples
The dot product of two vectors is calculated as shown:
a = [1 2 3]; b = [4 5 6];
c = dot(a,b)
c =
32
See Also
cross
2-541
double
Purpose
2double
Convert to double-precision
Syntax
double(X)
Description
double(x) returns the double-precision value for X. If X is already a
double-precision array, double has no effect.
Remarks
2-542
double is called for the expressions in for, if, and while loops if the expression
isn't already double-precision. double should be overloaded for any object when
it makes sense to convert it to a double-precision value.
dragrect
Purpose
2dragrect
Drag rectangles with mouse
Syntax
[finalrect] = dragrect(initialrect)
[finalrect] = dragrect(initialrect,stepsize)
Description
[finalrect] = dragrect(initialrect) tracks one or more rectangles
anywhere on the screen. The n-by-4 matrix, initialrect, defines the
rectangles. Each row of initialrect must contain the initial rectangle
position as [left bottom width height] values. dragrect returns the final
position of the rectangles in finalrect.
[finalrect] = dragrect(initialrect,stepsize) moves the rectangles in
increments of stepsize. The lower-left corner of the first rectangle is
constrained to a grid of size equal to stepsize starting at the lower-left corner
of the figure, and all other rectangles maintain their original offset from the
first rectangle.
[finalrect] = dragrect(...) returns the final positions of the rectangles
when the mouse button is released. The default stepsize is 1.
Remarks
dragrect returns immediately if a mouse button is not currently pressed. Use
dragrect in a ButtonDownFcn, or from the command line in conjunction with
waitforbuttonpress to ensure that the mouse button is down when dragrect
is called. dragrect returns when you release the mouse button.
If the drag ends over a figure window, the positions of the rectangles are
returned in that figure's coordinate system. If the drag ends over a part of the
screen not contained within a figure window, the rectangles are returned in the
coordinate system of the figure over which the drag began
Example
Drag a rectangle that is 50 pixels wide and 100 pixels in height.
waitforbuttonpress
point1 = get(gcf,'CurrentPoint') % button down detected
rect = [point1(1,1) point1(1,2) 50 100]
[r2] = dragrect(rect)
See Also
rbbox, waitforbuttonpress
“Selecting Region of Interest” for related functions
2-543
drawnow
Purpose
2drawnow
Complete pending drawing events
Syntax
drawnow
Description
drawnow flushes the event queue and updates the figure window.
Remarks
Other events that cause MATLAB to flush the event queue and draw the figure
windows include:
• Returning to the MATLAB prompt
• A pause statement
• A waitforbuttonpress statement
• A waitfor statement
• A getframe statement
• A figure statement
Examples
Executing the statements,
x = -pi:pi/20:pi;
plot(x,cos(x))
drawnow
title('A Short Title')
grid on
as an M-file updates the current figure after executing the drawnow function
and after executing the final statement.
See Also
waitfor, pause, waitforbuttonpress
“Figure Windows” for related functions
2-544
dsearch
Purpose
2dsearch
Search for nearest point
Syntax
K = dsearch(x,y,TRI,xi,yi)
K = dsearch(x,y,TRI,xi,yi,S)
Description
K = dsearch(x,y,TRI,xi,yi) returns the index into x and y of the nearest
point to the point (xi,yi). dsearch requires a triangulation TRI of the points x,y
obtained using delaunay. If xi and yi are vectors, K is a vector of the same size.
K = dsearch(x,y,TRI,xi,yi,S) uses the sparse matrix S instead of
computing it each time:
S = sparse(TRI(:,[1 1 2 2 3 3]),TRI(:,[2 3 1 3 1 2]),1,nxy,nxy)
where nxy = prod(size(x)).
See Also
delaunay, tsearch, voronoi
2-545
dsearchn
Purpose
2dsearchn
n-D nearest point search
Syntax
k = dsearchn(X,T,XI)
k = dsearchn(X,T,XI,outval)
k = dsearchn(X,XI)
[k,d] = dsearchn(X,...)
Description
k = dsearchn(X,T,XI) returns the indices k of the closest points in X for each
point in XI. X is an m-by-n matrix representing m points in n-D space. XI is a
p-by-n matrix, representing p points in n-D space. T is a numt-by-n+1 matrix, a
tessellation of the data X generated by delaunayn. The output k is a column
vector of length p.
k = dsearchn(X,T,XI,outval) returns the indices k of the closest points in X
for each point in XI, unless a point is outside the convex hull. If XI(J,:) is
outside the convex hull, then K(J) is assigned outval, a scalar double. Inf is
often used for outval. If outval is [], then k is the same as in the case
k = dsearchn(X,T,XI).
k = dsearchn(X,XI) performs the search without using a tessellation. With
large X and small XI, this approach is faster and uses much less memory.
[k,d] = dsearchn(X,...) also returns the distances d to the closest points. d
is a column vector of length p.
See Also
2-546
tsearch, dsearch, tsearchn, griddatan, delaunayn
echo
Purpose
Syntax
Description
2echo
Echo M-files during execution
echo
echo
echo
echo
echo
echo
echo
echo
on
off
fcnname on
fcnname off
fcnname
on all
off all
The echo command controls the echoing of M-files during execution. Normally,
the commands in M-files do not display on the screen during execution.
Command echoing is useful for debugging or for demonstrations, allowing the
commands to be viewed as they execute.
The echo command behaves in a slightly different manner for script files and
function files. For script files, the use of echo is simple; echoing can be either
on or off, in which case any script used is affected.
echo on
Turns on the echoing of commands in all script files.
echo off
Turns off the echoing of commands in all script files.
echo
Toggles the echo state.
With function files, the use of echo is more complicated. If echo is enabled on a
function file, the file is interpreted, rather than compiled. Each input line is
then displayed as it is executed. Since this results in inefficient execution, use
echo only for debugging.
See Also
echo fcnname on
Turns on echoing of the named function file.
echo fcnname off
Turns off echoing of the named function file.
echo fcnname
Toggles the echo state of the named function file.
echo on all
Set echoing on for all function files.
echo off all
Set echoing off for all function files.
function
2-547
edit
Purpose
2edit
Graphical
Interface
As an alternative to the edit function, select New or Open from the File menu
in the MATLAB desktop or any desktop tool.
Syntax
edit
edit
edit
edit
edit
edit
edit
Description
Edit or create M-file
fun.m
file.ext
fun1 fun2 fun3 ...
class/fun
private/fun
class/private/fun
edit opens a new editor window.
edit fun.m opens the M-file fun.m in the default editor. Note that fun.m can
be a MATLAB partialpath or a complete path. If fun.m does not exist, a
prompt appears asking if you want to create a new file titled fun.m. After you
click Yes, the Editor/Debugger creates a blank file titled fun.m. If you do not
want the prompt to appear in this situation, select that check box in the
prompt. Then when you type edit fun.m, where fun.m did not previously exist,
a new file called fun.m is automatically opened in the Editor. To make the
prompt appear, specify it in preferences for “Prompt” on page 7-38.
edit file.ext opens the specified file.
edit fun1 fun2 fun3 ... opens fun1.m, fun2.m, fun3.m, and so on, in the
default editor.
edit class/fun, edit private/fun, or edit class/private/fun can be
used to edit a method, private function, or private method (for the class named
class).
Remarks
2-548
To specify the default editor for MATLAB, select Preferences from the File
menu. On the Editor/Debugger panel, select the MATLAB Editor/Debugger or
specify another.
edit
UNIX Users
If you run MATLAB with the -nodisplay startup option, or run without the
DISPLAY environment variable set, edit uses the External Editor command.
It does not use the MATLAB Editor/Debugger, but instead uses the default
editor defined for your system in $matlabroot/X11/app-defaults/Matlab.
You can specify the editor that the edit function uses or specify editor options
by adding the following line to your own .Xdefaults file, located in ~home
matlab*externalEditorCommand: $EDITOR -option $FILE
where
• $EDITOR is the name of your default editor, for example, emacs; leaving it as
$EDITOR means your default system editor will be used.
• -option is a valid option flag you can include for the specified editor.
• $FILE means the filename you type with the edit command will open in the
specified editor.
For example,
emacs $FILE
means that when you type edit foo, the file foo will open in the emacs editor.
After adding the line to your .Xdefaults file, you must run the following before
starting MATLAB:
xrdb -merge ~home/.Xdefaults
For the HP 700 platform, the default editor is instead defined in
$matlabroot/toolbox/matlab/general/edit.m. To change it, open the file
edit.m and edit the line
eval( ['!$EDITOR “' file '" &']);
See Also
open, type
2-549
eig
Purpose
2eig
Find eigenvalues and eigenvectors
Syntax
d = eig(A)
d = eig(A,B)
[V,D] = eig(A)
[V,D] = eig(A,'nobalance')
[V,D] = eig(A,B)
[V,D] = eig(A,B,flag)
Description
d = eig(A) returns a vector of the eigenvalues of matrix A.
d = eig(A,B) returns a vector containing the generalized eigenvalues, if A and
B are square matrices.
Note If S is sparse and symmetric, you can use d = eig(S) to returns the
eigenvalues of S. To request eigenvectors, and in all other cases, use eigs to
find the eigenvalues or eigenvectors of sparse matrices.
[V,D] = eig(A) produces matrices of eigenvalues (D) and eigenvectors (V) of
matrix A, so that A*V = V*D. Matrix D is the canonical form of A—a diagonal
matrix with A’s eigenvalues on the main diagonal. Matrix V is the modal
matrix—its columns are the eigenvectors of A.
If W is a matrix such that W'*A = D*W', the columns of W are the left eigenvectors
of A . Use [W,D] = eig(A.'); W = conj(W) to compute the left eigenvectors.
[V,D] = eig(A,'nobalance') finds eigenvalues and eigenvectors without a
preliminary balancing step. Ordinarily, balancing improves the conditioning of
the input matrix, enabling more accurate computation of the eigenvectors and
eigenvalues. However, if a matrix contains small elements that are really due
to roundoff error, balancing may scale them up to make them as significant as
the other elements of the original matrix, leading to incorrect eigenvectors. Use
the nobalance option in this event. See the balance function for more details.
[V,D] = eig(A,B) produces a diagonal matrix D of generalized eigenvalues
and a full matrix V whose columns are the corresponding eigenvectors so that
A*V = B*V*D.
2-550
eig
[V,D] = eig(A,B,flag) specifies the algorithm used to compute eigenvalues
and eigenvectors. flag can be:
'chol'
Computes the generalized eigenvalues of A and B using the
Cholesky factorization of B. This is the default for symmetric
(Hermitian) A and symmetric (Hermitian) positive definite B.
'qz'
Ignores the symmetry, if any, and uses the QZ algorithm as it
would for nonsymmetric (non-Hermitian) A and B.
Note For eig(A), the eigenvectors are scaled so that the norm of each is 1.0.
For eig(A,B), eig(A,'nobalance'), and eig(A,B,flag), the eigenvectors are
not normalized.
Remarks
The eigenvalue problem is to determine the nontrivial solutions of the equation
Ax = λx
where A is an n-by-n matrix, x is a length n column vector, and λ is a scalar.
The n values of λ that satisfy the equation are the eigenvalues, and the
corresponding values of x are the right eigenvectors. In MATLAB, the function
eig solves for the eigenvalues λ , and optionally the eigenvectors x .
The generalized eigenvalue problem is to determine the nontrivial solutions of
the equation
Ax = λBx
where both A and B are n-by-n matrices and λ is a scalar. The values of λ that
satisfy the equation are the generalized eigenvalues and the corresponding
values of x are the generalized right eigenvectors.
If B is nonsingular, the problem could be solved by reducing it to a standard
eigenvalue problem
B – 1 Ax = λx
Because B can be singular, an alternative algorithm, called the QZ method, is
necessary.
2-551
eig
When a matrix has no repeated eigenvalues, the eigenvectors are always
independent and the eigenvector matrix V diagonalizes the original matrix A if
applied as a similarity transformation. However, if a matrix has repeated
eigenvalues, it is not similar to a diagonal matrix unless it has a full
(independent) set of eigenvectors. If the eigenvectors are not independent then
the original matrix is said to be defective. Even if a matrix is defective, the
solution from eig satisfies A*X = X*D.
Examples
The matrix
B = [ 3
-2
-2
4
-eps/4 eps/2
-.5
-.5
-.9
1
-1
.1
2*eps
-eps
0
1
];
has elements on the order of roundoff error. It is an example for which the
nobalance option is necessary to compute the eigenvectors correctly. Try the
statements
[VB,DB] = eig(B)
B*VB - VB*DB
[VN,DN] = eig(B,'nobalance')
B*VN - VN*DN
Algorithm
MATLAB uses LAPACK routines to compute eigenvalues and eigenvectors:
Case
Routine
Real symmetric A
DSYEV
Real nonsymmetric A:
2-552
• With preliminary balance step
DGEEV (with SCLFAC = 2 instead
of 8 in DGEBAL)
• d = eig(A,'nobalance')
DGEHRD, DHSEQR
• [V,D] = eig(A,'nobalance')
DGEHRD, DORGHR, DHSEQR, DTREVC
Hermitian A
ZHEEV
eig
Case
Routine
Non-Hermitian A:
• With preliminary balance step
ZGEEV (with SCLFAC = 2 instead
of 8 in ZGEBAL)
• d = eig(A,'nobalance')
ZGEHRD, ZHSEQR
• [V,D] = eig(A,'nobalance')
ZGEHRD, ZUNGHR, ZHSEQR, ZTREVC
Real symmetric A,
symmetric positive definite B.
Special case:
eig(A,B,'qz') for real A, B
(same as real nonsymmetric A, real
general B)
DSYGV
Real nonsymmetric A, real general B
DGGEV
Complex Hermitian A,
Hermitian positive definite B.
Special case:
eig(A,B,'qz') for complex A or B
(same as complex non-Hermitian A,
complex B)
ZHEGV
Complex non-Hermitian A, complex B
ZGGEV
DGGEV
ZGGEV
See Also
balance, condeig, eigs, hess, qz, schur
References
[1] Anderson, E., Z. Bai, C. Bischof, S. Blackford, J. Demmel, J. Dongarra,
J. Du Croz, A. Greenbaum, S. Hammarling, A. McKenney, and D. Sorensen,
LAPACK User’s Guide
(http://www.netlib.org/lapack/lug/lapack_lug.html), Third Edition,
SIAM, Philadelphia, 1999.
2-553
eigs
Purpose
2eigs
Find a few eigenvalues and eigenvectors of a square large sparse matrix
Syntax
d = eigs(A)
d = eigs(A,B)
d = eigs(A,k)
d = eigs(A,B,k)
d = eigs(A,k,sigma)
d = eigs(A,B,k,sigma)
d = eigs(A,k,sigma,options)
d = eigs(A,B,k,sigma,options)
d = eigs(Afun,n)
d = eigs(Afun,n,B)
d = eigs(Afun,n,k)
d = eigs(Afun,n,B,k)
d = eigs(Afun,n,k,sigma)
d = eigs(Afun,n,B,k,sigma)
d = eigs(Afun,n,k,sigma,options)
d = eigs(Afun,n,B,k,sigma,options)
d = eigs(Afun,n,k,sigma,options,p1,p2...)
d = eigs(Afun,n,B,k,sigma,options,p1,p2...)
[V,D] = eigs(A,...)
[V,D] = eigs(Afun,n,...)
[V,D,flag] = eigs(A,...)
[V,D,flag] = eigs(Afun,n,...)
Description
d = eigs(A) returns a vector of A's six largest magnitude eigenvalues.
[V,D] = eigs(A) returns a diagonal matrix D of A's six largest magnitude
eigenvalues and a matrix V whose columns are the corresponding eigenvectors.
[V,D,flag] = eigs(A) also returns a convergence flag. If flag is 0 then all
the eigenvalues converged; otherwise not all converged.
eigs(A,B) solves the generalized eigenvalue problem A*V == B*V*D. B must
be symmetric (or Hermitian) positive definite and the same size as A.
eigs(A,[],...) indicates the standard eigenvalue problem A*V == V*D.
eigs(A,k) and eigs(A,B,k) return the k largest magnitude eigenvalues.
2-554
eigs
eigs(A,k,sigma) and eigs(A,B,k,sigma) return k eigenvalues based on
sigma, which can take any of the following values:
scalar
The eigenvalues closest to sigma. If A is a function, Afun
(real or complex, must return Y = (A-sigma*B)\x (i.e., Y = A\x when
including 0)
sigma = 0). Note, B need only be symmetric (Hermitian)
positive semi-definite.
'lm'
Largest magnitude (default).
'sm'
Smallest magnitude. Same as sigma = 0. If A is a function,
Afun must return Y = A\x. Note, B need only be symmetric
(Hermitian) positive semi-definite.
For real symmetric problems, the following are also options:
'la'
Largest algebraic ('lr' in MATLAB 5)
'sa'
Smallest algebraic ('sr' in MATLAB 5)
'be'
Both ends (one more from high end if k is odd)
For nonsymmetric and complex problems, the following are also options:
'lr'
Largest real part
'sr'
Smallest real part
'li'
Largest imaginary part
'si'
Smallest imaginary part
Note The MATLAB 5 value sigma = 'be' is obsolete for nonsymmetric and
complex problems.
2-555
eigs
eigs(A,K,sigma,opts) and eigs(A,B,k,sigma,opts) specify an options
structure. Default values are shown in brackets ({}).
Parameter
Description
Values
options.issym
1 if A or A-sigma*B represented
by Afun is symmetric, 0
[{0} | 1]
otherwise.
options.isreal
1 if A or A-sigma*B represented
by Afun is real, 0 otherwise.
[0 | {1}]
options.tol
Convergence: Ritz estimate
residual <= tol*norm(A).
[scalar | {eps}]
options.maxit
Maximum number of iterations.
[integer | {300}]
options.p
Number of basis vectors. p >= 2k
(p >= 2k+1 real nonsymmetric)
advised. Note: p must satisfy
k < p <= n for real symmetric,
k+1 < p <= n otherwise.
[integer | 2*k]
options.v0
Starting vector.
Randomly
generated by
ARPACK
options.disp
Diagnostic information display
level.
[0 | {1} | 2]
options.cholB
1 if B is really its Cholesky factor
chol(B), 0 otherwise.
[{0} | 1]
options.permB
Permutation vector permB if
sparse B is really
chol(B(permB,permB)).
[permB | {1:n}]
Note MATLAB 5 options stagtol and cheb are no longer allowed.
2-556
eigs
eigs(Afun,n,...) accepts the function Afun instead of the matrix A.
y = Afun(x) should return:
A*x
if sigma is not specified, or is a string other than 'sm'
A\x
if sigma is 0 or 'sm'
(A-sigma*I)\x
if sigma is a nonzero scalar (standard eigenvalue
problem). I is an identity matrix of the same size as A.
(A-sigma*B)\x
if sigma is a nonzero scalar (generalized eigenvalue
problem)
n is the size of A. The matrix A, A-sigma*I or A-sigma*B represented by Afun is
assumed to be real and nonsymmetric unless specified otherwise by
opts.isreal and opts.issym. In all the eigs syntaxes, eigs(A,...) can be
replaced by eigs(Afun,n,...).
eigs(Afun,n,k,sigma,opts,p1,p2,...) and
eigs(Afun,n,B,k,sigma,opts,p1,p2,...) provide for additional arguments
which are passed to Afun(x,p1,p2,...).
Remarks
d = eigs(A,k) is not a substitute for
d = eig(full(A))
d = sort(d)
d = d(end-k+1:end)
but is most appropriate for large sparse matrices. If the problem fits into
memory, it may be quicker to use eig(full(A)).
Algorithm
eigs provides the reverse communication required by the Fortran library
ARPACK, namely the routines DSAUPD, DSEUPD, DNAUPD, DNEUPD, ZNAUPD, and
ZNEUPD.
Examples
Example 1: This example shows the use of function handles.
A = delsq(numgrid('C',15));
d1 = eigs(A,5,'sm');
Equivalently, if dnRk is the following one-line function:
function y = dnRk(x,R,k)
2-557
eigs
y = (delsq(numgrid(R,k))) \ x;
then pass dnRk's additional arguments, 'C' and 15, to eigs.
n = size(A,1);
opts.issym = 1;
d2 = eigs(@dnRk,n,5,'sm',opts,'C',15);
Example 2: west0479 is a real 479-by-479 sparse matrix with both real and
pairs of complex conjugate eigenvalues. eig computes all 479 eigenvalues. eigs
easily picks out the largest magnitude eigenvalues.
This plot shows the 8 largest magnitude eigenvalues of west0479 as computed
by eig and eigs.
load west0479
d = eig(full(west0479))
dlm = eigs(west0479,8)
[dum,ind] = sort(abs(d));
plot(dlm,'k+')
hold on
plot(d(ind(end-7:end)),'ks')
hold off
legend('eigs(west0479,8)','eig(full(west0479))')
2-558
eigs
2000
eigs(west0479,8)
eig(full(west0479))
1500
1000
500
0
−500
−1000
−1500
−2000
−150
−100
−50
0
50
100
150
Example 3: A = delsq(numgrid('C',30)) is a symmetric positive definite
matrix of size 632 with eigenvalues reasonably well-distributed in the interval
(0 8), but with 18 eigenvalues repeated at 4. The eig function computes all 632
eigenvalues. It computes and plots the six largest and smallest magnitude
eigenvalues of A successfully with:
A = delsq(numgrid('C',30));
d = eig(full(A));
[dum,ind] = sort(abs(d));
dlm = eigs(A);
dsm = eigs(A,6,'sm');
subplot(2,1,1)
plot(dlm,'k+')
hold on
plot(d(ind(end:-1:end-5)),'ks')
hold off
legend('eigs(A)','eig(full(A))',3)
set(gca,'XLim',[0.5 6.5])
2-559
eigs
subplot(2,1,2)
plot(dsm,'k+')
hold on
plot(d(ind(1:6)),'ks')
hold off
legend('eigs(A,6,''sm'')','eig(full(A))',2)
set(gca,'XLim',[0.5 6.5])
8
7.95
7.9
7.85
eigs(A)
eig(full(A))
7.8
1
2
3
4
5
6
2
3
4
5
6
0.2
eigs(A,6,’SM’)
eig(full(A))
0.15
0.1
0.05
0
1
However, the repeated eigenvalue at 4 must be handled more carefully. The
call eigs(A,18,4.0) to compute 18 eigenvalues near 4.0 tries to find
eigenvalues of A - 4.0*I. This involves divisions of the form
1/(lambda - 4.0), where lambda is an estimate of an eigenvalue of A. As
lambda gets closer to 4.0, eigs fails. We must use sigma near but not equal to
4 to find those 18 eigenvalues.
sigma = 4 - 1e-6
[V,D] = eigs(A,18,sigma)
2-560
eigs
The plot shows the 20 eigenvalues closest to 4 that were computed by eig,
along with the 18 eigenvalues closest to 4 - 1e-6 that were computed by eigs.
18 repeated eigenvalues of delsq(numgrid(’C’,30)) at 4
4.03
eigs(A,18,sigma)
eig(A)
4.02
4.01
4
3.99
3.98
3.97
2
4
6
8
10
12
14
16
18
20
See Also
arpackc, eig, svds
References
[1] Lehoucq, R.B. and D.C. Sorensen, “Deflation Techniques for an Implicitly
Re-Started Arnoldi Iteration,” SIAM J. Matrix Analysis and Applications, Vol.
17, 1996, pp. 789-821.
[2] Lehoucq, R.B., D.C. Sorensen, and C. Yang, ARPACK Users' Guide:
Solution of Large-Scale Eigenvalue Problems with Implicitly Restarted Arnoldi
Methods, SIAM Publications, Philadelphia, 1998.
[3] Sorensen, D.C., “Implicit Application of Polynomial Filters in a k-Step
Arnoldi Method,” SIAM J. Matrix Analysis and Applications, Vol. 13, 1992,
pp. 357-385.
2-561
ellipj
Purpose
2ellipj
Jacobi elliptic functions
Syntax
[SN,CN,DN]
[SN,CN,DN]
Definition
The Jacobi elliptic functions are defined in terms of the integral:
u =
φ
=
=
ellipj(U,M)
ellipj(U,M,tol)
dθ
∫0 -----------------------------------2
1
---
( 1 – m sin θ ) 2
Then
1
---
sn ( u ) = sin φ, cn ( u ) = cos φ, dn ( u ) = ( 1 – m sin2 φ ) 2, am ( u ) = φ
Some definitions of the elliptic functions use the modulus k instead of the
parameter m . They are related by
k 2 = m = sin2 α
The Jacobi elliptic functions obey many mathematical identities; for a good
sample, see [1].
Description
[SN,CN,DN] = ellipj(U,M) returns the Jacobi elliptic functions SN, CN, and
DN, evaluated for corresponding elements of argument U and parameter M.
Inputs U and M must be the same size (or either can be scalar).
[SN,CN,DN] = ellipj(U,M,tol) computes the Jacobi elliptic functions to
accuracy tol. The default is eps; increase this for a less accurate but more
quickly computed answer.
Algorithm
ellipj computes the Jacobi elliptic functions using the method of the
arithmetic-geometric mean [1]. It starts with the triplet of numbers:
1
--2
a 0 = 1, b 0 = ( 1 – m ) , c 0 = ( m )
2-562
1
--2
ellipj
ellipj computes successive iterates with
1
a i = --- ( a i – 1 + b i – 1 )
2
1
--bi = ( ai – 1 bi – 1 ) 2
1
c i = --- ( a i – 1 – b i – 1 )
2
Next, it calculates the amplitudes in radians using:
cn
sin ( 2φ n – 1 – φ n ) = ------ sin ( φ n )
an
being careful to unwrap the phases correctly. The Jacobian elliptic functions
are then simply:
sn ( u ) = sin φ 0
cn ( u ) = cos φ 0
2
1
---
dn ( u ) = ( 1 – m ⋅ sn ( u ) ) 2
Limitations
The ellipj function is limited to the input domain 0 ≤ m ≤ 1 . Map other values
of M into this range using the transformations described in [1], equations 16.10
and 16.11. U is limited to real values.
See Also
ellipke
References
[1] Abramowitz, M. and I.A. Stegun, Handbook of Mathematical Functions,
Dover Publications, 1965, 17.6.
2-563
ellipke
Purpose
2ellipke
Syntax
K = ellipke(M)
[K,E] = ellipke(M)
[K,E] = ellipke(M,tol)
Definition
The complete elliptic integral of the first kind [1] is
Complete elliptic integrals of the first and second kind
K (m) = F(π ⁄ 2 m)
where F , the elliptic integral of the first kind, is
K (m) =
1
∫0
–1
------
[ ( 1 – t 2 ) ( 1 – mt 2 ) ] 2 dt =
π
--2
∫0
–1
------
( 1 – m sin2 θ ) 2 dθ
The complete elliptic integral of the second kind
E ( m ) = E ( K ( m ) ) = E 〈π ⁄ 2|m〉
is
E(m) =
1
∫0
–1
------
1
---
( 1 – t 2 ) 2 ( 1 – mt 2 ) 2 dt =
π
--2
1
--2
∫0 ( 1 – m sin2 θ ) dθ
Some definitions of K and E use the modulus k instead of the parameter m .
They are related by
k 2 = m = sin2 α
Description
K = ellipke(M) returns the complete elliptic integral of the first kind for the
elements of M.
[K,E] = ellipke(M) returns the complete elliptic integral of the first and
second kinds.
[K,E] = ellipke(M,tol) computes the Jacobian elliptic functions to accuracy
tol. The default is eps; increase this for a less accurate but more quickly
computed answer.
2-564
ellipke
Algorithm
ellipke computes the complete elliptic integral using the method of the
arithmetic-geometric mean described in [1], section 17.6. It starts with the
triplet of numbers
1
---
1
---
a 0 = 1, b 0 = ( 1 – m ) 2, c 0 = ( m ) 2
ellipke computes successive iterations of a i , b i , and c i with
1
a i = --- ( a i – 1 + b i – 1 )
2
1
--bi = ( ai – 1 bi – 1 ) 2
1
c i = --- ( a i – 1 – b i – 1 )
2
stopping at iteration n when cn ≈ 0 , within the tolerance specified by eps. The
complete elliptic integral of the first kind is then
π
K ( m ) = ---------2a n
Limitations
ellipke is limited to the input domain 0 ≤ m ≤ 1 .
See Also
ellipj
References
[1] Abramowitz, M. and I.A. Stegun, Handbook of Mathematical Functions,
Dover Publications, 1965, 17.6.
2-565
ellipsoid
Purpose
2ellipsoid
Generate ellipsoid
Syntax
[x,y,z] = ellipsoid(xc,yc,zc,xr,yr,zr,n)
[x,y,z] = ellipsoid(xc,yc,zc,xr,yr,zr)
ellipsoid(...)
Description
[x,y,z] = ellipsoid(xc,yc,zc,xr,yr,zr,n) generates three n+1-by-n+1
matrices so that surf(x,y,z) produces an ellipsoid with center (xc,yc,zc)
and radii (xr,yr,zr).
[x,y,z] = ellipsoid(xc,yc,zc,xr,yr,zr) uses n = 20.
ellipsoid(...) with no output arguments graphs the ellipsoid as a surface.
Algorithm
ellipsoid generates the data using the following equation:
2
2
2
( x – xc )
( y – yc )
( z – zc )
----------------------- + ----------------------- + ---------------------2
2
2
xr
yr
zr
See Also
cylinder, sphere, surf
“Polygons and Surfaces” for related functions
2-566
else
Purpose
2else
Conditionally execute statements
Syntax
if expression
statements1
else
statements2
end
Description
else is used to delineate an alternate block of statements. If expression
evaluates as false, MATLAB executes the one or more commands denoted
here as statements2.
A true expression has either a logical true or nonzero value. For nonscalar
expressions, (for example, “if (matrix A is less than matrix B)”), true means
that every element of the resulting matrix has a logical true or nonzero value.
Expressions usually involve relational operations such as (count < limit) or
isreal(A). Simple expressions can be combined by logical operators (&,|,~) into
compound expressions such as: (count < limit) & ((height - offset) >=
0).
See if for more information.
Examples
In this example, if both of the conditions are not satisfied, then the student fails
the course.
if ((attendance >= 0.90) & (grade_average >= 60))
pass = 1;
else
fail = 1;
end;
See Also
if, elseif, end, for, while, switch, break, return, relational_operators,
logical_operators
2-567
elseif
Purpose
2elseif
Conditionally execute statements
Syntax
if expression1
statements1
elseif expression2
statements2
end
Description
If expression1 evaluates as false and expression2 as true, MATLAB
executes the one or more commands denoted here as statements2.
A true expression has either a logical true or nonzero value. For nonscalar
expressions, (for example, is matrix A less then matrix B), true means that
every element of the resulting matrix has a logical true or nonzero value.
Expressions usually involve relational operations such as (count < limit) or
isreal(A). Simple expressions can be combined by logical operators (&,|,~) into
compound expressions such as: (count < limit) & ((height - offset) >=
0).
See if for more information.
Remarks
else if, with a space between the else and the if, differs from elseif, with
no space. The former introduces a new, nested if, which must have a matching
end. The latter is used in a linear sequence of conditional statements with only
one terminating end.
The two segments shown below produce identical results. Exactly one of the
four assignments to x is executed, depending upon the values of the three
logical expressions, A, B, and C.
if A
x = a
else
if B
x = b
else
if C
x = c
else
x = d
2-568
if A
x = a
elseif B
x = b
elseif C
x = c
else
x = d
end
elseif
end
end
end
Examples
Here is an example showing if, else, and elseif.
for m = 1:k
for n = 1:k
if m == n
a(m,n) = 2;
elseif abs(m-n) == 2
a(m,n) = 1;
else
a(m,n) = 0;
end
end
end
For k=5 you get the matrix
a =
2
0
1
0
0
See Also
0
2
0
1
0
1
0
2
0
1
0
1
0
2
0
0
0
1
0
2
if, else, end, for, while, switch, break, return, relational_operators,
logical_operators
2-569
end
Purpose
Syntax
2end
Terminate for, while, switch, try, and if statements or indicate last index
while expression% (or if, for, or try)
statements
end
B = A(index:end,index)
Description
end is used to terminate for, while, switch, try, and if statements. Without
an end statement, for, while, switch, try, and if wait for further input. Each
end is paired with the closest previous unpaired for, while, switch, try, or if
and serves to delimit its scope.
The end command also serves as the last index in an indexing expression. In
that context, end = (size(x,k)) when used as part of the kth index. Examples
of this use are X(3:end) and X(1,1:2:end-1). When using end to grow an
array, as in X(end+1)=5, make sure X exists first.
You can overload the end statement for a user object by defining an end method
for the object. The end method should have the calling sequence end(obj,k,n),
where obj is the user object, k is the index in the expression where the end
syntax is used, and n is the total number of indices in the expression. For
example, consider the expression
A(end-1,:)
MATLAB will call the end method defined for A using the syntax
end(A,1,2)
Examples
This example shows end used with the for and if statements.
for k = 1:n
if a(k) == 0
a(k) = a(k) + 2;
end
end
In this example, end is used in an indexing expression.
A = magic(5)
2-570
end
A =
17
23
4
10
11
24
5
6
12
18
1
7
13
19
25
8
14
20
21
2
15
16
22
3
9
B = A(end,2:end)
B =
18
See Also
25
2
9
break, for, if, return, switch, try, while
2-571
eomday
Purpose
2eomday
End of month
Syntax
E = eomday(Y,M)
Description
E = eomday(Y,M) returns the last day of the year and month given by
corresponding elements of arrays Y and M.
Examples
Because 1996 is a leap year, the statement eomday(1996,2) returns 29.
To show all the leap years in this century, try:
y = 1900:1999;
E = eomday(y,2∗ones(length(y),1)');
y(find(E==29))'
ans =
Columns 1 through 6
1904
1908
See Also
2-572
1912
1916
1920
1924
Columns 7 through 12
1928
1932
1936
1940
1944
1948
Columns 13 through 18
1952
1956
1960
1964
1968
1972
Columns 19 through 24
1976
1980
1984
1988
1992
1996
datenum, datevec, weekday
eps
Purpose
2eps
Floating-point relative accuracy
Syntax
eps
Description
eps returns the distance from 1.0 to the next largest floating-point number.
The value eps is a default tolerance for pinv and rank, as well as several other
MATLAB functions. eps = 2^(-52), which is roughly 2.22e-16.
See Also
realmax, realmin
2-573
erf, erfc, erfcx, erfinv, erfcinv
Purpose
2erf, erfc, erfcx, erfinv, erfcinv
Error functions
Syntax
Y
Y
Y
X
X
Definition
The error function erf(X) is twice the integral of the Gaussian distribution
with 0 mean and variance of 1 ⁄ 2 .
=
=
=
=
=
Error function
Complementary error function
Scaled complementary error function
Inverse error function
Inverse complementary error function
erf(X)
erfc(X)
erfcx(X)
erfinv(Y)
erfcinv(Y)
2
π
erf ( x ) = -------
x
∫0 e –t dt
2
The complementary error function erfc(X) is defined as
2
π
erfc ( x ) = -------
∞
∫x e –t dt
2
= 1 – erf ( x )
The scaled complementary error function erfcx(X) is defined as
erfcx ( x ) = e x erfc ( x )
2
1 1
For large X, erfcx(X) is approximately  -------  -- πx
Description
Y = erf(X) returns the value of the error function for each element of real
array X.
Y = erfc(X) computes the value of the complementary error function.
Y = erfcx(X) computes the value of the scaled complementary error function.
X = erfinv(Y) returns the value of the inverse error function for each element
of Y. Elements of Y must be in the interval [-1 1]. The function erfinv
satisfies y = erf( x) for – 1 ≤ y ≤ 1 and – ∞ ≤ x ≤ ∞ .
X = erfcinv(Y) returns the value of the inverse of the complementary error
function for each element of Y. Elements of Y must be in the interval [0 2].
The function erfcinv satisfies y = erfc( x) for 2 ≥ y ≥ 0 and – ∞ ≤ x ≤ ∞ .
2-574
erf, erfc, erfcx, erfinv, erfcinv
Remarks
The relationship between the complementary error function erfc and the
standard normal probability distribution returned by the Statistics Toolbox
function normcdf is
normcdf ( x ) = 0.5 * erfc ( – x ⁄
2)
The relationship between the inverse complementary error function erfcinv
and the inverse standard normal probability distribution returned by the
Statistics Toolbox function norminv is
norminv ( p ) = – 2 * erfcinv ( 2 p )
Examples
erfinv(1) is Inf
erfinv(-1) is -Inf.
For abs(Y) > 1, erfinv(Y) is NaN.
Algorithms
For the error functions, the MATLAB code is a translation of a Fortran
program by W. J. Cody, Argonne National Laboratory, NETLIB/SPECFUN,
March 19, 1990. The main computation evaluates near-minimax rational
approximations from [1].
For the inverse of the error function, rational approximations accurate to
approximately six significant digits are used to generate an initial
approximation, which is then improved to full accuracy by one step of Halley’s
method.
References
[1] Cody, W. J., “Rational Chebyshev Approximations for the Error Function,”
Math. Comp., pgs. 631-638, 1969
2-575
error
Purpose
2error
Display error messages
Syntax
error('message')
error('message',a1,a2, ...)
error('message_id','message')
error('message_id','message',a1,a2,...)
Description
error('message') displays an error message and returns control to the
keyboard. The error message contains the input string message.
The error command has no effect if message is a null string.
error('message',a1,a2,...) displays a message string that contains
formatting conversion characters, such as those used with the MATLAB
sprintf function. Each conversion character in message is converted to one of
the values a1, a2, ... in the argument list.
Note MATLAB converts special characters (like \n and %d) in the error
message string only when you specify more than one input argument with
error. See Example 3 below.
error('message_id','message') attaches a unique message identifier, or
message_id, to the error message. The identifier enables you to better identify
the source of an error. See “Message Identifiers” and “Using Message
Identifiers with lasterr” in the MATLAB documentation for more information
on the message_id argument and how to use it.
error('message_id','message',a1,a2, ...) includes formatting
conversion characters in message, and the character translations a1, a2, ...
Examples
Example 1
The error function provides an error return from M-files:
function foo(x,y)
if nargin ~= 2
error('Wrong number of input arguments')
end
2-576
error
The returned error message looks like this:
foo(pi)
??? Error using ==> foo
Wrong number of input arguments
Example 2
Specify a message identifier and error message string with error:
error('MyToolbox:angleTooLarge', ...
'The angle specified must be less than 90 degrees.');
In your error handling code, use lasterr to determine the message identifier
and error message string for the failing operation:
[errmsg, msgid] = lasterr
errmsg =
The angle specified must be less than 90 degrees.
msgid =
MyToolbox:angleTooLarge
Example 3
MATLAB converts special characters (like \n and %d) in the error message
string only when you specify more than one input argument with error. In the
single argument case shown below, \n is taken to mean backslash-n. It is not
converted to a newline character:
error('In this case, the newline \n is not converted.')
??? In this case, the newline \n is not converted.
But, when more than one argument is specified, MATLAB does convert special
characters. This holds true regardless of whether the additional argument
supplies conversion values or is a message identifier:
error('ErrorTests:convertTest', ...
'In this case, the newline \n is converted.')
??? In this case, the newline
is converted.
See Also
lasterr, lasterror, rethrow, errordlg, warning, lastwarn, warndlg, dbstop,
disp, sprintf
2-577
errorbar
Purpose
2errorbar
Plot error bars along a curve
Syntax
errorbar(Y,E)
errorbar(X,Y,E)
errorbar(X,Y,L,U)
errorbar(...,LineSpec)
h = errorbar(...)
Description
Error bars show the confidence level of data or the deviation along a curve.
errorbar(Y,E) plots Y and draws an error bar at each element of Y. The error
bar is a distance of E(i) above and below the curve so that each bar is
symmetric and 2*E(i) long.
errorbar(X,Y,E) plots X versus Y with symmetric error bars 2*E(i) long. X, Y,
E must be the same size. When they are vectors, each error bar is a distance of
E(i) above and below the point defined by (X(i),Y(i)). When they are
matrices, each error bar is a distance of E(i,j) above and below the point
defined by (X(i,j),Y(i,j)).
errorbar(X,Y,L,U) plots X versus Y with error bars L(i)+U(i) long specifying
the lower and upper error bars. X, Y, L, and U must be the same size. When they
are vectors, each error bar is a distance of L(i) below and U(i) above the point
defined by (X(i),Y(i)). When they are matrices, each error bar is a distance
of L(i,j) below and U(i,j) above the point defined by (X(i,j),Y(i,j)).
errorbar(...,LineSpec) draws the error bars using the line type, marker
symbol, and color specified by LineSpec.
h = errorbar(...) returns a vector of handles to line graphics objects.
Remarks
When the arguments are all matrices, errorbar draws one line per matrix
column. If X and Y are vectors, they specify one curve.
Examples
Draw symmetric error bars that are two standard deviation units in length.
X = 0:pi/10:pi;
Y = sin(X);
E = std(Y)*ones(size(X));
2-578
errorbar
errorbar(X,Y,E)
1.4
1.2
1
0.8
0.6
0.4
0.2
0
−0.2
−0.4
−0.5
See Also
0
0.5
1
1.5
2
2.5
3
3.5
LineSpec, plot, std
“Basic Plots and Graphs” for related functions
2-579
errordlg
Purpose
2errordlg
Create and display an error dialog box
Syntax
errordlg
errordlg('errorstring')
errordlg('errorstring','dlgname')
errordlg('errorstring','dlgname','on')
h = errordlg(...)
Description
errordlg creates an error dialog box, or if the named dialog exists, errordlg
pops the named dialog in front of other windows.
errordlg displays a dialog box named 'Error Dialog' that contains the string
'This is the default error string.'
errordlg('errorstring') displays a dialog box named 'Error Dialog' that
contains the string 'errorstring'.
errordlg('errorstring','dlgname') displays a dialog box named 'dlgname'
that contains the string 'errorstring'.
errordlg('errorstring','dlgname','on') specifies whether to replace an
existing dialog box having the same name. 'on' brings an existing error dialog
having the same name to the foreground. In this case, errordlg does not create
a new dialog.
h = errordlg(...) returns the handle of the dialog box.
Remarks
MATLAB sizes the dialog box to fit the string 'errorstring'. The error dialog
box has an OK pushbutton and remains on the screen until you press the OK
button or the Return key. After pressing the button, the error dialog box
disappears.
The appearance of the dialog box depends on the windowing system you use.
Examples
The function
errordlg('File not found','File Error');
2-580
errordlg
displays this dialog box:
See Also
dialog, helpdlg, msgbox, questdlg, warndlg
“Predefined Dialog Boxes” for related functions
2-581
etime
Purpose
2etime
Elapsed time
Syntax
e = etime(t2,t1)
Description
e = etime(t2,t1) returns the time in seconds between vectors t1 and t2. The
two vectors must be six elements long, in the format returned by clock:
T = [Year Month Day Hour Minute Second]
Examples
Calculate how long a 2048-point real FFT takes.
x = rand(2048,1);
t = clock; fft(x); etime(clock,t)
ans =
0.4167
Limitations
As currently implemented, the etime function fails across month and year
boundaries. Since etime is an M-file, you can modify the code to work across
these boundaries if needed.
See Also
clock, cputime, tic, toc
2-582
etree
Purpose
2etree
Elimination tree
Syntax
p = etree(A)
p = etree(A,'col')
p = etree(A,'sym')
[p,q] = etree(...)
Description
p = etree(A) returns an elimination tree for the square symmetric matrix
whose upper triangle is that of A. p(j) is the parent of column j in the tree, or
0 if j is a root.
p = etree(A,'col') returns the elimination tree of A'*A.
p = etree(A,'sym') is the same as p = etree(A).
[p,q] = etree(...) also returns a postorder permutation q of the tree.
See Also
treelayout, treeplot, etreeplot
2-583
etreeplot
Purpose
2etreeplot
Plot elimination tree
Syntax
etreeplot(A)
etreeplot(A,nodeSpec,edgeSpec)
Description
etreeplot(A) plots the elimination tree of A (or A+A', if non-symmetric).
etreeplot(A,nodeSpec,edgeSpec) allows optional parameters nodeSpec and
edgeSpec to set the node or edge color, marker, and linestyle. Use '' to omit
one or both.
See Also
2-584
etree, treeplot, treelayout
eval
Purpose
2eval
Execute a string containing a MATLAB expression
Syntax
eval(expression)
eval(expression,catch_expr)
[a1,a2,a3,...] = eval(function(b1,b2,b3,...))
Description
eval(expression) executes expression, a string containing any valid
MATLAB expression. You can construct expression by concatenating
substrings and variables inside square brackets:
expression = [string1,int2str(var),string2,...]
eval(expression,catch_expr) executes expression and, if an error is
detected, executes the catch_expr string. If expression produces an error, the
error string can be obtained with the lasterr function. This syntax is useful
when expression is a string that must be constructed from substrings. If this
is not the case, use the try...catch control flow statement in your code.
[a1,a2,a3,...] = eval(function(b1,b2,b3,...)) executes function with
arguments b1,b2,b3,..., and returns the results in the specified output
variables.
Remarks
Examples
Using the eval output argument list is recommended over including the output
arguments in the expression string. The first syntax below avoids strict
checking by the MATLAB parser and can produce untrapped errors and other
unexpected behavior.
eval('[a1,a2,a3,...] = function(var)')
% not recommended
[a1,a2,a3,...] = eval('function(var)')
% recommended syntax
This for loop generates a sequence of 12 matrices named M1 through M12:
for n = 1:12
magic_str = ['M',int2str(n),' = magic(n)'];
eval(magic_str)
end
2-585
eval
This example uses a function showdemo that runs a MATLAB demo selected by
the user. If an error is encountered, a message is displayed that names the
demo that failed.
function showdemo(demos)
errstring = 'Error running demo: ';
n = input('Select a demo number: ');
eval(demos(n,:),'[errstring demos(n,:)]')
% ----- end of file showdemo.m ----D = ['odedemo'; 'quademo'; 'fitdemo'];
showdemo(D)
Select a demo number: 2
ans =
Error running demo: quademo
The next example executes the size function on a 3-dimensional array,
returning the array dimensions in output variables d1, d2, and d3.
A = magic(4);
A(:,:,2) = A';
[d1,d2,d3] = eval('size(A)')
d1 =
4
d2 =
4
d3 =
2
See Also
2-586
assignin, catch, evalin, feval, lasterr, try
evalc
Purpose
2evalc
Evaluate MATLAB expression with capture
Syntax
T = evalc(S)
T = evalc(s1,s2)
[T,X,Y,Z,...] = evalc(S)
Description
T = evalc(S) is the same as eval(S) except that anything that would normally
be written to the command window is captured and returned in the character
array T (lines in T are separated by \n characters).
T = evalc(s1,s2) is the same as eval(s1,s2) except that any output is
captured into T.
[T,X,Y,Z,...] = evalc(S) is the same as [X,Y,Z,...] = eval(S) except
that any output is captured into T.
Remark
When you are using evalc, diary, more, and input are disabled.
See Also
diary, eval, evalin, input, more
2-587
evalin
Purpose
2evalin
Syntax
evalin(ws,expression)
[a1,a2,a3,...] = evalin(ws,expression)
evalin(ws,expression,catch_expr)
Description
evalin(ws,expression) executes expression, a string containing any valid
MATLAB expression, in the context of the workspace ws. ws can have a value
of 'base' or 'caller' to denote the MATLAB base workspace or the workspace
of the caller function. You can construct expression by concatenating
Execute a string containing a MATLAB expression in a workspace
substrings and variables inside square brackets:
expression = [string1,int2str(var),string2,...]
[a1,a2,a3,...] = evalin(ws,expression) executes expression and
returns the results in the specified output variables. Using the evalin output
argument list is recommended over including the output arguments in the
expression string:
evalin(ws,'[a1,a2,a3,...] = function(var)')
The above syntax avoids strict checking by the MATLAB parser and can
produce untrapped errors and other unexpected behavior.
evalin(ws,expression,catch_expr) executes expression and, if an error is
detected, executes the catch_expr string. If expression produces an error, the
error string can be obtained with the lasterr function. This syntax is useful
when expression is a string that must be constructed from substrings. If this
is not the case, use the try...catch control flow statement in your code.
Remarks
The MATLAB base workspace is the workspace that is seen from the MATLAB
command line (when not in the debugger). The caller workspace is the
workspace of the function that called the M-file. Note, the base and caller
workspaces are equivalent in the context of an M-file that is invoked from the
MATLAB command line.
Examples
This example extracts the value of the variable var in the MATLAB base
workspace and captures the value in the local variable v:
v = evalin('base','var');
2-588
evalin
Limitation
evalin cannot be used recursively to evaluate an expression. For example, a
sequence of the form evalin('caller','evalin(''caller'',''x'')')
doesn’t work.
See Also
assignin, catch, eval, feval, lasterr, try
2-589
eventlisteners (COM)
Purpose
2eventlisteners (COM)
Return a list of events attached to listeners
Syntax
eventlisteners(h)
Arguments
h
Handle for a MATLAB COM control object.
Description
eventlisteners lists any events, along with their callback or event handler
routines, that have been registered with control, h. The function returns a cell
array of strings, with each row containing the name of a registered event and
the handler routine for that event. If the control has no registered events, then
eventlisteners returns an empty cell array.
Events and their callback or event handler routines must be registered in order
for the control to respond to them. You can register events either when you
create the control, using actxcontrol, or at any time afterwards, using
registerevent.
Examples
Create an mwsamp control, registering only the Click event. eventlisteners
returns the name of the event and its event handler routine, myclick:
f = figure('pos', [100 200 200 200]);
h = actxcontrol('mwsamp.mwsampctrl.2', [0 0 200 200], f, ...
{'Click' 'myclick'});
eventlisteners(h)
ans =
'click'
'myclick'
Register two more events: DblClick and MouseDown. eventlisteners returns
the names of the three registered events along with their respective handler
routines:
registerevent(h, {'DblClick', 'my2click'; ...
'MouseDown' 'mymoused'});
eventlisteners(h)
ans =
'click'
'dblclick'
2-590
'myclick'
'my2click'
eventlisteners (COM)
'mousedown'
'mymoused'
Now unregister all events for the control, and eventlisteners returns an
empty cell array, indicating that no events have been registered for the control:
unregisterallevents(h)
eventlisteners(h)
ans =
{}
See Also
events, registerevent, unregisterevent, unregisterallevents, isevent
2-591
events (COM)
Purpose
2events (COM)
Return a list of events that the control can trigger
Syntax
events(h)
Arguments
h
Handle for a MATLAB COM control object.
Description
Returns a structure array containing all events, both registered and
unregistered, known to the control, and the function prototype used when
calling the event handler routine. For each array element, the structure field
is the event name and the contents of that field is the function prototype for
that event’s handler.
Note The send function is identical to events, but send will be made obsolete
in a future release.
Examples
Create an mwsamp control and list all events:
f = figure ('pos', [100 200 200 200]);
h = actxcontrol ('mwsamp.mwsampctrl.2', [0 0 200 200], f);
events(h)
Click = void Click()
DblClick = void DblClick()
MouseDown = void MouseDown(int16 Button, int16 Shift,
Variant x, Variant y)
Or assign the output to a variable and get one field of the returned structure:
ev = events(h);
ev.MouseDown
ans =
void MouseDown(int16 Button, int16 Shift, Variant x, Variant y)
See Also
2-592
isevent, eventlisteners, registerevent, unregisterevent,
unregisterallevents
events (COM)
In the following example, exist returns 8 on the Java class, Welcome, and
returns 2 on the Java class file, Welcome.class.
exist Welcome
ans =
8
exist javaclasses/Welcome.class
ans =
2
indicates there is a Java class Welcome and a Java class file Welcome.class.
The following example indicates that testresults is both a variable in the
workspace and a directory on the search path:
exist('testresults','var')
ans =
1
exist('testresults','dir')
ans =
7
See Also
dir, help, lookfor, partialpath, what, which, who
2-593
exist
Purpose
2exist
Graphical
Interface
As an alternative to the exist function, use the Workspace browser or the
Current Directory Browser.
Syntax
exist item
exist item kind
a = exist('item',...)
Description
exist item returns the status of the variable or file, item:
Check if a variable or file exists
0
If item does not exist.
1
If the variable item exists in the workspace.
2
If item is an M-file or a file of unknown type.
3
If item is a MEX-file on your MATLAB search path.
4
If item is an MDL-file on your MATLAB search path.
5
If item is a built-in MATLAB function.
6
If item is a P-file on your MATLAB search path.
7
If item is a directory.
8
If item is a Java class.
If item specifies a filename, that filename may include an extension to
preclude conflicting with other similar filenames. For example,
exist('file.ext').
MEX, MDL, and P-files must be on the MATLAB search path for exist to
return the values shown above. If item is found, but is not on the MATLAB
search path, exist('item') returns 2, because it considers item to be an
unknown file type.
Any other file type or directory specified by item is not required to be on the
MATLAB search path to be recognized by exist. If the file or directory is not
on the search path, then item must specify either a full pathname, a partial
pathname relative to MATLABPATH, or a partial pathname relative to your
current directory.
2-594
exist
If item is a Java class, then exist('item') returns an 8. However, if item is a
Java class file, then exist('item') returns a 2.
exist item kind returns the status of item for the specified kind. If item of
type kind does not exist, it returns 0. The kind argument may be one of the
following:
builtin
Checks only for built-in functions.
class
Checks only for Java classes.
dir
Checks only for directories.
file
Checks only for files or directories.
var
Checks only for variables.
a = exist('item',...) returns the status of the variable or file in variable a.
Remarks
To check for the existence of more than one variable, use the ismember
function. For example,
a = 5.83;
c = 'teststring';
ismember({'a','b','c'},who)
ans =
1
Examples
0
1
This example uses exist to check whether a MATLAB function is a built-in
function or a file:
type = exist('plot')
type =
5
This indicates that plot is a built-in function.
2-595
exit
Purpose
2exit
Graphical
Interface
As an alternative to the exit function, select Exit MATLAB from the File
menu or click the close box in the MATLAB desktop.
Syntax
exit
Description
exit ends the current MATLAB session. It is the same as quit. See quit for
termination options.
See Also
finish, quit
2-596
Terminate MATLAB (same as quit)
exp
Purpose
2exp
Exponential
Syntax
Y = exp(X)
Description
The exp function is an elementary function that operates element-wise on
arrays. Its domain includes complex numbers.
Y = exp(X) returns the exponential for each element of X. For complex
z = x + i* y , it returns the complex exponential e z = e x ( cos ( y ) + i sin ( y ) ) .
Remark
Use expm for matrix exponentials.
See Also
expm, log, log10, expint
2-597
expint
Purpose
2expint
Exponential integral
Syntax
Y = expint(X)
Definitions
The exponential integral computed by this function is defined as
E 1( x) =
∞
∫x
e –t
------- dt
t
Another common definition of the exponential integral function is the Cauchy
principal value integral
Ei ( x ) =
x
et
∫ ---- dt
–∞ t
which, for real positive x, is related to expint as
E 1 ( – x ) = – Ei ( x ) – iπ
Description
Y = expint(X) evaluates the exponential integral for each element of X.
References
[1] Abramowitz, M. and I. A. Stegun. Handbook of Mathematical Functions.
Chapter 5, New York: Dover Publications, 1965.
2-598
expm
Purpose
2expm
Matrix exponential
Syntax
Y = expm(X)
Description
Y = expm(X) raises the constant e to the matrix power X. The expm function
produces complex results if X has nonpositive eigenvalues.
Use exp for the element-by-element exponential.
Algorithm
expm is a built-in function that uses the Padé approximation with scaling and
squaring. You can see the coding of this algorithm in the expm1 demo.
Note The expm1, expm2, and expm3 demos illustrate the use of Padé
approximation, Taylor series approximation, and eigenvalues and
eigenvectors, respectively, to compute the matrix exponential.
References [1] and [2] describe and compare many algorithms for computing a
matrix exponential. The built-in method, expm, is essentially method 3 of [2].
Examples
This example computes and compares the matrix exponential of A and the
exponential of A.
A = [1
0
0
expm(A)
ans =
2.7183
0
0
exp(A)
ans =
2.7183
1.0000
1.0000
1
0
0
0
2
-1 ];
1.7183
1.0000
0
2.7183
1.0000
1.0000
1.0862
1.2642
0.3679
1.0000
7.3891
0.3679
2-599
expm
Notice that the diagonal elements of the two results are equal. This would be
true for any triangular matrix. But the off-diagonal elements, including those
below the diagonal, are different.
See Also
exp, funm, logm, sqrtm
References
[1] Golub, G. H. and C. F. Van Loan, Matrix Computation, p. 384, Johns
Hopkins University Press, 1983.
[2] Moler, C. B. and C. F. Van Loan, “Nineteen Dubious Ways to Compute the
Exponential of a Matrix,” SIAM Review 20, 1979, pp. 801-836.
2-600
eye
Purpose
2eye
Identity matrix
Syntax
Y
Y
Y
=
=
=
eye(n)
eye(m,n)
eye(size(A))
Description
Y
=
eye(n) returns the n-by-n identity matrix.
= eye(m,n) or eye([m n]) returns an m-by-n matrix with 1’s on the
diagonal and 0’s elsewhere.
Y
Y
=
eye(size(A)) returns an identity matrix the same size as A.
Limitations
The identity matrix is not defined for higher-dimensional arrays. The
assignment y = eye([2,3,4]) results in an error.
See Also
ones, rand, randn, zeros
2-601
ezcontour
Purpose
2ezcontour
Easy to use contour plotter
Syntax
ezcontour(f)
ezcontour(f,domain)
ezcontour(...,n)
Description
ezcontour(f) plots the contour lines of f(x,y), where f is a string that
represents a mathematical function of two variables, such as x and y.
The function f is plotted over the default domain: -2π < x < 2π, -2π < y < 2π.
MATLAB chooses the computational grid according to the amount of variation
that occurs; if the function f is not defined (singular) for points on the grid, then
these points are not plotted.
ezcontour(f,domain) plots f(x,y) over the specified domain. domain can be
either a 4-by-1 vector [xmin, xmax, ymin, ymax] or a 2-by-1 vector [min, max]
(where min < x < max, min < y < max).
If f is a function of the variables u and v (rather than x and y), then the domain
endpoints umin, umax, vmin, and vmax are sorted alphabetically. Thus,
ezcontour('u^2 - v^3',[0,1],[3,6]) plots the contour lines for u2 - v3 over
0 < u < 1, 3 < v < 6.
ezcontour(...,n) plots f over the default domain using an n-by-n grid. The
default value for n is 60.
ezcontour automatically adds a title and axis labels.
Remarks
Array multiplication, division, and exponentiation are always implied in the
expression you pass to ezcontour. For example, the MATLAB syntax for a
contour plot of the expression,
sqrt(x.^2 + y.^2)
is written as:
ezcontour('sqrt(x^2 + y^2)')
That is, x^2 is interpreted as x.^2 in the string you pass to ezcontour.
Examples
2-602
The following mathematical expression defines a function of two variables, x
and y.
ezcontour
1
x
2
2
2
2
– 10  --- – x 3 – y 5 e – x – y – --- e – ( x + 1 ) – y
5

3
ezcontour requires a string argument that expresses this function using
MATLAB syntax to represent exponents, natural logs, etc. This function is
represented by the string:
f ( x, y ) = 3 ( 1 – x ) 2 e – x
2
– ( y + 1 )2
f = ['3*(1−x)^2*exp(−(x^2)−(y+1)^2)',...
'− 10*(x/5 − x^3 − y^5)*exp(-x^2−y^2)',...
'- 1/3*exp(−(x+1)^2 − y^2)'];
For convenience, this string is written on three lines and concatenated into one
string using square brackets.
Pass the string variable f to ezcontour along with a domain ranging from −3
to 3 and specify a computational grid of 49-by-49:
ezcontour(f,[-3,3],49)
3 (1−x)2 exp(−(x2) − (y+1)2)− ~~~ x2−y2)− 1/3 exp(−(x+1)2 − y2)
3
2
y
1
0
−1
−2
−3
−3
−2
−1
0
x
1
2
3
In this particular case, the title is too long to fit at the top of the graph so
MATLAB abbreviates the string.
2-603
ezcontour
See Also
contour, ezcontourf, ezmesh, ezmeshc, ezplot, ezplot3, ezpolar, ezsurf,
ezsurfc
“Contour Plots” for related functions
2-604
ezcontourf
Purpose
2ezcontourf
Easy to use filled contour plotter
Syntax
ezcontourf(f)
ezcontourf(f,domain)
ezcontourf(...,n)
Description
ezcontourf(f) plots the contour lines of f(x,y), where f is a string that
represents a mathematical function of two variables, such as x and y.
The function f is plotted over the default domain: -2π < x < 2π, -2π < y < 2π.
MATLAB chooses the computational grid according to the amount of variation
that occurs; if the function f is not defined (singular) for points on the grid, then
these points are not plotted.
ezcontourf(f,domain) plots f(x,y) over the specified domain. domain can be
either a 4-by-1 vector [xmin, xmax, ymin, ymax] or a 2-by-1 vector [min, max]
(where, min < x < max, min < y < max).
If f is a function of the variables u and v (rather than x and y), then the domain
endpoints umin, umax, vmin, and vmax are sorted alphabetically. Thus,
ezcontourf('u^2 - v^3',[0,1],[3,6]) plots the contour lines for u2 - v3 over
0 < u < 1, 3 < v < 6.
ezcontourf(...,n) plots f over the default domain using an n-by-n grid. The
default value for n is 60.
ezcontourf automatically adds a title and axis labels.
Remarks
Array multiplication, division, and exponentiation are always implied in the
expression you pass to ezcontourf. For example, the MATLAB syntax for a
filled contour plot of the expression,
sqrt(x.^2 + y.^2);
is written as:
ezcontourf('sqrt(x^2 + y^2)')
That is, x^2 is interpreted as x.^2 in the string you pass to ezcontourf.
Examples
The following mathematical expression defines a function of two variables, x
and y.
2-605
ezcontourf
1
x
2
2
2
2
– 10  --- – x 3 – y 5 e – x – y – --- e – ( x + 1 ) – y
5

3
ezcontourf requires a string argument that expresses this function using
MATLAB syntax to represent exponents, natural logs, etc. This function is
represented by the string:
f ( x, y ) = 3 ( 1 – x ) 2 e – x
2
– ( y + 1 )2
f = ['3*(1−x)^2*exp(−(x^2)−(y+1)^2)',...
'− 10*(x/5 − x^3 − y^5)*exp(-x^2−y^2)',...
'- 1/3*exp(−(x+1)^2 − y^2)'];
For convenience, this string is written on three lines and concatenated into one
string using square brackets.
Pass the string variable f to ezcontourf along with a domain ranging from −3
to 3 and specify a grid of 49-by-49:
ezcontourf(f,[-3,3],49)
3 (1−x)2 exp(−(x2) − (y+1)2)− ~~~ x2−y2)− 1/3 exp(−(x+1)2 − y2)
3
2
y
1
0
−1
−2
−3
−3
−2
−1
0
x
1
2
3
In this particular case, the title is too long to fit at the top of the graph so
MATLAB abbreviates the string.
2-606
ezcontourf
See Also
contourf, ezcontour, ezmesh, ezmeshc, ezplot, ezplot3, ezpolar, ezsurf,
ezsurfc
“Contour Plots” for related functions
2-607
ezmesh
Purpose
2ezmesh
Easy to use 3-D mesh plotter
Syntax
ezmesh(f)
ezmesh(f,domain)
ezmesh(x,y,z)
ezmesh(x,y,z,[smin,smax,tmin,tmax]) or ezmesh(x,y,z,[min,max])
ezmesh(...,n)
ezmesh(...,'circ')
Description
ezmesh(f) creates a graph of f(x,y), where f is a string that represents a
mathematical function of two variables, such as x and y.
The function f is plotted over the default domain: -2π < x < 2π, -2π < y < 2π.
MATLAB chooses the computational grid according to the amount of variation
that occurs; if the function f is not defined (singular) for points on the grid, then
these points are not plotted.
ezmesh(f,domain) plots f over the specified domain. domain can be either a
4-by-1 vector [xmin, xmax, ymin, ymax] or a 2-by-1 vector [min, max] (where,
min < x < max, min < y < max).
If f is a function of the variables u and v (rather than x and y), then the domain
endpoints umin, umax, vmin, and vmax are sorted alphabetically. Thus,
ezmesh('u^2 - v^3',[0,1],[3,6]) plots u2 - v3 over 0 < u < 1, 3 < v < 6.
ezmesh(x,y,z) plots the parametric surface x = x(s,t), y = y(s,t), and z = z(s,t)
over the square: -2π < s < 2π, -2π < t < 2π.
ezmesh(x,y,z,[smin,smax,tmin,tmax]) or ezmesh(x,y,z,[min,max]) plots
the parametric surface using the specified domain.
ezmesh(...,n) plots f over the default domain using an n-by-n grid. The
default value for n is 60.
ezmesh(...,'circ') plots f over a disk centered on the domain.
Remarks
Array multiplication, division, and exponentiation are always implied in the
expression you pass to ezmesh. For example, the MATLAB syntax for a mesh
plot of the expression,
sqrt(x.^2 + y.^2);
2-608
ezmesh
is written as:
ezmesh('sqrt(x^2 + y^2)')
That is, x^2 is interpreted as x.^2 in the string you pass to ezmesh.
Examples
This example visualizes the function,
f ( x, y ) = xe
2
–x – y
2
with a mesh plot drawn on a 40-by-40 grid. The mesh lines are set to a uniform
blue color by setting the colormap to a single color:
ezmesh('x*exp(-x^2-y^2)',40)
colormap([0 0 1])
x exp(−x2 − y2)
0.5
0
−0.5
2
1
2
0
0
−1
y
See Also
−2
−2
x
ezmeshc, mesh
“Function Plots” for related functions
2-609
ezmeshc
Purpose
2ezmeshc
Easy to use combination mesh/contour plotter
Syntax
ezmeshc(f)
ezmeshc(f,domain)
ezmeshc(x,y,z)
ezmeshc(x,y,z,[smin,smax,tmin,tmax]) or ezmeshc(x,y,z,[min,max])
ezmeshc(...,n)
ezmeshc(...,'circ')
Description
ezmeshc(f) creates a graph of f(x,y), where f is a string that represents a
mathematical function of two variables, such as x and y.
The function f is plotted over the default domain: -2π < x < 2π, -2π < y < 2π.
MATLAB chooses the computational grid according to the amount of variation
that occurs; if the function f is not defined (singular) for points on the grid, then
these points are not plotted.
ezmeshc(f,domain) plots f over the specified domain. domain can be either a
4-by-1 vector [xmin, xmax, ymin, ymax] or a 2-by-1 vector [min, max] (where,
min < x < max, min < y < max).
If f is a function of the variables u and v (rather than x and y), then the domain
endpoints umin, umax, vmin, and vmax are sorted alphabetically. Thus,
ezmeshc('u^2 - v^3',[0,1],[3,6]) plots u2 - v3 over 0 < u < 1, 3 < v < 6.
ezmeshc(x,y,z) plots the parametric surface x = x(s,t), y = y(s,t), and z = z(s,t)
over the square: -2π < s < 2π, -2π < t < 2π.
ezmeshc(x,y,z,[smin,smax,tmin,tmax]) or ezmeshc(x,y,z,[min,max])
plots the parametric surface using the specified domain.
ezmeshc(...,n) plots f over the default domain using an n-by-n grid. The
default value for n is 60.
ezmeshc(...,'circ') plots f over a disk centered on the domain.
Remarks
Array multiplication, division, and exponentiation are always implied in the
expression you pass to ezmeshc. For example, the MATLAB syntax for a
mesh/contour plot of the expression,
sqrt(x.^2 + y.^2);
2-610
ezmeshc
is written as:
ezmeshc('sqrt(x^2 + y^2)')
That is, x^2 is interpreted as x.^2 in the string you pass to ezmeshc.
Examples
Create a mesh/contour graph of the expression,
y
f ( x, y ) = ---------------------------2
2
1+x + y
over the domain -5 < x < 5, -2*pi < y < 2*pi:
ezmeshc('y/(1 + x^2 + y^2)',[−5,5,−2*pi,2*pi])
Use the mouse to rotate the axes to better observe the contour lines (this
picture uses a view of azimuth = -65.5 and elevation = 26).
y/(1 + x2 + y2)
0.5
0
5
−0.5
0
5
0
−5
y
See Also
−5
x
ezmesh, ezsurfc, meshc
“Function Plots” for related functions
2-611
ezplot
Purpose
2ezplot
Easy to use function plotter
Syntax
ezplot(f)
ezplot(f,[min,max])
ezplot(f,[xmin,xmax,ymin,ymax])
ezplot(x,y)
ezplot(x,y,[tmin,tmax])
ezplot(...,figure)
Description
ezplot(f) plots the expression f = f(x) over the default domain: -2π < x < 2π.
ezplot(f,[min,max]) plots f = f(x) over the domain: min < x < max.
For implicitly defined functions, f = f(x,y):
ezplot(f) plots f(x,y) = 0 over the default domain -2π < x < 2π, -2π < y < 2π.
ezplot(f,[xmin,xmax,ymin,ymax]) plots f(x,y) = 0 over xmin < x < xmax and
ymin < y < ymax.
ezplot(f,[min,max])plots f(x,y) = 0 over min < x < max and min < y < max.
If f is a function of the variables u and v (rather than x and y), then the domain
endpoints umin, umax, vmin, and vmax are sorted alphabetically. Thus,
ezplot('u^2 - v^2 - 1',[-3,2,-2,3]) plots u2 - v2 - 1 = 0 over -3 < u < 2, -2
< v < 3.
ezplot(x,y) plots the parametrically defined planar curve x = x(t) and y = y(t)
over the default domain 0 < t < 2π.
ezplot(x,y,[tmin,tmax]) plots x = x(t) and y = y(t) over tmin < t < tmax.
ezplot(...,figure) plots the given function over the specified domain in the
figure window identified by the handle figure.
Remarks
Array multiplication, division, and exponentiation are always implied in the
expression you pass to ezplot. For example, the MATLAB syntax for a plot of
the expression,
x.^2 - y.^2
which represents an implicitly defined function, is written as:
ezplot('x^2 - y^2')
2-612
ezplot
That is, x^2 is interpreted as x.^2 in the string you pass to ezplot.
Examples
This example plots the implicitly defined function,
x2 - y4 = 0
over the domain [-2π, 2π]:
ezplot('x^2-y^4')
x2−y4 = 0
6
4
y
2
0
−2
−4
−6
−6
See Also
−4
−2
0
x
2
4
6
ezplot3, ezpolar, plot
“Function Plots” for related functions
2-613
ezplot3
Purpose
2ezplot3
Easy to use 3-D parametric curve plotter
Syntax
ezplot3(x,y,z)
ezplot3(x,y,z,[tmin,tmax])
ezplot3(...,'animate')
Description
ezplot3(x,y,z) plots the spatial curve x = x(t), y = y(t), and z = z(t) over the
default domain 0 < t < 2π.
ezplot3(x,y,z,[tmin,tmax]) plots the curve x = x(t), y = y(t), and z = z(t) over
the domain tmin < t < tmax.
ezplot3(...,'animate') produces an animated trace of the spatial curve.
Remarks
Array multiplication, division, and exponentiation are always implied in the
expression you pass to ezplot3. For example, the MATLAB syntax for a plot of
the expression,
x = s./2, y = 2.*s, z = s.^2;
which represents a parametric function, is written as:
ezplot3('s/2','2*s','s^2')
That is, s/2 is interpreted as s./2 in the string you pass to ezplot3.
Examples
This example plots the parametric curve,
x = sin t ,
y = cos t ,
z=t
over the domain [0,6π]:
ezplot3('sin(t)','cos(t)','t',[0,6*pi])
2-614
ezplot3
x = sin(t), y = cos(t), z = t
20
z
15
10
5
0
1
1
0.5
0.5
0
0
−0.5
y
See Also
−0.5
−1
−1
x
ezplot, ezpolar, plot3
“Function Plots” for related functions
2-615
ezpolar
Purpose
2ezpolar
Easy to use polar coordinate plotter
Syntax
ezpolar(f)
ezpolar(f,[a,b])
Description
ezpolar(f) plots the polar curve rho = f(theta) over the default domain 0 <
theta < 2π.
ezpolar(f,[a,b]) plots f for a < theta < b.
Examples
This example creates a polar plot of the function,
1 + cos(t)
over the domain [0, 2π]:
ezpolar('1+cos(t)')
90
2
120
60
1.5
150
30
1
0.5
180
0
330
210
240
300
270
r = 1+cos(t)
See Also
2-616
ezplot, ezplot3, plot, plot3, polar
ezpolar
“Function Plots” for related functions
2-617
ezsurf
Purpose
2ezsurf
Easy to use 3-D colored surface plotter
Syntax
ezsurf(f)
ezsurf(f,domain)
ezsurf(x,y,z)
ezsurf(x,y,z,[smin,smax,tmin,tmax]) or ezsurf(x,y,z,[min,max])
ezsurf(...,n)
ezsurf(...,'circ')
Description
ezsurf(f) creates a graph of f(x,y), where f is a string that represents a
mathematical function of two variables, such as x and y.
The function f is plotted over the default domain: -2π < x < 2π, -2π < y < 2π.
MATLAB chooses the computational grid according to the amount of variation
that occurs; if the function f is not defined (singular) for points on the grid, then
these points are not plotted.
ezsurf(f,domain) plots f over the specified domain. domain can be either a
4-by-1 vector [xmin, xmax, ymin, ymax] or a 2-by-1 vector [min, max] (where,
min < x < max, min < y < max).
If f is a function of the variables u and v (rather than x and y), then the domain
endpoints umin, umax, vmin, and vmax are sorted alphabetically. Thus,
ezsurf('u^2 - v^3',[0,1],[3,6]) plots u2 - v3 over 0 < u < 1, 3 < v < 6.
ezsurf(x,y,z) plots the parametric surface x = x(s,t), y = y(s,t), and z = z(s,t)
over the square: -2π < s < 2π, -2π < t < 2π.
ezsurf(x,y,z,[smin,smax,tmin,tmax]) or ezsurf(x,y,z,[min,max]) plots
the parametric surface using the specified domain.
ezsurf(...,n) plots f over the default domain using an n-by-n grid. The
default value for n is 60.
ezsurf(...,'circ') plots f over a disk centered on the domain.
Remarks
Array multiplication, division, and exponentiation are always implied in the
expression you pass to ezsurf. For example, the MATLAB syntax for a surface
plot of the expression,
sqrt(x.^2 + y.^2);
2-618
ezsurf
is written as:
ezsurf('sqrt(x^2 + y^2)')
That is, x^2 is interpreted as x.^2 in the string you pass to ezsurf.
Examples
ezsurf does not graph points where the mathematical function is not defined
(these data points are set to NaNs, which MATLAB does not plot). This example
illustrates this filtering of singularities/discontinuous points by graphing the
function,
f ( x, y) = real ( atan ( x + iy ) )
over the default domain -2π < x < 2π, -2π < y < 2π:
ezsurf('real(atan(x+i*y))')
real(atan(x+i y))
2
1
0
−1
−2
5
5
0
y
0
−5
−5
x
Using surf to plot the same data produces a graph without filtering of
discontinuities (as well as requiring more steps):
[x,y] = meshgrid(linspace(-2*pi,2*pi,60));
z = real(atan(x+i.*y));
2-619
ezsurf
surf(x,y,z)
2
1
0
−1
−2
10
5
10
5
0
0
−5
−5
−10
−10
Note also that ezsurf creates graphs that have axis labels, a title, and extend
to the axis limits.
See Also
ezmesh, ezsurfc, surf
“Function Plots” for related functions
2-620
ezsurfc
Purpose
2ezsurfc
Easy to use combination surface/contour plotter
Syntax
ezsurfc(f)
ezsurfc(f,domain)
ezsurfc(x,y,z)
ezsurfc(x,y,z,[smin,smax,tmin,tmax]) or ezsurfc(x,y,z,[min,max])
ezsurfc(...,n)
ezsurfc(...,'circ')
Description
ezsurfc(f) creates a graph of f(x,y), where f is a string that represents a
mathematical function of two variables, such as x and y.
The function f is plotted over the default domain: -2π < x < 2π, -2π < y < 2π.
MATLAB chooses the computational grid according to the amount of variation
that occurs; if the function f is not defined (singular) for points on the grid, then
these points are not plotted.
ezsurfc(f,domain) plots f over the specified domain. domain can be either a
4-by-1 vector [xmin, xmax, ymin, ymax] or a 2-by-1 vector [min, max] (where,
min < x < max, min < y < max).
If f is a function of the variables u and v (rather than x and y), then the domain
endpoints umin, umax, vmin, and vmax are sorted alphabetically. Thus,
ezsurfc('u^2 - v^3',[0,1],[3,6]) plots u2 - v3 over 0 < u < 1, 3 < v < 6.
ezsurfc(x,y,z) plots the parametric surface x = x(s,t), y = y(s,t), and z = z(s,t)
over the square: -2π < s < 2π, -2π < t < 2π.
ezsurfc(x,y,z,[smin,smax,tmin,tmax]) or ezsurfc(x,y,z,[min,max])
plots the parametric surface using the specified domain.
ezsurfc(...,n) plots f over the default domain using an n-by-n grid. The
default value for n is 60.
ezsurfc(...,'circ') plots f over a disk centered on the domain.
Remarks
Array multiplication, division, and exponentiation are always implied in the
expression you pass to ezsurfc. For example, the MATLAB syntax for a
surface/contour plot of the experssion,
sqrt(x.^2 + y.^2);
2-621
ezsurfc
is written as:
ezsurfc('sqrt(x^2 + y^2)')
That is, x^2 is interpreted as x.^2 in the string you pass to ezsurfc.
Examples
Create a surface/contour plot of the expression,
y
f ( x, y ) = ---------------------------2
2
1+x + y
over the domain -5 < x < 5, -2*pi < y < 2*pi, with a computational grid of size
35-by-35:
ezsurfc('y/(1 + x^2 + y^2)',[−5,5,−2*pi,2*pi],35)
Use the mouse to rotate the axes to better observe the contour lines (this
picture uses a view of azimuth = -65.5 and elevation = 26)
y/(1 + x2 + y2)
0.5
0
5
−0.5
0
5
0
−5
y
See Also
2-622
ezmesh, ezmeshc, ezsurf, surfc
−5
x
ezsurfc
“Function Plots” for related functions
2-623
ezsurfc
2-624
Index
Symbols
! 2-24
- 2-11
% 2-24
& 2-20, 2-22
&& 2-22
' 2-11, 2-24
( ) 2-24
* 2-11
+ 2-11
, 2-24
. 2-24
... 2-24
/ 2-11
: 2-27
< 2-19
= 2-24
== 2-19
> 2-19
\ 2-11
^ 2-11
{} 2-24
| 2-20, 2-22
|| 2-22
~ 2-20, 2-22
~= 2-19
A
abs 2-29
absolute value 2-29
accuracy
of linear equation solution 2-357
of matrix inversion 2-357
relative floating-point 2-573
acos 2-30
acosh 2-32
acot 2-34
acoth 2-36
acsc 2-38
acsch 2-40
actxcontrol 2-42
actxserver 2-46
addframe
AVI files 2-48
addition (arithmetic operator) 2-11
addpath 2-50
addproperty 2-52
addressing selected array elements 2-27
adjacency graph 2-535
airy 2-53
Airy functions
relationship to modified Bessel functions 2-53
ALim, Axes property 2-117
all 2-56
AmbientLightColor, Axes property 2-117
and (M-file function equivalent for &) 2-21
AND, logical
bit-wise 2-190
angle 2-64
ans 2-65
any 2-66
arccosecant 2-38
arccosine 2-30
arccotangent 2-34
arcsecant 2-70
arcsine 2-74
arctangent 2-80
four-quadrant 2-82
area 2-68
arithmetic operations, matrix and array
distinguished 2-11
arithmetic operators
I-1
Index
reference 2-11
array
addressing selected elements of 2-27
displaying 2-525
left division (arithmetic operator) 2-12
multiplication (arithmetic operator) 2-11
power (arithmetic operator) 2-12
right division (arithmetic operator) 2-12
shift circularly 2-297
transpose (arithmetic operator) 2-12
arrays
maximum size of 2-356
arrowhead matrix 2-348
ASCII
delimited files
writing 2-534
ASCII data
printable characters (list of) 2-278
reading 2-533
auwrite 2-98
asec 2-70
bar3 2-151
asech 2-72
bar3h 2-151
asin 2-74
barh 2-147
asinh 2-76
assignin 2-78
base to decimal conversion 2-155
base two operations
conversion from decimal to binary 2-481
atan 2-80
base2dec 2-155
atan2 2-82
beep 2-156
Bessel functions
first kind 2-167
modified, first kind 2-161
modified, second kind 2-164
second kind 2-170
Bessel functions, modified
relationship to Airy functions 2-53
Bessel’s equation
(defined) 2-167
modified (defined) 2-161
aspect ratio of axes 2-428
atanh 2-84
.au files
reading 2-97
writing 2-98
audio
saving in AVI format 2-99
audio devices 2-86
audiodevinfo 2-86
audioplayer 2-88
audiorecorder 2-92
I-2
avi 2-99
avifile 2-99
aviinfo 2-102
aviread 2-104
Axes
creating 2-105
defining default properties 2-109
fixed-width font 2-126
property descriptions 2-117
axes
setting and querying data aspect ratio 2-428
axes 2-105
axis 2-138
B
balance 2-144
bar 2-147
Index
besseli 2-161
Box, Axes property 2-118
besselj 2-167
besselk 2-164
braces, curly (special characters) 2-24
brackets (special characters) 2-24
bessely 2-170
break 2-201
beta 2-173
betainc 2-175
breakpoints
listing 2-451
removing 2-442
resuming execution from 2-444
setting in M-files 2-453
brighten 2-202
betaln 2-176
builtin 2-204
bicg 2-177
BusyAction
beta function
(defined) 2-173
incomplete (defined) 2-175
natural logarithm 2-176
Axes property 2-118
bicgstab 2-184
BiConjugate Gradients method 2-177
BiConjugate Gradients Stabilized method 2-184
ButtonDownFcn
bin2dec 2-189
Axes property 2-118
bvp4c 2-205
binary to decimal conversion 2-189
bvpget 2-212
bitand 2-190
bvpinit 2-213
bitcmp 2-191
bvpset 2-215
bitget 2-192
bvpval 2-218
bitmax 2-193
bitor 2-194
bitset 2-195
C
bitshift 2-196
calendar 2-219
bit-wise operations
AND 2-190
get 2-192
OR 2-194
set bit 2-195
shift 2-196
XOR 2-197
camdolly 2-220
camera
dollying position 2-220
moving camera and target postions 2-220
placing a light at 2-222
positioning to view objects 2-224
rotating around camera target 2-226, 2-228
rotating around viewing axis 2-232
setting and querying position 2-229
setting and querying projection type 2-231
setting and querying target 2-233
setting and querying up vector 2-235
setting and querying view angle 2-237
bitxor 2-197
blanks
removing trailing 2-479
blanks 2-198
blkdiag 2-199
box 2-200
I-3
Index
CameraPosition, Axes property 2-119
cell2mat 2-266
CameraTarget, Axes property 2-119
cell2struct 2-268
CameraTargetMode, Axes property 2-119
celldisp 2-269
CameraUpVector, Axes property 2-119
cellfun 2-270
CameraUpVectorMode, Axes property 2-119
cellplot 2-272
CameraViewAngle, Axes property 2-120
cgs 2-274
CameraViewAngleMode, Axes property 2-120
char 2-278
camlight 2-222
checkin 2-280
camlookat 2-224
camproj 2-231
examples 2-281
options 2-280
checkout 2-282
examples 2-283
options 2-282
camroll 2-232
Children
camorbit 2-226
campan 2-228
campos 2-229
camtarget 2-233
Axes property 2-121
camup 2-235
chol 2-285
camva 2-237
capture 2-240
Cholesky factorization 2-285
(as algorithm for solving linear equations) 2-15
preordering for 2-348
cart2pol 2-241
cholinc 2-287
cart2sph 2-242
cholupdate 2-294
Cartesian coordinates 2-241, 2-242
circshift 2-297
case 2-243
cla 2-298
cat 2-244
clabel 2-299
catch 2-245
class 2-301
caxis 2-246
clc 2-303, 2-309
cd 2-250
clear 2-304
cdf2rdf 2-251
clear
cdfepoch 2-253
serial port I/O 2-308
clearing
Command Window 2-303
items from workspace 2-304
Java import list 2-305
clf 2-309
CLim, Axes property 2-121
CLimMode, Axes property 2-121
camzoom 2-239
cdfinfo 2-254
cdfread 2-258
cdfwrite 2-260
ceil 2-263
cell 2-264
cell array
creating 2-264
I-4
structure of, displaying 2-272
CameraPositionMode, Axes property 2-119
Index
AVI files 2-314
closest point search 2-546
cmapeditor 2-330
cmopts 2-316
complementary error function
(defined) 2-574
scaled (defined) 2-574
complete elliptic integral
(defined) 2-564
modulus of 2-562, 2-564
complex
exponential (defined) 2-597
phase angle 2-64
colamd 2-317
complex 2-354
colmmd 2-319
complex conjugate 2-365
sorting pairs of 2-407
complex data
creating 2-354
complex numbers, magnitude 2-29
computer 2-356
computer MATLAB is running on 2-356
concatenating arrays 2-244
clipboard 2-310
Clipping
Axes property 2-121
clock 2-311
close 2-312
Color
Axes property 2-122
colorbar 2-322
colormap
editor 2-330
colormap 2-326
ColorOrder, Axes property 2-122
ColorSpec 2-346
cond 2-357
colperm 2-348
condeig 2-358
COM
object methods
condest 2-359
actxserver 2-46
condition number of matrix 2-357
improving 2-144
coneplot 2-360
addproperty 2-52
conj 2-365
delete 2-499
conjugate, complex 2-365
sorting pairs of 2-407
continuation (..., special characters) 2-25
continue 2-366
contour
and mesh plot 2-610
filled plot 2-605
functions 2-602
of mathematical expression 2-602
with surface plot 2-621
contour 2-367
contour3 2-371
actxcontrol 2-42
deleteproperty 2-503
eventlisteners 2-590
events 2-592
comet 2-349
comet3 2-350
comma (special characters) 2-26
Command Window
clearing 2-303
compan 2-351
companion matrix 2-351
compass 2-352
I-5
Index
contourc 2-373
contourf 2-375
contours
in slice planes 2-377
contourslice 2-377
contrast 2-380
conv 2-381
conv2 2-382
conversion
base to decimal 2-155
binary to decimal 2-189
Cartesian to cylindrical 2-241
Cartesian to polar 2-241
complex diagonal to real block diagonal 2-251
decimal number to base 2-477, 2-480
decimal to binary 2-481
decimal to hexadecimal 2-482
string matrix to cell array 2-273
vector to character string 2-278
convex hulls
multidimensional vizualization 2-388
two-dimensional vizualization 2-386
cosh 2-400
cosine 2-398
hyperbolic 2-400
inverse 2-30
inverse hyperbolic 2-32
cot 2-402
cotangent 2-402
hyperbolic 2-404
inverse 2-34
inverse hyperbolic 2-36
coth 2-404
cov 2-406
cplxpair 2-407
cputime 2-408
CreateFcn
Axes property 2-122
cross 2-409
cross product 2-409
convhull 2-386
csc 2-410
convhulln 2-388
csch 2-412
convn 2-390
csvread 2-414
convolution 2-381
inverse See deconvolution
two-dimensional 2-382
coordinates
Cartesian 2-241, 2-242
cylindrical 2-241, 2-242
polar 2-241, 2-242
coordinates.See also conversion
copyfile 2-391
copyobj 2-393
csvwrite 2-416
corrcoef 2-395
cos 2-398
I-6
cosecant
hyperbolic 2-412
inverse 2-38
inverse hyperbolic 2-40
ctranspose (M-file function equivalent for ') 2-13
cumprod 2-417
cumsum 2-418
cumtrapz 2-419
cumulative
product 2-417
sum 2-418
curl 2-421
curly braces (special characters) 2-24
current directory
changing 2-250
Index
CurrentPoint
ddeget 2-466
Axes property 2-123
customverctrl 2-424
cylinder 2-425
cylindrical coordinates 2-241, 2-242
ddeinit 2-467
ddepoke 2-468
ddereq 2-470
ddeset 2-472
ddeterm 2-475
ddeunadv 2-476
D
deal 2-477
daspect 2-428
deblank 2-479
data aspect ratio of axes 2-428
data types
complex 2-354
DataAspectRatio, Axes property 2-123
DataAspectRatioMode, Axes property 2-125
datenum 2-432
debugging
changing workspace context 2-445
changing workspace to calling M-file 2-458
displaying function call stack 2-450
MEX-files on UNIX 2-448
quitting debug mode 2-449
removing breakpoints 2-442
resuming execution from breakpoint 2-452
setting breakpoints in 2-453
stepping through lines 2-452
dec2base 2-477, 2-480
datestr 2-434
dec2bin 2-481
datevec 2-440
dec2hex 2-482
dbclear 2-442
dbstack 2-450
decimal number to base conversion 2-477, 2-480
decimal point (.)
(special characters) 2-25
to distinguish matrix and array operations
2-11
decomposition
Dulmage-Mendelsohn 2-535
dbstatus 2-451
deconv 2-483
dbstep 2-452
dbtype 2-457
deconvolution 2-483
default tolerance 2-573
del operator 2-484
dbup 2-458
del2 2-484
dde23 2-459
delaunay 2-487
ddeadv 2-463
Delaunay tessellation
3-dimensional vizualization 2-492
date 2-431
date and time functions 2-572
date string
format of 2-434
date vector 2-440
dbcont 2-444
dbdown 2-445
dblquad 2-446
dbmex 2-448
dbquit 2-449
dbstop 2-453
ddeexec 2-465
I-7
Index
multidimensional vizualization 2-495
Delaunay triangulation
vizualization 2-487
delaunay3 2-492
delaunayn 2-495
delete 2-498, 2-499
delete
serial port I/O 2-501
timer object 2-502
DeleteFcn
Axes property 2-125
deleteproperty 2-503
deleting
files 2-498
items from workspace 2-304
delimiters in ASCII files 2-533, 2-534
demo 2-504
depdir 2-507
depfun 2-508
derivative
approximate 2-521
det 2-512
determinant of a matrix 2-512
detrend 2-513
deval 2-515
diag 2-517
diagonal 2-517
main 2-517
dialog 2-519
dialog box
error 2-580
diary 2-520
diff 2-521
differences
between adjacent array elements 2-521
differential equation solvers
ODE boundary value problems 2-205
I-8
adjusting parameters 2-215
extracting properties 2-212
extracting properties of 2-583, 2-584
forming initial guess 2-213
dir 2-523
directories
adding to search path 2-50
checking existence of 2-594
copying 2-391
listing contents of 2-523
See also directory, search path
directory
See also directories
directory, changing 2-250
discontinuities, plotting functions with 2-619
disp 2-525
disp
serial port I/O 2-526
timer object 2-527
display 2-529
distribution
Gaussian 2-574
division
array, left (arithmetic operator) 2-12
array, right (arithmetic operator) 2-12
matrix, left (arithmetic operator) 2-12
matrix, right (arithmetic operator) 2-11
of polynomials 2-483
dlmread 2-533
dlmwrite 2-534
dmperm 2-535
docroot 2-538
documentation
location of files for UNIX 2-537
documentation location 2-538
dolly camera 2-220
dos 2-539
Index
dot 2-541
dot product 2-409, 2-541
double 2-542
double integral
numerical evaluation 2-446
dragrect 2-543
DrawMode, Axes property 2-125
drawnow 2-544
elliptic functions, Jacobian
(defined) 2-562
elliptic integral
complete (defined) 2-564
modulus of 2-562, 2-564
else 2-567
elseif 2-568
end 2-570
dsearch 2-545
end of line, indicating 2-26
dsearchn 2-546
eomday 2-572
Dulmage-Mendelsohn decomposition 2-535
eps 2-573
E
equal sign (special characters) 2-25
equations, linear
accuracy of solution 2-357
echo 2-547
erf 2-574
edge finding, Sobel technique 2-383
editing
M-files 2-548
erfc 2-574
eig 2-550
erfinv 2-574
eigensystem
transforming 2-251
eigenvalue
accuracy of 2-550
complex 2-251
of companion matrix 2-351
problem 2-551
problem, generalized 2-551
repeated 2-552
eigenvalues
effect of roundoff error 2-144
improving accuracy 2-144
eigenvector
left 2-551
right 2-551
error 2-576
eigs 2-554
eventlisteners 2-590
ellipj 2-562
events 2-592
ellipke 2-564
examples
erfcinv 2-574
erfcx 2-574
error function
(defined) 2-574
complementary 2-574
scaled complementary 2-574
error message
displaying 2-576
errorbar 2-578
errordlg 2-580
etime 2-582
etree 2-583
etreeplot 2-584
eval 2-585
evalc 2-587
evalin 2-588
I-9
Index
contouring mathematical expressions 2-602
mesh plot of mathematical function 2-609
mesh/contour plot 2-611
plotting filled contours 2-605
plotting function of two variables 2-613
plotting parametric curves 2-614
polar plot of function 2-616
surface plot of mathematical function 2-619
surface/contour plot 2-622
exclamation point (special characters) 2-26
execution
resuming from breakpoint 2-444
exist 2-594
exit 2-596
exp 2-597
expint 2-598
expm 2-599
exponential 2-597
complex (defined) 2-597
integral 2-598
matrix 2-599
exponentiation
array (arithmetic operator) 2-12
matrix (arithmetic operator) 2-12
eye 2-601
ezcontour 2-602
ezcontourf 2-605
ezmesh 2-608
ezmeshc 2-610
ezplot 2-612
ezplot3 2-614
ezpolar 2-616
ezsurf 2-618
ezsurfc 2-621
F
factorization, Cholesky 2-285
(as algorithm for solving linear equations) 2-15
preordering for 2-348
Figures
updating from M-file 2-544
files
ASCII delimited
reading 2-533
writing 2-534
checking existence of 2-594
copying 2-391
deleting 2-498
listing
names in a directory 2-523
sound
reading 2-97
writing 2-98, 2-99
filter
two-dimensional 2-382
fixed-width font
axes 2-126
flint See floating-point, integer
floating-point
integer 2-191, 2-195
integer, maximum 2-193
numbers, interval between 2-573
flow control
break 2-201
case 2-243
end 2-570
error 2-576
font
fixed-width, axes 2-126
FontAngle
Axes property 2-125
FontName
I-10
Index
Axes property 2-126
FontSize
Axes property 2-126
FontUnits
Help browser
accessing from doc 2-536
help files 2-538
HitTest
Axes property 2-126
Axes property 2-128
FontWeight
horzcat (M-file function equivalent for [,]) 2-26
Axes property 2-127
Fourier transform
convolution theorem and 2-381
functions
call stack for 2-450
checking existence of 2-594
clearing from workspace 2-304
Householder reflections (as algorithm for solving
linear equations) 2-16
hyperbolic
cosecant 2-412
cosecant, inverse 2-40
cosine 2-400
cosine, inverse 2-32
cotangent 2-404
cotangent, inverse 2-36
secant, inverse 2-72
sine, inverse 2-76
tangent, inverse 2-84
G
Gaussian distribution function 2-574
Gaussian elimination
(as algorithm for solving linear equations)
2-16
generalized eigenvalue problem 2-551
generating a sequence of matrix names (M1
through M12) 2-585
global variables, clearing from workspace 2-304
graph
adjacency 2-535
graphics objects
Axes 2-105
graphics objects, deleting 2-498
GridLineStyle, Axes property 2-127
H
HandleVisibility
Axes property 2-127
help
files, location for UNIX 2-537
I
identity matrix 2-601
incomplete beta function
(defined) 2-175
inheritance, of objects 2-302
integer
floating-point 2-191, 2-195
floating-point, maximum 2-193
Interruptible
Axes property 2-128
inverse
cosecant 2-38
cosine 2-30
cotangent 2-34
hyperbolic cosecant 2-40
hyperbolic cosine 2-32
hyperbolic cotangent 2-36
I-11
Index
hyperbolic secant 2-72
hyperbolic sine 2-76
hyperbolic tangent 2-84
secant 2-70
sine 2-74
tangent 2-80
tangent, four-quadrant 2-82
inversion, matrix
accuracy of 2-357
J
Jacobian elliptic functions
(defined) 2-562
Java
class names 2-305
Java import list
clearing 2-305
joining arrays See concatenating arrays
L
labeling
matrix columns 2-525
Laplacian 2-484
Layer, Axes property 2-128
ldivide (M-file function equivalent for .\) 2-13
Light
positioning in camera coordinates 2-222
line numbers in M-files 2-457
linear equation systems
accuracy of solution 2-357
linear equation systems, methods for solving
Cholesky factorization 2-15
Gaussian elimination 2-16
Householder reflections 2-16
LineStyleOrder
I-12
Axes property 2-129
LineWidth
Axes property 2-129
Lobatto IIIa ODE solver 2-211
log
saving session to file 2-520
logarithm
of beta function (natural) 2-176
logical operations
AND, bit-wise 2-190
OR, bit-wise 2-194
XOR, bit-wise 2-197
logical operators 2-20, 2-22
logical tests
all 2-56
any 2-66
M
matrix
addressing selected rows and columns of 2-27
arrowhead 2-348
companion 2-351
condition number of 2-357
condition number, improving 2-144
converting to vector 2-27
defective (defined) 2-552
determinant of 2-512
diagonal of 2-517
Dulmage-Mendelsohn decomposition 2-535
exponential 2-599
identity 2-601
inversion, accuracy of 2-357
left division (arithmetic operator) 2-12
maximum size of 2-356
modal 2-550
multiplication (defined) 2-11
Index
power (arithmetic operator) 2-12
reading files into 2-533
right division (arithmetic operator) 2-11
singularity, test for 2-512
trace of 2-517
transpose (arithmetic operator) 2-12
transposing 2-25
writing to ASCII delimited file 2-534
See also array
matrix names, (M1 through M12) generating a
sequence of 2-585
matrix power See matrix, exponential
maximum matching 2-535
MDL-files
checking existence of 2-594
memory
clearing 2-304
methods
inheritance of 2-302
MEX-files
clearing from workspace 2-304
debugging on UNIX 2-448
M-file
displaying during execution 2-547
function file, echoing 2-547
script file, echoing 2-547
M-files
checking existence of 2-594
clearing from workspace 2-304
deleting 2-498
editing 2-548
line numbers, listing 2-457
setting breakpoints 2-453
MinorGridLineStyle, Axes property 2-129
minus (M-file function equivalent for -) 2-13
mldivide (M-file function equivalent for \) 2-13
modal matrix 2-550
modified Bessel functions
relationship to Airy functions 2-53
modifying for PVCS 2-316
movies
exporting in AVI format 2-99
mpower (M-file function equivalent for ^) 2-13
mrdivide (M-file function equivalent for /) 2-13
mtimes (M-file function equivalent for *) 2-13
multidimensional arrays
concatenating 2-244
multiplication
array (arithmetic operator) 2-11
matrix (defined) 2-11
of polynomials 2-381
N
NextPlot
Axes property 2-130
not (M-file function equivalent for ~) 2-21
numerical evaluation
double integral 2-446
O
object
inheritance 2-302
object classes, list of predefined 2-301
online help
location of files for UNIX 2-537
operating system command, issuing 2-26
operators
arithmetic 2-11
logical 2-20, 2-22
relational 2-19
special characters 2-24
logical OR
I-13
Index
bit-wise 2-194
or (M-file function equivalent for |) 2-21
orthographic projection, setting and querying
2-231
P
parametric curve, plotting 2-614
Parent
Axes property 2-130
parentheses (special characters) 2-25
path
adding directories to 2-50
pauses, removing 2-442
percent sign (special characters) 2-26
perfect matching 2-535
period (.), to distinguish matrix and array
operations 2-11
period (special characters) 2-25
perspective projection, setting and querying
2-231
P-files
checking existence of 2-594
phase angle, complex 2-64
platform MATLAB is running on 2-356
PlotBoxAspectRatio, Axes property 2-130
PlotBoxAspectRatioMode, Axes property 2-130
plotting
contours (a 2-602
contours (ez function) 2-602
errorbars 2-578
ez-function mesh plot 2-608
filled contours 2-605
functions with discontinuities 2-619
in polar coordinates 2-616
mathematical function 2-612
mesh contour plot 2-610
I-14
parametric curve 2-614
surfaces 2-618
velocity vectors 2-360
plus (M-file function equivalent for +) 2-13
polar coordinates
computing the angle 2-64
converting from Cartesian 2-241
plotting in 2-616
polynomial
division 2-483
multiplication 2-381
poorly conditioned eigenvalues 2-144
Position
Axes property 2-131
position of camera
dollying 2-220
position of camera, setting and querying 2-229
power
matrix See matrix exponential
power (M-file function equivalent for .^) 2-13
printing, suppressing 2-26
product
cumulative 2-417
of vectors (cross) 2-409
scalar (dot) 2-409
projection type, setting and querying 2-231
ProjectionType, Axes property 2-131
R
rdivide (M-file function equivalent for ./) 2-13
rearranging arrays
converting to vector 2-27
rearranging matrices
converting to vector 2-27
transposing 2-25
reference page
Index
accessing from doc 2-536
regularly spaced vectors, creating 2-27
relational operators 2-19
relative accuracy
floating-point 2-573
rolling camera 2-232
rotating camera 2-226
rotating camera target 2-228
round
towards infinity 2-263
roundoff error
convolution theorem and 2-381
effect on eigenvalues 2-144
S
saving
session to a file 2-520
scalar product (of vectors) 2-409
scaled complementary error function (defined)
2-574
search path
adding directories to 2-50
secant
inverse 2-70
inverse hyperbolic 2-72
Selected
Axes property 2-131
SelectionHighlight
Axes property 2-132
semicolon (special characters) 2-26
sequence of matrix names (M1 through M12)
generating 2-585
session
saving 2-520
shifting array
circular 2-297
sine
inverse 2-74
inverse hyperbolic 2-76
single quote (special characters) 2-25
slice planes, contouring 2-377
sorting
complex conjugate pairs 2-407
sound
files
reading 2-97
writing 2-98
source control systems
checking in files 2-280
checking out files 2-282
viewing current system 2-316
sparse matrix
minimum degree ordering of 2-319
permuting columns of 2-348
spreadsheets
reading into a matrix 2-533
writing matrices into 2-534
stack, displaying 2-450
str2cell 2-273
stretch-to-fill 2-106
string
converting from vector to 2-278
string matrix to cell array conversion 2-273
subsref (M-file function equivalent for
A(i,j,k...)) 2-26
subtraction (arithmetic operator) 2-11
sum
cumulative 2-418
Surface
and contour plotter 2-621
plotting mathematical functions 2-618
I-15
Index
T
uminus (M-file function equivalent for unary –)
2-13
Tag
Axes property 2-132
tangent
four-quadrant, inverse 2-82
inverse 2-80
inverse hyperbolic 2-84
target, of camera 2-233
test, logical See logical tests and detecting
TickDir, Axes property 2-132
TickDirMode, Axes property 2-132
TickLength, Axes property 2-132
time
CPU 2-408
required to execute commands 2-582
time and date functions 2-572
times (M-file function equivalent for .*) 2-13
Title, Axes property 2-133
tolerance, default 2-573
trace of a matrix 2-517
trailing blanks
removing 2-479
transformation
See also conversion
transpose
array (arithmetic operator) 2-12
matrix (arithmetic operator) 2-12
transpose (M-file function equivalent for .')
2-13
truth tables (for logical operations) 2-20
Type
Axes property 2-133
Units
Axes property 2-133
up vector, of camera 2-235
updating figure during M-file execution 2-544
uplus (M-file function equivalent for unary +) 2-13
UserData
Axes property 2-134
V
variables
checking existence of 2-594
clearing from workspace 2-304
vector
dot product 2-541
product (cross) 2-409
vector field, plotting 2-360
vectorizing ODE function (BVP) 2-216
vectors, creating
regularly spaced 2-27
velocity vectors, plotting 2-360
vertcat (M-file function equivalent for [;]) 2-26
video
saving in AVI format 2-99
view 2-224
view angle, of camera 2-237
View, Axes property (obsolete) 2-134
viewing
a group of object 2-224
a specific object in a scene 2-224
Visible
U
UIContextMenu
Axes property 2-133
I-16
Axes property 2-134
visualizing
cell array structure 2-272
volumes
Index
contouring slice planes 2-377
YScale, Axes property 2-136
YTick, Axes property 2-136
YTickLabel, Axes property 2-136
W
YTickLabelMode, Axes property 2-137
workspace
changing context while debugging 2-445,
2-458
clearing items from 2-304
YTickMode, Axes property 2-137
Z
ZColor, Axes property 2-134
ZDir, Axes property 2-134
X
ZGrid, Axes property 2-135
XAxisLocation, Axes property 2-134
ZLim, Axes property 2-135
XColor, Axes property 2-134
ZLimMode, Axes property 2-136
XDir, Axes property 2-134
ZMinorGrid, Axes property 2-136
XGrid, Axes property 2-135
ZScale, Axes property 2-136
XLabel, Axes property 2-135
ZTick, Axes property 2-136
XLim, Axes property 2-135
ZTickLabel, Axes property 2-136
XLimMode, Axes property 2-136
ZTickLabelMode, Axes property 2-137
XMinorGrid, Axes property 2-136
ZTickMode, Axes property 2-137
logical XOR
bit-wise 2-197
XScale, Axes property 2-136
XTick, Axes property 2-136
XTickLabel, Axes property 2-136
XTickLabelMode, Axes property 2-137
XTickMode, Axes property 2-137
Y
YAxisLocation, Axes property 2-134
YColor, Axes property 2-134
YDir, Axes property 2-134
YGrid, Axes property 2-135
YLabel, Axes property 2-135
YLim, Axes property 2-135
YLimMode, Axes property 2-136
YMinorGrid, Axes property 2-136
I-17
Was this manual useful for you? yes no
Thank you for your participation!

* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project

Download PDF

advertisement