Course Hero has millions of student submitted documents similar to the one

below including study guides, practice problems, reference materials, practice exams, textbook help and tutor support.

Course Hero has millions of student submitted documents similar to the one below including study guides, practice problems, reference materials, practice exams, textbook help and tutor support.

Language MATLAB
The of Technical Computing
Computation Visualization Programming
MATLAB Function Reference Volume 3: P - Z
Version 6
How to Contact The MathWorks:
www.mathworks.com comp.soft-sys.matlab support@mathworks.com suggest@mathworks.com bugs@mathworks.com doc@mathworks.com service@mathworks.com info@mathworks.com
Web Newsgroup Technical support Product enhancement suggestions Bug reports Documentation error reports Order status, license renewals, passcodes Sales, pricing, and general information Phone Fax Mail
508-647-7000 508-647-7001 The MathWorks, Inc. 3 Apple Hill Drive Natick, MA 01760-2098
For contact information about worldwide offices, see the MathWorks Web site. MATLAB Function Reference Volume 3: P - Z 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 . . . . . . . . . . . . . . . . . . . . . . . . . . . . File I/O . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Filename Construction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Opening, Loading, Saving Files . . . . . . . . . . . . . . . . . . . . . . . . Low-Level File I/O . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Text Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . XML Documents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1-21 1-21 1-25 1-27 1-29 1-34 1-34 1-34 1-35 1-35 1-35
i
Spreadsheets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Scientific Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Audio and Audio/Video . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Images . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Graphics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Basic Plots and Graphs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Annotating Plots . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Specialized Plotting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Bit-Mapped Images . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Printing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Handle Graphics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-D Visualization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Surface and Mesh Plots . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . View Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Lighting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Transparency . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Volume Visualization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 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-35 1-36 1-36 1-37 1-38 1-38 1-38 1-39 1-41 1-41 1-42 1-44 1-44 1-45 1-46 1-47 1-47 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 Mathematics Programming and Data Types File I/O Graphics 3-D Visualization Creating Graphical User Interface External Interfaces Startup, Command Window, help, editing and debugging, other general functions Arrays and matrices, linear algebra, data analysis, other areas of mathematics Function/expression evaluation, program control, function handles, object oriented programming, error handling, operators, data types, dates and times, timers General and low-level file I/O, plus specific file formats, like audio, spreadsheet, HDF, images Line plots, annotating graphs, specialized plots, images, printing, Handle Graphics Surface and mesh plots, view control, lighting and transparency, volume visualization. GUIDE, programming graphical user 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" "Command Window" "Getting Help" "Workspace, File, and Search Path" "Programming Tools" "System" "Performance Improvement Tools and Techniques" Startup and shutdown options Controlling Command Window Finding information File, search path, variable management Editing and debugging, source control, Notebook Identifying current computer, license, product version, and more 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
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
1-2
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
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
1-4
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. "Arrays and Matrices" "Linear Algebra" Basic array operators and operations, creation of elementary and specialized arrays and matrices Matrix analysis, linear equations, eigenvalues, singular values, logarithms, exponentials, factorization Trigonometry, exponentials and logarithms, complex values, rounding, remainders, discrete math Descriptive statistics, finite differences, correlation, filtering and convolution, fourier transforms Multiplication, division, evaluation, roots, derivatives, integration, eigenvalue problem, curve fitting, partial fraction expansion Interpolation, Delaunay triangulation and tessellation, convex hulls, Voronoi diagrams, domain generation Conversions between Cartesian and polar or spherical coordinates Differential equations, optimization, integration Airy, Bessel, Jacobi, Legendre, beta, elliptic, error, exponential integral, gamma functions Elementary sparse matrices, operations, reordering algorithms, linear algebra, iterative methods, tree operations Pi, imaginary unit, infinity, Not-a-Number, largest and smallest positive floating point numbers, floating point relative accuracy
"Elementary Math"
"Data Analysis and Fourier Transforms" "Polynomials"
"Interpolation and Computational Geometry" "Coordinate System Conversion" "Nonlinear Numerical Methods" "Specialized Math" "Sparse Matrices"
"Math Constants"
1-6
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
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
1-8
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
Matrix exponential Matrix logarithm Matrix square root
1-10
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
Round towards zero Round towards minus infinity Round towards plus infinity Round towards nearest integer Modulus after division Remainder after division Signum
1-12
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
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
1-14
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
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
1-20
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" "Arrays" "Operators and Operations" Numeric, character, structures, cell arrays, and data type conversion Basic array operations and manipulation Special characters and arithmetic, bit-wise, relational, logical, set, date and time operations M-files, function/expression evaluation, program control, function handles, object oriented programming, error handling
"Programming in MATLAB"
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
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
1-22
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 String to Numeric base2dec bin2dec hex2dec hex2num str2double str2num Numeric to String char dec2base dec2bin dec2hex int2str mat2str num2str Other Conversions cell2mat cell2struct datestr func2str logical mat2cell num2cell str2func struct2cell
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
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
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
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
1-24
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
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
1-26
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
Set intersection of two vectors Detect members of set Return set difference of two vectors Determine if set elements are in sorted order
1-28
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
Assign value to workspace variable
1-30
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
Begin catch block of try/catch statement Display error message Query MATLAB about errors in file input or output
1-32
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" "Opening, Loading, Saving Files" "Low-Level File I/O" "Text Files" "XML Documents" "Spreadsheets" "Scientific Data" "Audio and Audio/Video" "Images" Get path, directory, filename information; construct filenames Open files; transfer data between files and MATLAB workspace Low-level operations that use a file identifier (e.g., fopen, fseek, fread) Delimited or formatted I/O to text files Documents written in Extensible Markup Language Excel and Lotus 123 files CDF, FITS, HDF formats General audio functions; SparcStation, Wave, AVI files 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
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)
1-34
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
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
1-36
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 Annotating Plots Specialized Plotting Bit-Mapped Images Printing Handle Graphics Linear line plots, log and semilog plots Titles, axes labels, legends, mathematical symbols Bar graphs, histograms, pie charts, contour plots, function plotters Display image object, read and write graphics file, convert to movie frames Printing and exporting figures to standard formats 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
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
1-38
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
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
1-40
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
Screen capture of the current figure Clear figure window Clear figure
1-42
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 View Control Lighting Transparency Volume Visualization Plot matrices, visualize functions of two variables, specify colormap Control the camera viewpoint, zooming, rotation, aspect ratio, set axis limits Add and control scene lighting Specify and control object transparency 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
Data gridding and surface fitting Generation of X and Y arrays for 3-D plots
1-44
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
Cerate or position Light Light object creation function Position light in sphereical coordinates Lighting mode Material reflectance mode
1-46
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 Deploying User Interfaces Developing User Interfaces User Interface Objects Finding Objects from Callbacks GUI Utility Functions Controlling Program Execution Dialog boxes for error, user input, waiting, etc. Launching GUIs, creating the handles structure Starting GUIDE, managing application data, getting user input Creating GUI components Finding object handles from within callbacks functions Moving objects, text wrapping 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
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
1-48
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
Resumes program execution halted with uiwait Halts program execution, restart with uiresume
1-50
2
Functions Alphabetical List
2
Functions Alphabetical List
pack . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-12 pagedlg . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-14 pagesetupdlg . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-15 pareto . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-16 partialpath . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-17 pascal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-18 patch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-19 Patch Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-31 path . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-49 path2rc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-51 pathtool . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-52 pause . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-53 pbaspect . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-54 pcg . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-59 pchip . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-63 pcode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-65 pcolor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-66 pdepe . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-69 pdeval . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-80 peaks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-81 perl . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-82 perms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-83 permute . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-84 persistent . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-85 pi . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-86 pie . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-87 pie3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-89 pinv . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-91 planerot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-94 plot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-95 plot3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-100 plotedit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-102 plotmatrix . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-104 plotyy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-106 pol2cart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-108 polar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-109 poly . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-111
2-2
polyarea . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . polyder . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . polyeig . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . polyfit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . polyint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . polyval . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . polyvalm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . pow2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ppval . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . prefdir . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . primes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . print, printopt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . printdlg . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . printpreview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . prod . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . profile . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . profreport . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . propedit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . propedit (COM) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . psi . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . pwd . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . qmr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . qr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . qrdelete . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . qrinsert . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . qrupdate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . quad, quad8 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . quadl . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . questdlg . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . quit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . quiver . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . quiver3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . qz . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rand . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . randn . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . randperm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rank . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2-113 2-114 2-115 2-117 2-120 2-121 2-123 2-125 2-126 2-127 2-128 2-129 2-143 2-144 2-145 2-146 2-150 2-152 2-154 2-155 2-157 2-158 2-162 2-166 2-168 2-170 2-173 2-175 2-177 2-179 2-181 2-184 2-186 2-188 2-190 2-192 2-193
2-3
2
Functions Alphabetical List
rat, rats . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rbbox . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rcond . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . readasync . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . reallog . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . realmax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . realmin . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . realpow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . realsqrt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . record . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . reducepatch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . reducevolume . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . refresh . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . regexp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . regexpi . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . regexprep . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . registerevent (COM) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rehash . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . release (COM) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . repmat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . reset . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . reshape . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . residue . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rethrow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . return . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rgb2hsv . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rgbplot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ribbon . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rmappdata . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rmdir . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rmfield . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rmpath . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2-194 2-197 2-199 2-200 2-202 2-203 2-204 2-205 2-206 2-207 2-208 2-210 2-217 2-224 2-225 2-229 2-231 2-232 2-235 2-237 2-239 2-241 2-243 2-245 2-246 2-247 2-248 2-250 2-253 2-254 2-255 2-256 2-257 2-259 2-260 2-263 2-264
2-4
root object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Root Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . roots . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rose . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rosser . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rot90 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rotate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rotate3d . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . round . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rref . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rsf2csf . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . run . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . runtime . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . save . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . save (COM) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . save (serial) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . saveas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . saveobj . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . scatter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . scatter3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . schur . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . script . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . sec . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . sech . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . selectmoveresize . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . semilogx, semilogy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . send (COM) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . sendmail . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . serial . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . serialbreak . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . set . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . set (COM) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . set (serial) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . set (timer) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . setappdata . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . setdiff . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . setfield . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2-265 2-268 2-274 2-276 2-278 2-279 2-280 2-282 2-283 2-284 2-286 2-288 2-289 2-290 2-293 2-294 2-296 2-299 2-300 2-302 2-304 2-306 2-307 2-309 2-311 2-312 2-314 2-315 2-316 2-318 2-319 2-322 2-323 2-325 2-328 2-329 2-330
2-5
2
Functions Alphabetical List
setstr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . setxor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . shading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . shiftdim . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . shrinkfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . sign . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . sin . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . single . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . sinh . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . size . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . size (serial) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . slice . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . smooth3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . sort . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . sortrows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . sound . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . soundsc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . spalloc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . sparse . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . spaugment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . spconvert . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . spdiags . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . speye . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . spfun . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . sph2cart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . sphere . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . spinmap . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . spline . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . spones . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . spparms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . sprand . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . sprandn . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . sprandsym . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . sprank . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . sprintf . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . spy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . sqrt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2-332 2-333 2-334 2-337 2-338 2-342 2-343 2-345 2-346 2-348 2-351 2-352 2-357 2-359 2-361 2-362 2-363 2-364 2-365 2-367 2-368 2-370 2-373 2-374 2-376 2-377 2-379 2-380 2-384 2-385 2-388 2-389 2-390 2-391 2-392 2-398 2-400
2-6
sqrtm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . squeeze . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . sscanf . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . stairs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . start . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . startat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . std . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . stem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . stem3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . stop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . stopasync . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . str2double . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . str2func . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . str2mat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . str2num . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . strcat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . strcmp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . strcmpi . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . stream2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . stream3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . streamline . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . streamparticles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . streamribbon . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . streamslice . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . streamtube . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . strfind . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . strjust . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . strmatch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . strncmp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . strncmpi . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . strread . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . strrep . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . strtok . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . struct . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . struct2cell . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . strvcat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2-401 2-404 2-405 2-408 2-410 2-411 2-413 2-415 2-417 2-419 2-420 2-421 2-422 2-423 2-424 2-425 2-427 2-429 2-430 2-432 2-434 2-436 2-440 2-446 2-451 2-455 2-456 2-458 2-459 2-460 2-461 2-462 2-466 2-467 2-468 2-470 2-471
2-7
2
Functions Alphabetical List
sub2ind . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . subplot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . subsasgn . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . subsindex . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . subspace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . subsref . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . substruct . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . subvolume . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . sum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . superiorto . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . support . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . surf, surfc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . surf2patch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . surface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Surface Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . surfl . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . surfnorm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . svd . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . svds . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . switch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . symamd . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . symbfact . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . symmlq . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . symmmd . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . symrcm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . symvar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . startup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . system . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . tan . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . tanh . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . tempdir . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . tempname . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . terminal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . tetramesh . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . texlabel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Text Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2-472 2-474 2-476 2-477 2-479 2-480 2-481 2-482 2-484 2-485 2-486 2-487 2-491 2-493 2-501 2-515 2-518 2-520 2-523 2-525 2-527 2-529 2-530 2-534 2-536 2-538 2-539 2-540 2-541 2-543 2-545 2-546 2-547 2-549 2-552 2-554 2-562
2-8
textread . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . textwrap . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . tic, toc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . timer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . timerfind . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . title . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . toeplitz . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . trace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . trapz . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . treelayout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . treeplot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . tril . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . trimesh . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . triplequad . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . triplot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . trisurf . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . triu . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . true . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . try . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . tsearch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . tsearchn . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . uicontextmenu . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . uicontextmenu Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . uicontrol . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Uicontrol Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . uigetdir . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . uigetfile . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . uiimport . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . uimenu . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Uimenu Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . uint8, uint16, uint32, uint64 . . . . . . . . . . . . . . . . . . . . . . . . . uiputfile . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . uiresume, uiwait . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . uisetcolor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . uisetfont . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . uistack . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2-579 2-584 2-585 2-586 2-591 2-593 2-595 2-596 2-597 2-599 2-600 2-601 2-602 2-603 2-605 2-607 2-608 2-609 2-610 2-611 2-612 2-613 2-614 2-617 2-622 2-630 2-644 2-648 2-654 2-655 2-659 2-666 2-668 2-673 2-674 2-675 2-677
2-9
2
Functions Alphabetical List
................................................. undocheckout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . union . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . unique . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . unix . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . unmkpp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . unregisterallevents (COM) . . . . . . . . . . . . . . . . . . . . . . . . . . . unregisterevent (COM) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . unwrap . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . unzip . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . upper . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . urlread . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . urlwrite . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . usejava . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . vander . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . var . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . varargin, varargout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . vectorize . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ver . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . verctrl . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . version . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . vertcat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . view . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . viewmtx . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . volumebounds . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . voronoi . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . voronoin . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . wait . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . waitbar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . waitfor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . waitforbuttonpress . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . warndlg . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . warning . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . waterfall . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . wavplay . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . wavread . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . wavrecord . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2-677 2-678 2-679 2-680 2-682 2-683 2-684 2-686 2-688 2-692 2-693 2-694 2-695 2-696 2-697 2-698 2-699 2-701 2-702 2-704 2-708 2-709 2-711 2-714 2-718 2-720 2-724 2-727 2-728 2-730 2-731 2-732 2-733 2-737 2-739 2-741 2-742
2-10
wavwrite . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . web . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . weekday . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . what . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . whatsnew . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . which . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . while . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . whitebg . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . who, whos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . wilkinson . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . winopen . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . wk1read . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . wk1write . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . workspace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xlabel, ylabel, zlabel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xlim, ylim, zlim . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xlsfinfo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xlsread . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xmlread . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xmlwrite . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xslt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . zeros . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . zip . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . zoom . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2-743 2-744 2-746 2-747 2-749 2-750 2-753 2-756 2-757 2-759 2-760 2-761 2-762 2-763 2-764 2-766 2-768 2-769 2-773 2-774 2-775 2-776 2-777 2-778 2-780
2-11
pack
Purpose Syntax
2pack
Consolidate workspace memory
pack pack filename pack('filename') pack frees up needed space by reorganizing information so it only uses the minimum memory required. You must run pack from a directory for which you have write permission. Running pack clears all variables not in the base
Description
workspace, so persistent variables, for example, will be cleared.
pack filename accepts an optional filename for the temporary file used to hold the variables. Otherwise, it uses the file named pack.tmp. You must run pack from a directory for which you have write permission. pack('filename') is the function form of pack.
Remarks
The pack function does not affect the amount of memory allocated to the MATLAB process. You must quit MATLAB to free up this memory. Since MATLAB uses a heap method of memory management, extended MATLAB sessions may cause memory to become fragmented. When memory is fragmented, there may be plenty of free space, but not enough contiguous memory to store a new large variable. If you get the Out of memory message from MATLAB, the pack function may find you some free memory without forcing you to delete variables. The pack function frees space by: Saving all variables in the base workspace to disk in a temporary file called
pack.tmp
Clearing all variables and functions from memory Reloading the base workspace variables back from pack.tmp Deleting the temporary file pack.tmp
2-12
pack
If you use pack and there is still not enough free memory to proceed, you must clear some variables. If you run out of memory often, you can allocate larger matrices earlier in the MATLAB session and use these system-specific tips: UNIX: Ask your system manager to increase your swap space. Windows: Increase virtual memory using the Windows Control Panel. To maintain persistent variables when you run pack, use mlock in the function.
Examples
Change the current directory to one that is writable, run pack, and return to the previous directory.
cwd = pwd; cd(tempdir); pack cd(cwd)
See Also
clear
2-13
pagedlg
Purpose Syntax Description
2pagedlg
This function is obsolete. Use pagesetupdlg to display the page setup dialog.
pagedlg pagedlg(fig) pagedlg displays a page position dialog box for the current figure. The dialog
box enables you to set page layout properties.
pagedlg(fig) displays a page position dialog box for the figure identified by the handle fig.
Remarks
This dialog box enables you to set figure properties that determine how MATLAB lays out the figure on the printed paper. See the dialog box help for more information. The figure properties PaperPosition, PaperOrientation, PaperUnits
See Also
2-14
pagesetupdlg
Purpose Syntax Description
2pagesetupdlg
Page position dialog box
dlg = pagesetupdlg(fig) dlg = pagesetupdlg(fig) creates a dialog box from which a set of pagelayout properties for the figure window, fig, can be set. pagesetupdlg implements the "Page Setup..." option in the Figure File Menu.
Unlike pagedlg, pagesetupdlg currently only supports setting the layout for a single figure. fig must be a single figure handle, not a vector of figures or a simulink diagram.
See Also
pagedlg, printpreview, printopt
2-15
pareto
Purpose Syntax
2pareto
Pareto chart
pareto(Y) pareto(Y,names) pareto(Y,X) H = pareto(...)
Description
Pareto charts display the values in the vector Y as bars drawn in descending order.
pareto(Y) labels each bar with its element index in Y. pareto(Y,names) labels each bar with the associated name in the string matrix or cell array names. pareto(Y,X) labels each bar with the associated value from X. H = pareto(...) returns a combination of patch and line object handles.
See Also
hist, bar
2-16
partialpath
Purpose Description
2partialpath
pathname
A partial pathname is a pathname relative to the MATLAB path, matlabpath. It is used to locate private and method files, which are usually hidden, or to restrict the search for files when more than one file with the given name exists. A partial pathname contains the last component, or last several components, of the full pathname separated by /. For example, matfun/trace, private/children, inline/formula, and demos/clown.mat are valid partial pathnames. Specifying the @ in method directory names is optional, so funfun/inline/formula is also a valid partial pathname. Partial pathnames make it easy to find toolbox or MATLAB relative files on your path, independent of the location where MATLAB is installed. Many commands accept partial pathnames instead of a full pathname. Some of these commands are
help, type, load, exist, what, which, edit, dbtype, dbstop, dbclear, and fopen
Examples
The following examples use partial pathnames:
what funfun/inline M-files in argnames cat char directory matlabroot\toolbox\matlab\funfun\@inline disp feval inline subsref vertcat display formula nargin symvar exist horzcat nargout vectorize
which funfun/inline/formula matlabroot\toolbox\matlab\funfun\@inline\formula.m % inline method
See Also
matlabroot, path
2-17
pascal
Purpose Syntax
2pascal
Pascal matrix
A = pascal(n) A = pascal(n,1) A = pascal(n,2) A = pascal(n) returns the Pascal matrix of order n: a symmetric positive
Description
definite matrix with integer entries taken from Pascal's triangle. The inverse of A has integer entries.
A = pascal(n,1) returns the lower triangular Cholesky factor (up to the signs
of the columns) of the Pascal matrix. It is involutary, that is, it is its own inverse.
A = pascal(n,2) returns a transposed and permuted version of pascal(n,1). A is a cube root of the identity matrix.
Examples
pascal(4) returns 1 1 1 1 1 2 3 4 1 3 6 10 1 4 10 20
A = pascal(3,2) produces A = 1 -2 1 1 -1 0 1 0 0
See Also
chol
2-18
patch
Purpose Syntax
2patch
Create patch graphics object
patch(X,Y,C) patch(X,Y,Z,C) patch(FV) patch(...'PropertyName',PropertyValue...) patch('PropertyName',PropertyValue...) PN/PV pairs only handle = patch(...)
patch is the low-level graphics function for creating patch graphics objects. A
Description
patch object is one or more polygons defined by the coordinates of its vertices. You can specify the coloring and lighting of the patch. See the Creating 3-D Models with Patches for more information on using patch objects.
patch(X,Y,C) adds the filled two-dimensional patch to the current axes. The
elements of X and Y specify the vertices of a polygon. If X and Y are matrices, MATLAB draws one polygon per column. C determines the color of the patch. It can be a single ColorSpec, one color per face, or one color per vertex (see "Remarks"). If C is a 1-by-3 vector, it is assumed to be an RGB triplet, specifying a color directly.
patch(X,Y,Z,C) creates a patch in three-dimensional coordinates. patch(FV) creates a patch using structure FV, which contains the fields vertices, faces, and optionally facevertecdata. These fields correspond to the Vertices, Faces, and FaceVertexCData patch properties. patch(...'PropertyName',PropertyValue...) follows the X, Y, (Z), and C
arguments with property name/property value pairs to specify additional patch properties.
patch('PropertyName',PropertyValue,...) specifies all properties using property name/property value pairs. This form enables you to omit the color specification because MATLAB uses the default face color and edge color, unless you explicitly assign a value to the FaceColor and EdgeColor properties. This form also allows you to specify the patch using the Faces and Vertices properties instead of x-, y-, and z-coordinates. See the "Examples" section for more information.
2-19
patch
handle = patch(...) returns the handle of the patch object it creates.
Remarks
Unlike high-level area creation functions, such as fill or area, patch does not check the settings of the figure and axes NextPlot properties. It simply adds the patch object to the current axes. If the coordinate data does not define closed polygons, patch closes the polygons. The data can define concave or intersecting polygons. However, if the edges of an individual patch face intersect themselves, the resulting face may or may not be completely filled. In that case, it is better to break up the face into smaller polygons.
Specifying Patch Properties
You can specify properties as property name/property value pairs, structure arrays, and cell arrays (see the set and get reference pages for examples of how to specify these data types). There are two patch properties that specify color: CData use when specifying x-, y-, and z-coordinates (XData, YData, ZData). FaceVertexCData use when specifying vertices and connection matrix (Vertices and Faces). The CData and FaceVertexCData properties accept color data as indexed or true color (RGB) values. See the CData and FaceVertexCData property descriptions for information on how to specify color. Indexed color data can represent either direct indices into the colormap or scaled values that map the data linearly to the entire colormap (see the caxis
2-20
patch
function for more information on this scaling). The CDataMapping property determines how MATLAB interprets indexed color data. Color Specification
CData
Color Interpretation by MATLAB
FaceVertexCData
True Color Indexed
(CDataMapping) direct scaled
Color Mapping
Color Data Interpretation
You can specify patch colors as: A single color for all faces One color for each face enabling flat coloring One color for each vertex enabling interpolated coloring The following tables summarize how MATLAB interprets color data defined by the CData and FaceVertexCData properties.
Interpretation of the CData Property [X,Y,Z]Data Dimensions CData Required for Indexed True Color Results Obtained
m-by-n
scalar
1-by-1-by-3
Use the single color specified for all patch faces. Edges can be only a single color.
2-21
patch
[X,Y,Z]Data Dimensions
CData Required for Indexed True Color
Results Obtained
m-by-n m-by-n
1-by-n (n >= 4) m-by-n
1-by-n-by-3 m-by-n-3
Use one color for each patch face. Edges can be only a single color. Assign a color to each vertex. patch faces can be flat (a single color) or interpolated. Edges can be flat or interpolated.
Interpretation of the FaceVertexCData Property Vertices Dimensions Faces Dimensions FaceVertexCData Required for Indexed True Color Results Obtained
m-by-n
k-by-3
scalar
1-by-3
Use the single color specified for all patch faces. Edges can be only a single color. Use one color for each patch face. Edges can be only a single color. Assign a color to each vertex. patch faces can be flat (a single color) or interpolated. Edges can be flat or interpolated.
m-by-n m-by-n
k-by-3 k-by-3
k-by-1 m-by-1
k-by-3 m-by-3
Examples
This example creates a patch object using two different methods: Specifying x-, y-, and z-coordinates and color data (XData, YData, ZData, and CData properties). Specifying vertices, the connection matrix, and color data (Vertices, Faces, FaceVertexCData, and FaceColor properties).
2-22
patch
Specifying X, Y, and Z Coordinates
The first approach specifies the coordinates of each vertex. In this example, the coordinate data defines two triangular faces, each having three vertices. Using true color, the top face is set to white and the bottom face to gray.
x = [0 0;0 1;1 1]; y = [1 1;2 2;2 1]; z = [1 1;1 1;1 1]; tcolor(1,1,1:3) = [1 1 1]; tcolor(1,2,1:3) = [.7 .7 .7]; patch(x,y,z,tcolor)
2 1.9 1.8 1.7 1.6 1.5 1.4 1.3 1.2 1.1 1 0
V2
V3 V5
V1 V4
0.2 0.4 0.6 0.8
V6
1
Notice that each face shares two vertices with the other face (V1-V4 and V3-V5).
Specifying Vertices and Faces
The Vertices property contains the coordinates of each unique vertex defining the patch. The Faces property specifies how to connect these vertices to form each face of the patch. For this example, two vertices share the same location so you need to specify only four of the six vertices. Each row contains the x, y, and z-coordinates of each vertex.
vert = [0 1 1;0 2 1;1 2 1;1 1 1];
2-23
patch
There are only two faces, defined by connecting the vertices in the order indicated.
fac = [1 2 3;1 3 4];
To specify the face colors, define a 2-by-3 matrix containing two RGB color definitions.
tcolor = [1 1 1;.7 .7 .7];
With two faces and two colors, MATLAB can color each face with flat shading. This means you must set the FaceColor property to flat, since the faces/vertices technique is available only as a low-level function call (i.e., only by specifying property name/property value pairs). Create the patch by specifying the Faces, Vertices, and FaceVertexCData properties as well as the FaceColor property.
patch('Faces',fac,'Vertices',vert,'FaceVertexCData',tcolor,... 'FaceColor','flat')
V22
1.9 1.8 1.7 1.6 1.5 1.4 1.3 1.2 1.1
V3
Face 1
Face 2
V1 0
1
0.2
0.4
0.6
0.8
1
V4
Specifying only unique vertices and their connection matrix can reduce the size of the data for patches having many faces. See the descriptions of the Faces, Vertices, and FaceVertexCData properties for information on how to define them.
2-24
patch
MATLAB does not require each face to have the same number of vertices. In cases where they do not, pad the Faces matrix with NaNs. To define a patch with faces that do not close, add one or more NaN to the row in the Vertices matrix that defines the vertex you do not want connected.
Object Hierarchy
Root
Figure
Axes
Uicontrol
Uimenu
Uicontextmenu
Image
Light
Line
Patch
Rectangle
Surface
Text
Setting Default Properties
You can set default patch properties on the axes, figure, and root levels.
set(0,'DefaultPatchPropertyName',PropertyValue...) set(gcf,'DefaultPatchPropertyName',PropertyValue...) set(gca,'DefaultPatchPropertyName',PropertyValue...) PropertyName is the name of the patch property and PropertyValue is the value you are specifying. Use set and get to access patch properties.
Property List
The following table lists all patch properties and provides a brief description of each. The property name links take you to an expanded description of the properties.
Property Description Property Value
Property Name Data Defining the Object Faces
Connection matrix for Vertices
Values: m-by-n matrix Default: [1,2,3]
2-25
patch
Property Name Vertices
Property Description
Property Value
Matrix of x-, y-, and z-coordinates of the vertices (used with Faces) The x-coordinates of the vertices of the patch The y-coordinates of the vertices of the patch The z-coordinates of the vertices of the patch
Values: matrix Default: [0,1;1,1;0,0] Values: vector or matrix Default: [0;1;0] Values: vector or matrix Default: [1;1;0] Values: vector or matrix Default: [] empty matrix
XData
YData
ZData
Specifying Color
CData
Color data for use with the
XData/YData/ZData method
Values: scalar, vector, or matrix Default: [] empty matrix Values: scaled, direct Default: scaled Values: ColorSpec, none, flat, interp Default: ColorSpec Values: ColorSpec, none, flat, interp Default: ColorSpec Values: matrix Default: [] empty matrix Values: ColorSpec, none,
auto
CDataMapping EdgeColor
Controls mapping of CData to colormap Color of face edges
FaceColor
Color of face
FaceVertexCData
MarkerEdgeColor
Color data for use with
Faces/Vertices method
Color of marker or the edge color for filled markers Fill color for markers that are closed shapes
Default: auto
MarkerFaceColor
Values: ColorSpec, none,
auto
Default: none
Controlling the Effects of Lights
2-26
patch
Property Name AmbientStrength
Property Description
Property Value
Intensity of the ambient light Controls lighting of faces pointing away from camera Intensity of diffuse light Method used to light edges
Values: scalar >=0 and <=1 Default: 0.3 Values: unlit, lit,
reverselit Default: reverselit
BackFaceLighting
DiffuseStrength
Values: scalar >=0 and <=1 Default: 0.6 Values: none, flat, gouraud, phong Default: none Values: none, flat, gouraud, phong Default: none Values: auto, manual Default: auto Values: scalar 0 to 1 Default: 1 Values: scalar >= 1 Default: 10 Values: scalar >=0 and <=1 Default: 0.9 Values: matrix
EdgeLighting
FaceLighting
Method used to light edges
NormalMode
SpecularColorReflectan ce SpecularExponent
MATLAB-generated or user-specified normal vectors Composite color of specularly reflected light Harshness of specular reflection Intensity of specular light Vertex normal vectors
SpecularStrength
VertexNormals
Defining Edges and Markers LineStyle
Select from five line styles. The width of the edge in points
Values: -, --, :, -., none Default: - Values: scalar Default: 0.5 points
LineWidth
2-27
patch
Property Name Marker
Property Description
Property Value
Marker symbol to plot at data points Size of marker in points
Values: see Marker property Default: none Values: size in points Default: 6
MarkerSize
Specifying Transparency AlphaDataMapping
Transparency mapping method Transparency of the edges of patch faces Transparency of the patch face Face and vertex transparency data
none, direct, scaled Default: scaled scalar, flat, interp Default: 1 (opaque) scalar, flat, interp Default: 1 (opaque)
EdgeAlpha
FaceAlpha
FaceVertexAlphaData Controlling the Appearance
m-by-1 matrix
Clipping EraseMode
Clipping to axes rectangle Method of drawing and erasing the patch (useful for animation) Highlight patch when selected (Selected property set to on) Make the patch visible or invisible
Values: on, off Default: on Values: normal, none, xor,
background Default: normal
SelectionHighlight
Values: on, off Default: on Values: on, off Default: on
Visible
Controlling Access to Objects HandleVisibility
Determines if and when the the patch's handle is visible to other functions
Values: on, callback, off Default: on
2-28
patch
Property Name HitTest
Property Description
Property Value
Determines if the patch can become the current object (see the figure CurrentObject property)
Values: on, off Default: on
Controlling Callback Routine Execution BusyAction
Specify how to handle callback routine interruption Define a callback routine that executes when a mouse button is pressed on over the patch Define a callback routine that executes when an patch is created Define a callback routine that executes when the patch is deleted (via close or delete) Determine if callback routine can be interrupted Associate a context menu with the patch
Values: cancel, queue Default: queue Values: string or function handle Default: '' (empty string) Values: string or function handle Default: '' (empty string) Values: string or function handle Default: '' (empty string) Values: on, off Default: on (can be interrupted) Values: handle of a Uicontrextmenu
ButtonDownFcn
CreateFcn
DeleteFcn
Interruptible
UIContextMenu
General Information About the Patch Children Parent
Patch objects have no children The parent of a patch object is always an axes object Indicate whether the patch is in a "selected" state. User-specified label
Values: [] (empty matrix) Value: axes handle Values: on, off Default: on Value: any string Default: '' (empty string)
Selected
Tag
2-29
patch
Property Name Type
Property Description
Property Value
The type of graphics object (read only) User-specified data
Value: the string 'patch' Values: any matrix Default: [] (empty matrix)
UserData
See Also
area, caxis, fill, fill3, isosurface, surface
2-30
Patch Properties
Modifying Properties
2Patch 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.
Patch Property Descriptions
This section lists property names along with the type of values each accepts. Curly braces { } enclose default values.
AlphaDataMapping none | direct | {scaled}
Transparency mapping method. This property determines how MATLAB interprets indexed alpha data. This property can be any of the following: none - The transparency values of FaceVertexAlphaData are between 0 and 1 or are clamped to this range (the default). scaled - Transform the FaceVertexAlphaData to span the portion of the alphamap indicated by the axes ALim property, linearly mapping data values to alpha values. direct - use the FaceVertexAlphaData as indices directly into the alphamap. When not scaled, the data are usually integer values ranging from 1 to length(alphamap). MATLAB maps values less than 1 to the first alpha value in the alphamap, and values greater than length(alphamap) to the last alpha value in the alphamap. Values with a decimal portion are fixed to the nearest, lower integer. If FaceVertexAlphaData is an array unit8 integers, then the indexing begins at 0 (i.e., MATLAB maps a value of 0 to the first alpha value in the alphamap).
AmbientStrength
scalar >= 0 and <= 1
Strength of ambient light. This property sets the strength of the ambient light, which is a nondirectional light source that illuminates the entire scene. You must have at least one visible light object in the axes for the ambient light to be visible. The axes AmbientColor property sets the color of the ambient light, which is therefore the same on all objects in the axes. You can also set the strength of the diffuse and specular contribution of light objects. See the DiffuseStrength and SpecularStrength properties.
2-31
Patch Properties
BackFaceLighting
unlit | lit | {reverselit}
Face lighting control. This property determines how faces are lit when their vertex normals point away from the camera: unlit face is not lit lit face lit in normal way reverselit face is lit as if the vertex pointed towards the camera This property is useful for discriminating between the internal and external surfaces of an object. See the Using MATLAB Graphics manual for an example.
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 routes 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 over the patch object. 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.
CData
scalar, vector, or matrix
Patch colors. This property specifies the color of the patch. You can specify color for each vertex, each face, or a single color for the entire patch. The way
2-32
Patch Properties
MATLAB interprets CData depends on the type of data supplied. The data can be numeric values that are scaled to map linearly into the current colormap, integer values that are used directly as indices into the current colormap, or arrays of RGB values. RGB values are not mapped into the current colormap, but interpreted as the colors defined. On true color systems, MATLAB uses the actual colors defined by the RGB triples. On pseudocolor systems, MATLAB uses dithering to approximate the RGB triples using the colors in the figure's Colormap and Dithermap. The following two diagrams illustrate the dimensions of CData with respect to the coordinate data arrays, XData, YData, and ZData. The first diagram illustrates the use of indexed color.
Single Color
One Color Per Face
One Color Per Vertex
CData
CData CData [X,Y,Z]Data [X,Y,Z]Data
F a c e 1
F a c e 2
F a c e 3
F a c e 4
F a c e 5
[X,Y,Z]Data
2-33
Patch Properties
The second diagram illustrates the use of true color. True color requires m-by-n-by-3 arrays to define red, green, and blue components for each color. Single Color
CData
One Color Per Face
One Color Per Vertex Blue Green Red
B G R
[X,Y,Z]Data
B G R
CData [X,Y,Z]Data
CData
F a c e 1
F a c e 2
F a c e 3
F a c e 4
F a c e 5
[X,Y,Z]Data
Note that if CData contains NaNs, MATLAB does not color the faces. See also the Faces, Vertices, and FaceVertexCData properties for an alternative method of patch definition.
CDataMapping {scaled} | direct
Direct or scaled color mapping. This property determines how MATLAB interprets indexed color data used to color the patch. (If you use true color specification for CData or FaceVertexCData, this property has no effect.) scaled transform the color data to span the portion of the colormap indicated by the axes CLim property, linearly mapping data values to colors. See the caxis command for more information on this mapping. direct use the color data as indices directly into the colormap. When not scaled, the data are usually integer values ranging from 1 to
2-34
Patch Properties
length(colormap). MATLAB maps values less than 1 to the first color in the colormap, and values greater than length(colormap) to the last color in
the colormap. Values with a decimal portion are fixed to the nearest, lower integer.
Children
matrix of handles
Always the empty matrix; patch objects have no children.
Clipping {on} | off
Clipping to axes rectangle. When Clipping is on, MATLAB does not display any portion of the patch outside the axes rectangle.
CreateFcn
string or function handle
Callback routine executed during object creation. This property defines a callback routine that executes when MATLAB creates a patch object. You must define this property as a default value for patches. For example, the statement,
set(0,'DefaultPatchCreateFcn','set(gcf,''DitherMap'',my_dither_ map)')
defines a default value on the root level that sets the figure DitherMap property whenever you create a patch object. MATLAB executes this routine after setting all properties for the patch created. Setting this property on an existing patch object has no effect. The handle of the object whose CreateFcn is being executed is accessible only through the root CallbackObject property, which you can query using gcbo. See Function Handle Callbacks for information on how to use function handles to define the callback function.
DeleteFcn
string or function handle
Delete patch callback routine. A callback routine that executes when you delete the patch object (e.g., when you issue a delete command or clear the axes (cla) or figure (clf) containing the patch). MATLAB executes the routine before deleting the object's properties so these values are available to the callback routine. The handle of the object whose DeleteFcn is being executed is accessible only through the root CallbackObject property, which you can query using gcbo.
2-35
Patch Properties
See Function Handle Callbacks for information on how to use function handles to define the callback function.
DiffuseStrength
scalar >= 0 and <= 1
Intensity of diffuse light. This property sets the intensity of the diffuse component of the light falling on the patch. Diffuse light comes from light objects in the axes. You can also set the intensity of the ambient and specular components of the light on the patch object. See the AmbientStrength and SpecularStrength properties.
EdgeAlpha {scalar = 1} | flat | interp
Transparency of the edges of patch faces. This property can be any of the following: scalar - A single non-Nan scalar value between 0 and 1 that controls the transparency of all the edges of the object. 1 (the default) is fully opaque and 0 means completely transparent. flat - The alpha data (FaceVertexAlphaData) of each vertex controls the transparency of the edge that follows it. interp - Linear interpolation of the alpha data (FaceVertexAlphaData) at each vertex determines the transparency of the edge. Note that you cannot specify flat or interp EdgeAlpha without first setting FaceVertexAlphaData to a matrix containing one alpha value per face (flat) or one alpha value per vertex (interp).
EdgeColor {ColorSpec} | none | flat | interp
Color of the patch edge. This property determines how MATLAB colors the edges of the individual faces that make up the patch. ColorSpec A three-element RGB vector or one of the MATLAB predefined names, specifying a single color for edges. The default edge color is black. See ColorSpec for more information on specifying color. none Edges are not drawn.
2-36
Patch Properties
flat The color of each vertex controls the color of the edge that follows it. This means flat edge coloring is dependent on the order you specify the vertices:
Vertex controlling the color of the following edge
interp Linear interpolation of the CData or FaceVertexCData values at the vertices determines the edge color.
EdgeLighting {none} | flat | gouraud | phong
Algorithm used for lighting calculations. This property selects the algorithm used to calculate the effect of light objects on patch edges. Choices are: none Lights do not affect the edges of this object. flat The effect of light objects is uniform across each edge of the patch. gouraud The effect of light objects is calculated at the vertices and then linearly interpolated across the edge lines. phong The effect of light objects is determined by interpolating the vertex normals across each edge line and calculating the reflectance at each pixel. Phong lighting generally produces better results than Gouraud lighting, but takes longer to render.
EraseMode {normal} | none | xor | background
Erase mode. This property controls the technique MATLAB uses to draw and erase patch objects. Alternative erase modes are useful in creating animated sequences, where control of the way individual objects redraw is necessary to improve performance and obtain the desired effect. normal Redraw the affected region of the display, performing the three-dimensional analysis necessary to ensure that all objects are rendered correctly. This mode produces the most accurate picture, but is the slowest.
2-37
Patch Properties
The other modes are faster, but do not perform a complete redraw and are therefore less accurate. none Do not erase the patch when it is moved or destroyed. While the object is still visible on the screen after erasing with EraseMode none, you cannot print it because MATLAB stores no information about its former location. xor Draw and erase the patch by performing an exclusive OR (XOR) with each pixel index of the screen behind it. Erasing the patch does not damage the color of the objects behind it. However, patch color depends on the color of the screen behind it and is correctly colored only when over the axes background Color, or the figure background Color if the axes Color is set to none. background Erase the patch by drawing it in the axes' background Color, or the figure background Color if the axes Color is set to none. This damages objects that are behind the erased patch, but the patch is always properly colored.
Printing with Non-normal Erase Modes. MATLAB always prints figures as if the EraseMode of all objects is normal. This means graphics objects created with EraseMode set to none, xor, or background can look different on screen than on
paper. On screen, MATLAB may mathematically combine layers of colors (e.g., XORing a pixel color with that of the pixel behind it) and ignore three-dimensional sorting to obtain greater rendering speed. However, these techniques are not applied to the printed output. You can use the MATLAB getframe command or other screen capture application to create an image of a figure containing non-normal mode objects.
FaceAlpha {scalar = 1} | flat | interp
Transparency of the patch face. This property can be any of the following: A scalar - A single non-NaN scalar value between 0 and 1 that controls the transparency of all the faces of the object. 1 (the default) is fully opaque and 0 is completely transparent (invisible). flat - The values of the alpha data (FaceVertexAlphaData) determine the transparency for each face. The alpha data at the first vertex determines the transparency of the entire face. interp - Bilinear interpolation of the alpha data (FaceVertexAlphaData) at each vertex determine the transparency of each face.
2-38
Patch Properties
Note that you cannot specify flat or interp FaceAlpha without first setting FaceVertexAlphaData to a matrix containing one alpha value per face (flat) or one alpha value per vertex (interp).
FaceColor {ColorSpec} | none | flat | interp
Color of the patch face. This property can be any of the following: ColorSpec A three-element RGB vector or one of the MATLAB predefined names, specifying a single color for faces. See ColorSpec for more information on specifying color. none Do not draw faces. Note that edges are drawn independently of faces. flat The values of CData or FaceVertexCData determine the color for each face in the patch. The color data at the first vertex determines the color of the entire face. interp Bilinear interpolation of the color at each vertex determines the coloring of each face.
FaceLighting {none} | flat | gouraud | phong
Algorithm used for lighting calculations. This property selects the algorithm used to calculate the effect of light objects on patch faces. Choices are: none Lights do not affect the faces of this object. flat The effect of light objects is uniform across the faces of the patch. Select this choice to view faceted objects. gouraud The effect of light objects is calculated at the vertices and then linearly interpolated across the faces. Select this choice to view curved surfaces. phong The effect of light objects is determined by interpolating the vertex normals across each face and calculating the reflectance at each pixel. Select this choice to view curved surfaces. Phong lighting generally produces better results than Gouraud lighting, but takes longer to render.
Faces
m-by-n matrix
Vertex connection defining each face. This property is the connection matrix specifying which vertices in the Vertices property are connected. The Faces matrix defines m faces with up to n vertices each. Each row designates the connections for a single face, and the number of elements in that row that are not NaN defines the number of vertices for that face.
2-39
Patch Properties
The Faces and Vertices properties provide an alternative way to specify a patch that can be more efficient than using x, y, and z coordinates in most cases. For example, consider the following patch. It is composed of eight triangular faces defined by nine vertices.
Faces property Vertices property
V7
2 1.8 1.6 1.4 1.2
V8
V9 F1 V1 V4 V5 5 V1 V5 V2 5 V2 V5 V6 5 V2 V6 V3 V4 V7 V8 V4 V8 V5 7 V1 X1 Y1 Z1 V2 X2 Y2 Z2 V3 X3 Y3 Z3 V4 X4 Y4 Z4 V5 X5 Y5 Z5 V6 X6 Y6 Z6 V7 X7 Y7 Z7 V8 X8 Y8 Z8 V9 X9 Y9 Z9 F2 F8 F3 V6 F3 F4 F5 F6 F4
F5 F6 V5 F1 F2
0.2 0.4 0.6 0.8 1
F7
V4 1
0.8 0.6 0.4 0.2 0 0
F7 V5 V8 V9 F8 5 5 V9 V6 V
1.8 2
V1
V2
1.2
1.4
1.6
V3
The corresponding Faces and Vertices properties are shown to the right of the patch. Note how some faces share vertices with other faces. For example, the fifth vertex (V5) is used six times, once each by faces one, two, and three and six, seven, and eight. Without sharing vertices, this same patch requires 24 vertex definitions.
FaceVertexAlphaDatam-by-1 matrix
Face and vertex transparency data. The FaceVertexAlphaData property specifies the tranparency of patches defined by the Faces and Vertices properties. The interpretation of the values specified for FaceVertexAlphaData depends on the dimensions of the data.
FaceVertexAlphaData can be one of the following:
A single value, which applies the same transparency to the entire patch. An m-by-1 matrix (where m is the number of rows in the Faces property), which specifies one transparency value per face.
2-40
Patch Properties
An m-by-1 matrix (where m is the number of rows in the Vertices property), which specifies one transparency value per vertex.
FaceVertexCData
matrix
Face and vertex colors. The FaceVertexCData property specifies the color of patches defined by the Faces and Vertices properties, and the values are used when FaceColor, EdgeColor, MarkerFaceColor, or MarkerEdgeColor are set appropriately. The interpretation of the values specified for FaceVertexCData depends on the dimensions of the data. For indexed colors, FaceVertexCData can be: A single value, which applies a single color to the entire patch An n-by-1 matrix, where n is the number of rows in the Faces property, which specifies one color per face An n-by-1 matrix, where n is the number of rows in the Vertices property, which specifies one color per vertex For true colors, FaceVertexCData can be: A 1-by-3 matrix , which applies a single color to the entire patch An n-by-3 matrix, where n is the number of rows in the Faces property, which specifies one color per face An n-by-3 matrix, where n is the number of rows in the Vertices property, which specifies one color per vertex The following diagram illustrates the various forms of the FaceVertexCData property for a patch having eight faces and nine vertices. The CDataMapping
2-41
Patch Properties
property determines how MATLAB interprets the FaceVertexCData property when you specify indexed colors.
FaceVertexCData
Indexed
True color
One color Single color per face C C1 C2 C3 C4 C5 C6 C7 C8
One color per vertex C1 C2 C3 C4 C5 C6 C7 C8 C9
Single color R G B
One color per face R1 G1 B1 R2 G2 B2 R3 G3 B3 R4 G4 B4 R5 G5 B5 R6 G6 B6 R7 G7 B7 R8 G8 B8
One color per vertex R1 G1 B1 R2 G2 B2 R3 G3 B3 R4 G4 B4 R5 G5 B5 R6 G6 B6 R7 G7 B7 R8 G8 B8 R9 B9 B9
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
2-42
Patch Properties
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. 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 patch 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 patch. If HitTest is off, clicking on the patch selects the object below it (which maybe the axes containing it).
Interruptible
{on} | off
Callback routine interruption mode. The Interruptible property controls whether a patch 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.
2-43
Patch Properties
{-} | -- | : | -. | none
LineStyle
Edge linestyle. This property specifies the line style of the patch edges. The following table lists the available line styles.
Symbol Line Style
- --
:
solid line (default) dashed line dotted line dash-dot line no line
-.
none
You can use LineStyle none when you want to place a marker at each point but do not want the points connected with a line (see the Marker property).
LineWidth
scalar
Edge line width. The width, in points, of the patch edges (1 point = 1/72 inch). The default LineWidth is 0.5 points.
Marker
character (see table)
Marker symbol. The Marker property specifies marks that locate vertices. You can set values for the Marker property independently from the LineStyle property. The following tables lists the available markers.
Marker Specifier + o * . x s Description
plus sign circle asterisk point cross square
2-44
Patch Properties
Marker Specifier d ^ v > < p h none MarkerEdgeColor
Description
diamond upward pointing triangle downward pointing triangle right pointing triangle left pointing triangle five-pointed star (pentagram) six-pointed star (hexagram) no marker (default)
ColorSpec | none | {auto} | flat
Marker edge color. The color of the marker or the edge color for filled markers (circle, square, diamond, pentagram, hexagram, and the four triangles). ColorSpec defines the color to use. none specifies no color, which makes nonfilled markers invisible. auto sets MarkerEdgeColor to the same color as the EdgeColor property.
MarkerFaceColor ColorSpec | {none} | auto | flat
Marker face color. The fill color for markers that are closed shapes (circle, square, diamond, pentagram, hexagram, and the four triangles). ColorSpec defines the color to use. none makes the interior of the marker transparent, allowing the background to show through. auto sets the fill color to the axes color, or the figure color, if the axes Color property is set to none.
MarkerSize
size in points
Marker size. A scalar specifying the size of the marker, in points. The default value for MarkerSize is six points (1 point = 1/72 inch). Note that MATLAB draws the point marker at 1/3 of the specified size.
2-45
Patch Properties
NormalMode
{auto} | manual
MATLAB-generated or user-specified normal vectors. When this property is auto, MATLAB calculates vertex normals based on the coordinate data. If you specify your own vertex normals, MATLAB sets this property to manual and does not generate its own data. See also the VertexNormals property.
Parent
axes handle
Patch's parent. The handle of the patch's parent object. The parent of a patch object is the axes in which it is displayed. You can move a patch object to another axes by setting this property to the handle of the new parent.
Selected on | {off}
Is object selected? When this property is on, MATLAB displays selection handles or a dashed box (depending on the number of faces) if the SelectionHighlight property is also on. You can, for example, define the ButtonDownFcn to set this property, allowing users to select the object with the mouse.
SelectionHighlight {on} | off
Objects highlight when selected. When the Selected property is on, MATLAB indicates the selected state by: Drawing handles at each vertex for a single-faced patch. Drawing a dashed bounding box for a multi-faced patch. When SelectionHighlight is off, MATLAB does not draw the handles.
SpecularColorReflectancescalar in the range 0 to 1
Color of specularly reflected light. When this property is 0, the color of the specularly reflected light depends on both the color of the object from which it reflects and the color of the light source. When set to 1, the color of the specularly reflected light depends only on the color or the light source (i.e., the light object Color property). The proportions vary linearly for values in between.
SpecularExponent
scalar >= 1
Harshness of specular reflection. This property controls the size of the specular spot. Most materials have exponents in the range of 5 to 20.
2-46
Patch Properties
SpecularStrength
scalar >= 0 and <= 1
Intensity of specular light. This property sets the intensity of the specular component of the light falling on the patch. Specular light comes from light objects in the axes. You can also set the intensity of the ambient and diffuse components of the light on the patch object. See the AmbientStrength and DiffuseStrength properties.
Tag
string
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 use patch objects to create borders for a group of uicontrol objects and want to change the color of the borders in a uicontrol's callback routine. You can specify a Tag with the patch definition:
patch(X,Y,'k','Tag','PatchBorder')
Then use findobj in the uicontrol's callback routine to obtain the handle of the patch and set its FaceColor property.
set(findobj('Tag','PatchBorder'),'FaceColor','w') Type
string (read only)
Class of the graphics object. For patch objects, Type is always the string 'patch'.
UIContextMenu
handle of a uicontextmenu object
Associate a context menu with the patch. Assign this property the handle of a uicontextmenu object created in the same figure as the patch. Use the uicontextmenu function to create the context menu. MATLAB displays the context menu whenever you right-click over the patch.
UserData
matrix
User-specified data. Any matrix you want to associate with the patch object. MATLAB does not use this data, but you can access it using set and get.
2-47
Patch Properties
VertexNormals
matrix
Surface normal vectors. This property contains the vertex normals for the patch. MATLAB generates this data to perform lighting calculations. You can supply your own vertex normal data, even if it does not match the coordinate data. This can be useful to produce interesting lighting effects.
Vertices
matrix
Vertex coordinates. A matrix containing the x-, y-, z-coordinates for each vertex. See the Faces property for more information.
Visible {on} | off
Patch object visibility. By default, all patches are visible. When set to off, the patch is not visible, but still exists and you can query and set its properties.
XData
vector or matrix
X-coordinates. The x-coordinates of the patch vertices. If XData is a matrix, each column represents the x-coordinates of a single face of the patch. In this case, XData, YData, and ZData must have the same dimensions.
YData
vector or matrix
Y-coordinates. The y-coordinates of the patch vertices. If YData is a matrix, each column represents the y-coordinates of a single face of the patch. In this case, XData, YData, and ZData must have the same dimensions.
ZData
vector or matrix
Z-coordinates. The z-coordinates of the patch vertices. If ZData is a matrix, each column represents the z-coordinates of a single face of the patch. In this case, XData, YData, and ZData must have the same dimensions.
See Also
patch
2-48
path
Purpose Graphical Interface Syntax
2path
View or change the MATLAB directory search path As an alternative to the path function, use the Set Path dialog box. To open it, select Set Path from the File menu in the MATLAB desktop.
path path('newpath') path(path,'newpath') path('newpath',path) p = path(...) path displays the current MATLAB search path. The initial search path list is defined by toolbox/local/pathdef.m. path('newpath') changes the search path to newpath, where newpath is a
Description
string array of directories.
path(path,'newpath') appends a new directory to the current search path. path('newpath',path) prepends a new directory to the current search path. p = path(...) returns the specified path in string variable p.
Remarks
For more information on how MATLAB uses the directory search path, see "Search Path", "How Functions Work", and "How MATLAB Determines Which Method to Call".
Note Save any M-files you create and any MathWorks-supplied M-files that you edit in a directory that is not in the $matlabroot/toolbox directory tree. If you keep your files in $matlabroot/toolbox directories, they may be overwritten when you install a new version of MATLAB. Also note that locations of files in $matlabroot/toolbox directories are loaded and cached in memory at the beginning of each MATLAB session to improve performance. If you edit and save files in $matlabroot/toolbox directories using the Editor, run clear functions to ensure that the updated files are used. If you save files to $matlabroot/toolbox directories using an external editor or add or remove in from these directories using file system operations, run rehash toolbox before you use the files in the current session. If you make
2-49
path
changes to existing files in $matlabroot/toolbox directories using an external editor, run clear functionname before you use the files in the current session. For more information, see rehash or "Toolbox Path Caching" in MATLAB Development Environment documentation.
Examples
To add a new directory to the search path on Windows,
path(path,'c:/tools/goodstuff')
To add a new directory to the search path on UNIX,
path(path,'/home/tools/goodstuff')
See Also
addpath, cd, dir, genpath, matlabroot, partialpath, pathtool, rehash, rmpath, what
2-50
path2rc
Purpose Graphical Interface Syntax Description
2path2rc
Save current MATLAB search path to pathdef.m file As an alternative to the pathdef function, use the Set Path dialog box. To open it, select Set Path from the File menu in the MATLAB desktop.
path2rc path2rc newfile path2rc saves the current MATLAB search path to pathdef.m. It returns 0 1
If the file was saved successfully If the save failed
path2rc newfile saves the current MATLAB search path to newfile, where newfile is in the current directory or is a relative or absolute path.
Examples
path2rc myfiles/newpath
saves the current search path to the file newpath.m, which is located in the myfiles directory in the MATLAB current directory.
See Also
path, pathtool
2-51
pathtool
Purpose Graphical Interface Syntax Description
2pathtool
Open Set Path dialog box to view and change MATLAB path As an alternative to the pathtool function, select Set Path from the File menu in the MATLAB desktop.
pathtool pathtool opens the Set Path dialog box, a graphical user interface you use to
view and modify the MATLAB search path, as well as see files on the path.
When you press one of these buttons, the change is made to the current search path, but the search path is not automatically saved for future sessions.
Directories on the current MATLAB search path.
Make changes to the search path.
Save changes for use in the next MATLAB session.
See Also
addpath, edit, path, rmpath, workspace
"Setting the Search Path"
2-52
pause
Purpose Syntax
2pause
Halt execution temporarily
pause pause(n) pause on pause off pause, by itself, causes M-files to stop and wait for you to press any key before
Description
continuing.
pause(n) pauses execution for n seconds before continuing, where n can be any
real number. The resolution of the clock is platform specific. A fractional pause of 0.01 seconds should be supported on most platforms.
pause on allows subsequent pause commands to pause execution. pause off ensures that any subsequent pause or pause(n) statements do not pause execution. This allows normally interactive scripts to run unattended.
See Also
drawnow
2-53
pbaspect
Purpose Syntax
2pbaspect
Set or query the plot box aspect ratio
pbaspect pbaspect([aspect_ratio]) pbaspect('mode') pbaspect('auto') pbaspect('manual') pbaspect(axes_handle,...)
Description
The plot box aspect ratio determines the relative size of the x-, y-, and z-axes.
pbaspect with no arguments returns the plot box aspect ratio of the current
axes.
pbaspect([aspect_ratio]) sets the plot box 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-axes size. For example, a value of [1 1 1] (the default) means the plot box is a cube (although with stretch-to-fill enabled, it may not appear as a cube). See Remarks. pbaspect('mode') returns the current value of the plot box aspect ratio mode, which can be either auto (the default) or manual. See Remarks. pbaspect('auto') sets the plot box aspect ratio mode to auto. pbaspect('manual') sets the plot box aspect ratio mode to manual. pbaspect(axes_handle,...) performs the set or query on the axes identified by the first argument, axes_handle. If you do not specify an axes handle, pbaspect operates on the current axes.
Remarks
pbaspect sets or queries values of the axes object PlotBoxAspectRatio and PlotBoxAspectRatioMode properties.
When the plot box aspect ratio mode is auto, MATLAB sets the ratio to [1 1 1], but may change it to accommodate manual settings of the data aspect ratio, camera view angle, or axis limits. See the axes DataAspectRatio property for a table listing the interactions between various properties.
2-54
pbaspect
Setting a value for the plot box aspect ratio or setting the plot box aspect ratio mode to manual disables the MATLAB stretch-to-fill feature (stretching of the axes to fit the window). This means setting the plot box aspect ratio to its current value,
pbaspect(pbaspect)
can cause a change it the way the graphs look. See the Remarks section of the axes reference description and the "Aspect Ratio" section in the Using MATLAB Graphics manual for a discussion of stretch-to-fill.
Examples
The following surface plot of the function z = xe ( x y ) is useful to illustrate the plot box 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 0 -1 -2 -2 0 -1 1 2
Querying the plot box aspect ratio shows that the plot box is square.
pbaspect ans = 1 1
1
2-55
pbaspect
It is also interesting to look at the data aspect ratio selected by MATLAB.
daspect ans = 4 4
1
To illustrate the interaction between the plot box and data aspect ratios, set the data aspect ratio to [1 1 1] and again query the plot box aspect ratio.
daspect([1 1 1])
0.5
0
-0.5 2 1.5 1 0.5 0 -0.5 -1 -1.5 -2 -2 -1 0 1 2
pbaspect ans = 4 4
1
The plot box aspect ratio has changed to accommodate the specified data aspect ratio. Now suppose you want the plot box aspect ratio to be [1 1 1] as well.
2-56
pbaspect
pbaspect([1 1 1])
2 1.5 1 0.5 0 -0.5 -1 -1.5 -2 2 1 0 0 -1 -2 -2 -1 1 2
Notice how MATLAB changed the axes limits because of the constraints introduced by specifying both the plot box and data aspect ratios. You can also use pbaspect to disable stretch-to-fill. For example, displaying two subplots in one figure can give surface plots a squashed appearance. Disabling stretch-to-fill.
upper_plot = subplot(211); surf(x,y,z) lower_plot = subplot(212); surf(x,y,z) pbaspect(upper_plot,'manual')
2-57
pbaspect
0.5
0
-0.5 2 0 -2 -2 2 0
0.5
0
-0.5 2 1 0 -1 -2 -2 -1 0 1 2
See Also
axis, daspect, xlim, ylim, zlim
The axes properties DataAspectRatio, PlotBoxAspectRatio, XLim, YLim, ZLim The "Aspect Ratio" section in the Using MATLAB Graphics manual.
2-58
pcg
Purpose Syntax
2pcg
Preconditioned Conjugate Gradients method
x = pcg(A,b) pcg(A,b,tol) pcg(A,b,tol,maxit) pcg(A,b,tol,maxit,M) pcg(A,b,tol,maxit,M1,M2) pcg(A,b,tol,maxit,M1,M2,x0) pcg(A,b,tol,maxit,M1,M2,x0,p1,p2,...) [x,flag] = pcg(A,b,tol,maxit,M1,M2,x0,p1,p2,...) [x,flag,relres] = pcg(A,b,tol,maxit,M1,M2,x0,p1,p2,...) [x,flag,relres,iter] = pcg(A,b,tol,maxit,M1,M2,x0,p1,p2,...) [x,flag,relres,iter,resvec] = pcg(A,b,tol,maxit,M1,M2,x0,p1,p2,...) x = pcg(A,b) attempts to solve the system of linear equations A*x=b for x. The n-by-n coefficient matrix A must be symmetric and positive definite, and should also 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.
Description
If pcg converges, a message to that effect is displayed. If pcg 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.
pcg(A,b,tol) specifies the tolerance of the method. If tol is [], then pcg uses the default, 1e-6. pcg(A,b,tol,maxit) specifies the maximum number of iterations. If maxit is [], then pcg uses the default, min(n,20). pcg(A,b,tol,maxit,M) and pcg(A,b,tol,maxit,M1,M2) use symmetric positive definite preconditioner M or M = M1*M2 and effectively solve the system inv(M)*A*x = inv(M)*b for x. If M is [] then pcg applies no preconditioner. M can be a function that returns M\x. pcg(A,b,tol,maxit,M1,M2,x0) specifies the initial guess. If x0 is [], then pcg
uses the default, an all-zero vector.
2-59
pcg
pcg(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] = pcg(A,b,tol,maxit,M1,M2,x0) also returns a convergence flag. Flag 0 Convergence pcg converged to the desired tolerance tol within maxit
iterations.
1 2 3 4 pcg iterated maxit times but did not converge.
Preconditioner M was ill-conditioned.
pcg stagnated. (Two consecutive iterates were the same.)
One of the scalar quantities calculated during pcg 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] = pcg(A,b,tol,maxit,M1,M2,x0) also returns the relative residual norm(b-A*x)/norm(b). If flag is 0, relres <= tol. [x,flag,relres,iter] = pcg(A,b,tol,maxit,M1,M2,x0) also returns the iteration number at which x was computed, where 0 <= iter <= maxit. [x,flag,relres,iter,resvec] = pcg(A,b,tol,maxit,M1,M2,x0) 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; M = diag([10:-1:1 1 1:10]);
2-60
pcg
[x,flag,rr,iter,rv] = pcg(A,b,tol,maxit,M);
Alternatively, use this one-line 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 one-line preconditioner backsolve function
function y = mfun(r,n) y = r ./ [((n-1)/2:-1:1)'; 1; (1:(n-1)/2)'];
as inputs to pcg
[x1,flag1,rr1,iter1,rv1] = pcg(@afun,b,tol,maxit,@mfun,... [],[],21);
Example 2.
A = delsq(numgrid('C',25)); b = ones(length(A),1); [x,flag] = pcg(A,b) flag is 1 because pcg does not converge to the default tolerance of 1e-6 within
the default 20 iterations.
R = cholinc(A,1e-3); [x2,flag2,relres2,iter2,resvec2] = pcg(A,b,1e-8,10,R',R) flag2 is 0 because pcg converges to the tolerance of 1.2e-9 (the value of relres2) at the sixth iteration (the value of iter2) when preconditioned by the incomplete Cholesky factorization with a drop tolerance of 1e-3. resvec2(1) = norm(b) and resvec2(7) = norm(b-A*x2). You can follow the progress of pcg by plotting the relative residuals at each iteration starting from
the initial estimate (iterate number 0).
semilogy(0:iter2,resvec2/norm(b),'-o') xlabel('iteration number') ylabel('relative residual')
2-61
pcg
10
0
10
-1
10
-2
10 relative residual
-3
10
-4
10
-5
10
-6
10
-7
10
-8
10
-9
0
1
2
3 iteration number
4
5
6
See Also
bicg, bicgstab, cgs, cholinc, gmres, lsqr, minres, 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-62
pchip
Purpose Syntax Description
2pchip
Piecewise Cubic Hermite Interpolating Polynomial (PCHIP)
yi = pchip(x,y,xi) pp = pchip(x,y) yi = pchip(x,y,xi) returns vector yi containing elements corresponding to the elements of xi and determined by piecewise cubic interpolation within vectors x and y. The vector x specifies the points at which the data y is given. If y is a matrix, then the interpolation is performed for each column of y and yi is length(xi)-by-size(y,2). pp = pchip(x,y) returns a piecewise polynomial structure for use by ppval. x can be a row or column vector. y is a row or column vector of the same length as x, or a matrix with length(x) columns. pchip finds values of an underlying interpolating function P ( x ) at
intermediate points, such that: On each subinterval x k x x k + 1 , P ( x ) is the cubic Hermite interpolant to the given values and certain slopes at the two endpoints. P ( x ) interpolates y , i.e., P ( x j ) = y j, and the first derivative P ( x ) is continuous. P ( x ) is probably not continuous; there may be jumps at the x j . The slopes at the x j are chosen in such a way that P ( x ) preserves the shape of the data and respects monotonicity. This means that, on intervals where the data are monotonic, so is P ( x ) ; at points where the data has a local extremum, so does P ( x ) . Note If y is a matrix, P ( x ) satisfies the above for each column of y .
Remarks
spline constructs S ( x ) in almost the same way pchip constructs P ( x ) . However, spline chooses the slopes at the x j differently, namely to make even
S ( x ) continuous. This has the following effects:
spline produces a smoother result, i.e. S ( x ) is continuous. spline produces a more accurate result if the data consists of values of a smooth function.
2-63
pchip
pchip has no overshoots and less oscillation if the data are not smooth. pchip is less expensive to set up. The two are equally expensive to evaluate.
Examples
x = -3:3; y = [-1 -1 -1 0 1 1 1]; t = -3:.01:3; p = pchip(x,y,t); s = spline(x,y,t); plot(x,y,'o',t,p,'-',t,s,'-.') legend('data','pchip','spline',4)
1.5
1
0.5
0
-0.5
-1
data pchip spline
-1.5 -3
-2
-1
0
1
2
3
See Also References
interp1, spline, ppval
[1] Fritsch, F. N. and R. E. Carlson, "Monotone Piecewise Cubic Interpolation," SIAM J. Numerical Analysis, Vol. 17, 1980, pp.238-246. [2] Kahaner, David, Cleve Moler, Stephen Nash, Numerical Methods and Software, Prentice Hall, 1988.
2-64
pcode
Purpose Syntax
2pcode
Create preparsed pseudocode file (P-file)
pcode fun pcode *.m pcode fun1 fun2 ... pcode... -inplace pcode fun parses the M-file fun.m into the P-file fun.p and puts it into the current directory. The original M-file can be anywhere on the search path. pcode *.m creates P-files for all the M-files in the current directory. pcode fun1 fun2 ... creates P-files for the listed functions. pcode... -inplace creates P-files in the same directory as the M-files. An
Description
error occurs if the files can't be created.
2-65
pcolor
Purpose Syntax
2pcolor
Pseudocolor plot
pcolor(C) pcolor(X,Y,C) h = pcolor(...)
Description
A pseudocolor plot is a rectangular array of cells with colors determined by C. MATLAB creates a pseudocolor plot by using each set of four adjacent points in C to define a surface patch (i.e., cell).
pcolor(C) draws a pseudocolor plot. The elements of C are linearly mapped to an index into the current colormap. The mapping from C to the current colormap is defined by colormap and caxis. pcolor(X,Y,C) draws a pseudocolor plot of the elements of C at the locations specified by X and Y. The plot is a logically rectangular, two-dimensional grid with vertices at the points [X(i,j), Y(i,j)]. X and Y are vectors or matrices that specify the spacing of the grid lines. If X and Y are vectors, X corresponds to the columns of C and Y corresponds to the rows. If X and Y are matrices, they must be the same size as C. h = pcolor(...) returns a handle to a surface graphics object.
Remarks
A pseudocolor plot is a flat surface plot viewed from above. pcolor(X,Y,C) is the same as viewing surf(X,Y,0*Z,C) using view([0 90]). When you use shading faceted or shading flat, the constant color of each cell is the color associated with the corner having the smallest x-y coordinates. Therefore, C(i,j) determines the color of the cell in the ith row and jth column. The last row and column of C are not used. When you use shading interp, each cell's color results from a bilinear interpolation of the colors at its four vertices and all elements of C are used.
Examples
A Hadamard matrix has elements that are +1 and 1. A colormap with only two entries is appropriate when displaying a pseudocolor plot of this matrix.
pcolor(hadamard(20)) colormap(gray(2)) axis ij
2-66
pcolor
axis square
2 4 6 8 10 12 14 16 18 20
2
4
6
8
10
12
14
16
18
20
A simple color wheel illustrates a polar coordinate system.
n = 6; r = (0:n)'/n; theta = pi*(n:n)/n; X = r*cos(theta); Y = r*sin(theta); C = r*cos(2theta); pcolor(X,Y,C)
2-67
pcolor
axis equal tight
1 0.8 0.6 0.4 0.2 0 -0.2 -0.4 -0.6 -0.8 -1 -1
-0.5
0
0.5
1
Algorithm
The number of vertex colors for pcolor(C) is the same as the number of cells for image(C). pcolor differs from image in that pcolor(C) specifies the colors of vertices, which are scaled to fit the colormap; changing the axes clim property changes this color mapping. image(C) specifies the colors of cells and directly indexes into the colormap without scaling. Additionally, pcolor(X,Y,C) can produce parametric grids, which is not possible with image.
caxis, image, mesh, shading, surf, view
See Also
2-68
pdepe
Purpose Syntax
2pdepe
Solve initial-boundary value problems for systems of parabolic and elliptic partial differential equations (PDEs) in one space variable and time
sol = pdepe(m,pdefun,icfun,bcfun,xmesh,tspan) sol = pdepe(m,pdefun,icfun,bcfun,xmesh,tspan,options) sol = pdepe(m,pdefun,icfun,bcfun,xmesh,tspan,options,p1,p2...) m pdefun icfun bcfun xmesh
Arguments
A parameter corresponding to the symmetry of the problem. m can be slab = 0, cylindrical = 1, or spherical = 2. A function that defines the components of the PDE. A function that defines the initial conditions. A function that defines the boundary conditions. A vector [x0, x1, ..., xn] specifying the points at which a numerical solution is requested for every value in tspan. The elements of xmesh must satisfy x0 < x1 < ... < xn. The length of xmesh must be >= 3. A vector [t0, t1, ..., tf] specifying the points at which a solution is requested for every value in xmesh. The elements of tspan must satisfy t0 < t1 < ... < tf. The length of tspan must be >= 3. Some options of the underlying ODE solver are available in pdepe: RelTol, AbsTol, NormControl, InitialStep, and MaxStep. In most cases, default values for these options provide satisfactory solutions. See odeset for details.
tspan
options
p1,p2,... Optional parameters to be passed to pdefun, icfun, and bcfun.
Description
sol = pdepe(m,pdefun,icfun,bcfun,xmesh,tspan) solves initial-boundary value problems for systems of parabolic and elliptic PDEs in the one space variable x and time t . The ordinary differential equations (ODEs) resulting from discretization in space are integrated to obtain approximate solutions at times specified in tspan. The pdepe function returns values of the solution on a mesh provided in xmesh.
2-69
pdepe
pdepe solves PDEs of the form:
u u u u m m ------ x f x, t, u, ------ + s x, t, u, ------ c x, t, u, ------ ------ = x t x x x x
(2-1)
The PDEs hold for t 0 t t f and a x b . The interval [ a, b ] must be finite. m can be 0, 1, or 2, corresponding to slab, cylindrical, or spherical symmetry, respectively. If m > 0 , then a must be >= 0. In Equation 2-1, f ( x, t, u, u / x) is a flux term and s( x, t, u, u / x) is a source term. The coupling of the partial derivatives with respect to time is restricted to multiplication by a diagonal matrix c( x, t, u, u / x) . The diagonal elements of this matrix are either identically zero or positive. An element that is identically zero corresponds to an elliptic equation and otherwise to a parabolic equation. There must be at least one parabolic equation. An element of c that corresponds to a parabolic equation can vanish at isolated values of x if those values of x are mesh points. Discontinuities in c and/or s due to material interfaces are permitted provided that a mesh point is placed at each interface. For t = t 0 and all x , the solution components satisfy initial conditions of the form u ( x, t 0 ) = u 0 ( x ) For all t and either x = a or x = b , the solution components satisfy a boundary condition of the form
(2-2)
u p ( x, t, u ) + q ( x, t ) f x, t, u, ------ = 0 x
(2-3)
Elements of q are either identically zero or never zero. Note that the boundary conditions are expressed in terms of the flux f rather than u / x . Also, of the two coefficients, only p can depend on u . In the call sol = pdepe(m,pdefun,icfun,bcfun,xmesh,tspan): m corresponds to m . xmesh(1) and xmesh(end) correspond to a and b . tspan(1) and tspan(end) correspond to t 0 and t f .
2-70
pdepe
pdefun computes the terms c , f , and s (Equation 2-1). It has the form
[c,f,s] = pdefun(x,t,u,dudx)
The input arguments are scalars x and t and vectors u and dudx that approximate the solution u and its partial derivative with respect to x , respectively. c, f, and s are column vectors. c stores the diagonal elements of the matrix c (Equation 2-1). icfun evaluates the initial conditions. It has the form
u = icfun(x)
When called with an argument x, icfun evaluates and returns the initial values of the solution components at x in the column vector u. bcfun evaluates the terms p and q of the boundary conditions (Equation 2-3). It has the form
[pl,ql,pr,qr] = bcfun(xl,ul,xr,ur,t) ul is the approximate solution at the left boundary xl = a and ur is the approximate solution at the right boundary xr = b . pl and ql are column vectors corresponding to p and q evaluated at xl, similarly pr and qr correspond to xr. When m > 0 and a = 0 , boundedness of the solution near x = 0 requires that the flux f vanish at a = 0 . pdepe imposes this boundary condition automatically and it ignores values returned in pl and ql. pdepe returns the solution as a multidimensional array sol. u i = ui = sol(:,:,i) is an approximation to the ith component of the solution vector u . The element ui(j,k) = sol(j,k,i) approximates u i at ( t, x ) = (tspan(j),xmesh(k)). ui = sol(j,:,i) approximates component i of the solution at time tspan(j) and mesh points xmesh(:). Use pdeval to compute the approximation and its partial derivative u i / x at points not included in xmesh. See pdeval for
details.
sol = pdepe(m,pdefun,icfun,bcfun,xmesh,tspan,options) solves as above with default integration parameters replaced by values in options, an argument created with the odeset function. Only some of the options of the underlying ODE solver are available in pdepe: RelTol, AbsTol, NormControl,
2-71
pdepe
InitialStep, and MaxStep. The defaults obtained by leaving off the input argument options will generally be satisfactory. See odeset for details. sol = pdepe(m,pdefun,icfun,bcfun,xmesh,tspan,options,p1,p2...) passes the additional parameters p1, p2, ... to the functions pdefun, icfun, and bcfun. Use options = [] as a placeholder if no options are set.
Remarks
The arrays xmesh and tspan play different roles in pdepe.
tspan The pdepe function performs the time integration with an ODE
solver that selects both the time step and formula dynamically. The elements of tspan merely specify where you want answers and the cost depends weakly on the length of tspan.
xmesh Second order approximations to the solution are made on the mesh specified in xmesh. Generally, it is best to use closely spaced mesh points where the solution changes rapidly. pdepe does not select the mesh in x automatically. You must provide an appropriate fixed mesh in xmesh. The cost depends strongly on the length of xmesh. When m > 0 , it is not necessary
to use a fine mesh near x = 0 to account for the coordinate singularity. The time integration is done with ode15s. pdepe exploits the capabilities of ode15s for solving the differential-algebraic equations that arise when Equation 2-1 contains elliptic equations, and for handling Jacobians with a specified sparsity pattern. After discretization, elliptic equations give rise to algebraic equations. If the elements of the initial conditions vector that correspond to elliptic equations are not "consistent" with the discretization, pdepe tries to adjust them before beginning the time integration. For this reason, the solution returned for the initial time may have a discretization error comparable to that at any other time. If the mesh is sufficiently fine, pdepe can find consistent initial conditions close to the given ones. If pdepe displays a message that it has difficulty finding consistent initial conditions, try refining the mesh. No adjustment is necessary for elements of the initial conditions vector that correspond to parabolic equations.
2-72
pdepe
Examples
Example 1. This example illustrates the straightforward formulation,
computation, and plotting of the solution of a single PDE. u 2 u ------ = ----- ------ t x x This equation holds on an interval 0 x 1 for times t 0 . The PDE satisfies the initial condition u ( x, 0 ) = sin x and boundary conditions u ( 0, t ) 0 t u e + ------ ( 1, t ) = 0 x It is convenient to use subfunctions to place all the functions required by pdepe in a single M-file.
function pdex1 m = 0; x = linspace(0,1,20); t = linspace(0,2,5); sol = pdepe(m,@pdex1pde,@pdex1ic,@pdex1bc,x,t); % Extract the first solution component as u. u = sol(:,:,1); % A surface plot is often a good way to study a solution. surf(x,t,u) title('Numerical solution computed with 20 mesh points.') xlabel('Distance x') ylabel('Time t') % A solution profile can also be illuminating. figure plot(x,u(end,:)) title('Solution at t = 2') xlabel('Distance x')
2-73
pdepe
ylabel('u(x,2)') % -------------------------------------------------------------function [c,f,s] = pdex1pde(x,t,u,DuDx) c = pi^2; f = DuDx; s = 0; % -------------------------------------------------------------function u0 = pdex1ic(x) u0 = sin(pi*x); % -------------------------------------------------------------function [pl,ql,pr,qr] = pdex1bc(xl,ul,xr,ur,t) pl = ul; ql = 0; pr = pi * exp(-t); qr = 1;
In this example, the PDE, initial condition, and boundary conditions are coded in subfunctions pdex1pde, pdex1ic, and pdex1bc. The surface plot shows the behavior of the solution.
Numerical solution computed with 20 mesh points.
1
0.8
0.6
0.4
0.2
0 2 1.5 1 0.5 0.2 Time t 0 0 Distance x 0.4 0.8 0.6 1
2-74
pdepe
The following plot shows the solution profile at the final value of t (i.e., t = 2).
Solution at t = 2 0.14
0.12
0.1
0.08
u(x,2)
0.06
0.04
0.02
0
-0.02
0
0.1
0.2
0.3
0.4
0.5 Distance x
0.6
0.7
0.8
0.9
1
Example 2. This example illustrates the solution of a system of PDEs. The
problem has boundary layers at both ends of the interval. The solution changes rapidly for small t . The PDEs are u1 u 1 --------- = 0.024 ----------- F (u 1 u 2) 2 t x u2 u 2 --------- = 0.170 ----------- + F (u 1 u 2) 2 t x where F ( y ) = exp(5.73 y) exp( 11.46 y) . This equation holds on an interval 0 x 1 for times t 0 .
2 2
2-75
pdepe
The PDE satisfies the initial conditions u 1 ( x, 0 ) 1 u 2 ( x, 0 ) 0 and boundary conditions u 1 --------- ( 0, t ) 0 x u 2(0, t) 0 u 1(1, t) 1 u 2 --------- ( 1, t ) 0 x In the form expected by pdepe, the equations are F ( u1 u2 ) u 0.024 ( u 1 / x ) + . ---- 1 = ----t u x 0.170 ( u / x ) F ( u1 u2 ) 1 2 2 1 The boundary conditions on the partial derivatives of u have to be written in terms of the flux. In the form expected by pdepe, the left boundary condition is 0.024 ( u 1 / x ) 0 1 0 + = . u2 0.170 ( u 2 / x ) 0 0 and the right boundary condition is u1 1 0 0 1 0.024 ( u 1 / x ) 0.170 ( u 2 / x ) 0 0
+
.
=
The solution changes rapidly for small t . The program selects the step size in time to resolve this sharp change, but to see this behavior in the plots, the example must select the output times accordingly. There are boundary layers in the solution at both ends of [0,1], so the example places mesh points near 0 and 1 to resolve these sharp changes. Often some experimentation is needed to select a mesh that reveals the behavior of the solution.
2-76
pdepe
function pdex4 m = 0; x = [0 0.005 0.01 0.05 0.1 0.2 0.5 0.7 0.9 0.95 0.99 0.995 1]; t = [0 0.005 0.01 0.05 0.1 0.5 1 1.5 2]; sol = pdepe(m,@pdex4pde,@pdex4ic,@pdex4bc,x,t); u1 = sol(:,:,1); u2 = sol(:,:,2); figure surf(x,t,u1) title('u1(x,t)') xlabel('Distance x') ylabel('Time t') figure surf(x,t,u2) title('u2(x,t)') xlabel('Distance x') ylabel('Time t') % -------------------------------------------------------------function [c,f,s] = pdex4pde(x,t,u,DuDx) c = [1; 1]; f = [0.024; 0.17] .* DuDx; y = u(1) - u(2); F = exp(5.73*y)-exp(-11.47*y); s = [-F; F]; % -------------------------------------------------------------function u0 = pdex4ic(x); u0 = [1; 0]; % -------------------------------------------------------------function [pl,ql,pr,qr] = pdex4bc(xl,ul,xr,ur,t) pl = [0; ul(2)]; ql = [1; 0]; pr = [ur(1)-1; 0]; qr = [0; 1];
In this example, the PDEs, intial conditions, and boundary conditions are coded in subfunctions pdex4pde, pdex4ic, and pdex4bc.
2-77
pdepe
The surface plots show the behavior of the solution components.
u1(x,t)
1
0.8
0.6
0.4
0.2
0 2 1.5 1 0.5 0.2 Time t 0 0 Distance x 0.4 0.8 0.6 1
u2(x,t)
0.8 0.7 0.6 0.5 0.4 0.3 0.2 0.1 0 2 1.5 1 0.5 0.2 Time t 0 0 Distance x 0.4 0.8 0.6 1
2-78
pdepe
See Also References
function_handle, pdeval, ode15s, odeset, odeget
[1] Skeel, R. D. and M. Berzins, "A Method for the Spatial Discretization of Parabolic Equations in One Space Variable," SIAM Journal on Scientific and Statistical Computing, Vol. 11, 1990, pp.1-32.
2-79
pdeval
Purpose Syntax Arguments
2pdeval
Evaluate the numerical solution of a PDE using the output of pdepe
[uout,duoutdx] = pdeval(m,xmesh,ui,xout) m xmesh
Symmetry of the problem: slab = 0, cylindrical = 1, spherical = 2. This is the first input argument used in the call to pdepe. A vector [x0, x1, ..., xn] specifying the points at which the elements of ui were computed. This is the same vector with which pdepe was called. A vector sol(j,:,i) that approximates component i of the solution at time t f and mesh points xmesh, where sol is the solution returned by pdepe. A vector of points from the interval [x0,xn] at which the interpolated solution is requested.
ui
xout
Description
[uout,duoutdx] = pdeval(m,x,ui,xout) approximates the solution u and i its partial derivative u i / x at points from the interval [x0,xn]. The pdeval function returns the computed values in uout and duoutdx, respectively.
Note pdeval evaluates the partial derivative u i / x rather than the flux f . Although the flux is continuous, the partial derivative may have a jump at a material interface.
See Also
pdepe
2-80
peaks
Purpose Syntax
2peaks
A sample function of two variables.
Z Z Z Z = = = = peaks; peaks(n); peaks(V); peaks(X,Y);
peaks; peaks(N); peaks(V); peaks(X,Y); [X,Y,Z] = peaks; [X,Y,Z] = peaks(n); [X,Y,Z] = peaks(V);
Description
peaks is a function of two variables, obtained by translating and scaling Gaussian distributions, which is useful for demonstrating mesh, surf, pcolor, contour, and so on. Z = peaks; returns a 49-by-49 matrix. Z = peaks(n); returns an n-by-n matrix. Z = peaks(V); returns an n-by-n matrix, where n = length(V). Z = peaks(X,Y); evaluates peaks at the given X and Y (which must be the same size) and returns a matrix the same size. peaks(...) (with no output argument) plots the peaks function with surf. [X,Y,Z] = peaks(...); returns two additional matrices, X and Y, for parametric plots, for example, surf(X,Y,Z,del2(Z)). If not given as input, the underlying matrices X and Y are: [X,Y] = meshgrid(V,V)
where V is a given vector, or V is a vector of length n with elements equally spaced from -3 to 3. If no input argument is given, the default n is 49.
See Also
meshgrid, surf
2-81
perl
Purpose Syntax
2perl
Call Perl script using appropriate operating system executable
perl('perlfile') perl('perlfile',arg1,arg2,...) result = perl(...) perl('perlfile') calls the Perl script perlfile, using the appropriate
Description
operating system Perl executable.
perl('perlfile',arg1,arg2,...) calls the Perl script perlfile, using the appropriate operating system Perl executable and passes the arguments arg1, arg2, and so on, to perlfile. result = perl(...) returns the results of attempted Perl call to result.
See Also
! (exclamation point), dos, system, unix
2-82
perms
Purpose Syntax Description
2perms
All possible permutations
P = perms(v) P = perms(v), where v is a row vector of length n, creates a matrix whose rows consist of all possible permutations of the n elements of v. Matrix P contains n! rows and n columns.
Examples
The command perms(2:2:6) returns all the permutations of the numbers 2, 4, and 6:
2 2 4 4 6 6 4 6 2 6 4 2 6 4 6 2 2 4
Limitations See Also
This function is only practical for situations where n is less than about 15.
nchoosek, permute, randperm
2-83
permute
Purpose Syntax Description
2permute
Rearrange the dimensions of a multidimensional array
B = permute(A,order) B = permute(A,order) rearranges the dimensions of A so that they are in the order specified by the vector order. B has the same values of A but the order of
the subscripts needed to access any particular element is rearranged as specified by order. All the elements of order must be unique.
Remarks Examples
permute and ipermute are a generalization of transpose (.') for
multidimensional arrays. Given any matrix A, the statement
permute(A,[2 1])
is the same as A'. For example:
A = [1 2; 3 4]; permute(A,[2 1]) ans = 1 3 2 4
The following code permutes a three-dimensional array:
X = rand(12,13,14); Y = permute(X,[2 3 1]); size(Y) ans = 13 14 12
See Also
ipermute
2-84
persistent
Purpose Syntax Description
2persistent
Define persistent variable
persistent X Y Z persistent X Y Z defines X, Y, and Z as variables that are local to the function in which they are declared yet their values are retained in memory between calls to the function. Persistent variables are similar to global variables because MATLAB creates permanent storage for both. They differ from global variables in that persistent variables are known only to the function in which they are declared. This prevents persistent variables from being changed by other functions or from the MATLAB command line.
Persistent variables are cleared when the M-file is cleared from memory or when the M-file is changed. To keep an M-file in memory until MATLAB quits, use mlock. If the persistent variable does not exist the first time you issue the persistent statement, it is initialized to the empty matrix. It is an error to declare a variable persistent if a variable with the same name exists in the current workspace.
Remarks See Also
There is no function form of the persistent command (i.e., you cannot use parentheses and quote the variable names).
clear, global, mislocked, mlock, munlock
2-85
pi
Purpose Syntax Description Examples
Ratio of a circle's circumference to its diameter,
2pi
pi pi returns the floating-point number nearest the value of . The expressions 4*atan(1) and imag(log(-1)) provide the same value.
The expression sin(pi) is not exactly zero because pi is not exactly .
sin(pi) ans = 1.2246e-16
See Also
ans, eps, i, Inf, j, NaN
2-86
pie
Purpose Syntax
2pie
Pie chart
pie(X) pie(X,explode) h = pie(...) pie(X) draws a pie chart using the data in X. Each element in X is represented
Description
as a slice in the pie chart.
pie(X,explode) offsets a slice from the pie. explode is a vector or matrix of zeros and nonzeros that correspond to X. A non-zero value offsets the corresponding slice from the center of the pie chart, so that X(i,j) is offset from the center if explode(i,j) is nonzero. explode must be the same size as X. h = pie(...) returns a vector of handles to patch and text graphics objects.
Remarks
The values in X are normalized via X/sum(X) to determine the area of each slice of the pie. If sum(X)1, the values in X directly specify the are of the pie slices. MATLAB draws only a partial pie if sum(X)<1. Emphasize the second slice in the chart by setting its corresponding explode element to 1.
x = [1 3 0.5 2.5 2]; explode = [0 1 0 0 0]; pie(x,explode)
Examples
2-87
pie
colormap jet
11% 22%
33%
28%
6%
See Also
pie3
2-88
pie3
Purpose Syntax
2pie3
Three-dimensional pie chart
pie3(X) pie3(X,explode) h = pie3(...) pie3(X) draws a three-dimensional pie chart using the data in X. Each element in X is represented as a slice in the pie chart. pie3(X,explode) specifies whether to offset a slice from the center of the pie chart. X(i,j) is offset from the center of the pie chart if explode(i,j) is nonzero. explode must be the same size as X. h = pie(...) returns a vector of handles to patch, surface, and text graphics
Description
objects.
Remarks
The values in X are normalized via X/sum(X) to determine the area of each slice of the pie. If sum(X)1, the values in X directly specify the area of the pie slices. MATLAB draws only a partial pie if sum(X)<1. Offset a slice in the pie chart by setting the corresponding explode element to 1:
x = [1 3 0.5 2.5 2] explode = [0 1 0 0 0] pie3(x,explode) colormap hsv
22% 11%
Examples
28%
33%
6%
2-89
pie3
See Also
pie
2-90
pinv
Purpose Syntax Definition
2pinv
Moore-Penrose pseudoinverse of a matrix
B = pinv(A) B = pinv(A,tol)
The Moore-Penrose pseudoinverse is a matrix B of the same dimensions as A' satisfying four conditions:
A*B*A B*A*B A*B is B*A is = A = B
Hermitian Hermitian
The computation is based on svd(A) and any singular values less than tol are treated as zero.
Description
B = pinv(A) returns the Moore-Penrose pseudoinverse of A. B = pinv(A,tol) returns the Moore-Penrose pseudoinverse and overrides the default tolerance, max(size(A))*norm(A)*eps.
Examples
If A is square and not singular, then pinv(A) is an expensive way to compute inv(A). If A is not square, or is square and singular, then inv(A) does not exist. In these cases, pinv(A) has some of, but not all, the properties of inv(A). If A has more rows than columns and is not of full rank, then the overdetermined least squares problem minimize norm(A*x-b) does not have a unique solution. Two of the infinitely many solutions are
x = pinv(A)*b
and
y = A\b
These two are distinguished by the facts that norm(x) is smaller than the norm of any other solution and that y has the fewest possible nonzero components. For example, the matrix generated by
2-91
pinv
A = magic(8); A = A(:,1:6)
is an 8-by-6 matrix that happens to have rank(A) = 3.
A = 64 9 17 40 32 41 49 8 2 55 47 26 34 23 15 58 3 54 46 27 35 22 14 59 61 12 20 37 29 44 52 5 60 13 21 36 28 45 53 4 6 51 43 30 38 19 11 62
The right-hand side is b = 260*ones(8,1),
b = 260 260 260 260 260 260 260 260
The scale factor 260 is the 8-by-8 magic sum. With all eight columns, one solution to A*x = b would be a vector of all 1's. With only six columns, the equations are still consistent, so a solution exists, but it is not all 1's. Since the matrix is rank deficient, there are infinitely many solutions. Two of them are
x = pinv(A)*b
which is
x = 1.1538 1.4615 1.3846 1.3846 1.4615 1.1538
2-92
pinv
and
y = A\b
which produces this result.
Warning: Rank deficient, rank = 3 y = 4.0000 5.0000 0 0 0 -1.0000 tol = 1.8829e-013.
Both of these are exact solutions in the sense that norm(Ax-b) and norm(Ay-b) are on the order of roundoff error. The solution x is special because
norm(x) = 3.2817
is smaller than the norm of any other solution, including
norm(y) = 6.4807
On the other hand, the solution y is special because it has only three nonzero components.
See Also
inv, qr, rank, svd
2-93
planerot
Purpose Syntax Description Examples
2planerot
Givens plane rotation
[G,y] = planerot(x) [G,y] = planerot(x) where x is a 2-component column vector, returns a 2-by-2 orthogonal matrix G so that y = G*x has y(2) = 0. x = [3 4]; [G,y] = planerot(x') G = 0.6000 -0.8000 y = 5 0 0.8000 0.6000
See Also
qrdelete, qrinsert
2-94
plot
Purpose Syntax
2plot
Linear 2D plot
plot(Y) plot(X1,Y1,...) plot(X1,Y1,LineSpec,...) plot(...,'PropertyName',PropertyValue,...) h = plot(...) plot(Y) plots the columns of Y versus their index if Y is a real number. If Y is complex, plot(Y) is equivalent to plot(real(Y),imag(Y)). In all other uses of plot, the imaginary component is ignored. plot(X1,Y1,...) plots all lines defined by Xn versus Yn pairs. If only Xn or Yn
Description
is a matrix, the vector is plotted versus the rows or columns of the matrix, depending on whether the vector's row or column dimension matches the matrix.
plot(X1,Y1,LineSpec,...) plots all lines defined by the Xn,Yn,LineSpec triples, where LineSpec is a line specification that determines line type, marker symbol, and color of the plotted lines. You can mix Xn,Yn,LineSpec triples with Xn,Yn pairs: plot(X1,Y1,X2,Y2,LineSpec,X3,Y3). plot(...,'PropertyName',PropertyValue,...) sets properties to the specified property values for all line graphics objects created by plot. (See the
"Examples" section for examples.)
h = plot(...) returns a column vector of handles to line graphics objects, one
handle per line.
Remarks
If you do not specify a color when plotting more than one line, plot automatically cycles through the colors in the order specified by the current axes ColorOrder property. After cycling through all the colors defined by ColorOrder, plot then cycles through the line styles defined in the axes LineStyleOrder property. Note that, by default, MATLAB resets the ColorOrder and LineStyleOrder properties each time you call plot. If you want changes you make to these properties to persist, then you must define these changes as default values. For example,
2-95
plot
set(0,'DefaultAxesColorOrder',[0 0 0],... 'DefaultAxesLineStyleOrder','-|-.|--|:')
sets the default ColorOrder to use only the color black and sets the LineStyleOrder to use solid, dash-dot, dash-dash, and dotted line styles.
Additional Information
See the "Creating 2-D Graphs" and "Labeling Graphs" in Using MATLAB Graphics for more information on plotting. See LineSpec for more information on specifying line styles and colors.
Examples
Specifying the Color and Size of Markers
You can also specify other line characteristics using graphics properties (see line for a description of these properties): LineWidth specifies the width (in points) of the line. MarkerEdgeColor specifies the color of the marker or the edge color for filled markers (circle, square, diamond, pentagram, hexagram, and the four triangles). MarkerFaceColor specifies the color of the face of filled markers. MarkerSize specifies the size of the marker in units of points. For example, these statements,
x = -pi:pi/10:pi; y = tan(sin(x)) - sin(tan(x)); plot(x,y,'--rs','LineWidth',2,... 'MarkerEdgeColor','k',... 'MarkerFaceColor','g',... 'MarkerSize',10)
2-96
plot
produce this graph.
3
2
1
0
-1
-2
-3 -4
-3
-2
-1
0
1
2
3
4
Specifying Tick Mark Location and Labeling
You can adjust the axis tick-mark locations and the labels appearing at each tick. For example, this plot of the sine function relabels the x-axis with more meaningful values,
x = -pi:.1:pi; y = sin(x); plot(x,y) set(gca,'XTick',-pi:pi/2:pi) set(gca,'XTickLabel',{'-pi','-pi/2','0','pi/2','pi'})
2-97
plot
Now add axis labels and annotate the point -pi/4, sin(-pi/4).
1 0.8 0.6 0.4 0.2 0 -0.2 -0.4 -0.6 -0.8 -1
-pi
-pi/2
0
pi/2
pi
Adding Titles, Axis Labels, and Annotations MATLAB enables you to add axis labels and titles. For example, using the graph from the previous example, add an x- and y-axis label,
xlabel('-\pi \leq \Theta \leq \pi') ylabel('sin(\Theta)') title('Plot of sin(\Theta)') text(-pi/4,sin(-pi/4),'\leftarrow sin(-\pi\div4)',... 'HorizontalAlignment','left')
Now change the line color to red by first finding the handle of the line object created by plot and then setting its Color property. In the same statement, set the LineWidth property to 2 points.
set(findobj(gca,'Type','line','Color',[0 0 1]),... 'Color','red',... 'LineWidth',2)
2-98
plot
Plot of sin() 1 0.8 0.6 0.4 0.2 sin() 0 -0.2 -0.4 -0.6 sin(-4) -0.8 -1
-pi
-pi/2
0 -
pi/2
pi
See Also
axis, bar, grid, hold, legend, line, LineSpec, loglog, plotyy, semilogx, semilogy, subplot, title, xlabel, xlim, ylabel, ylim, zlabel, zlim, stem
See the text String property for a list of symbols and how to display them. See the Plot Editor for information on plot annotation tools in the figure window toolbar. See Basic Plots and Graphs for related functions.
2-99
plot3
Purpose Syntax
2plot3
Linear 3-D plot
plot3(X1,Y1,Z1,...) plot3(X1,Y1,Z1,LineSpec,...) plot3(...,'PropertyName',PropertyValue,...) h = plot3(...)
Description
The plot3 function displays a three-dimensional plot of a set of data points.
plot3(X1,Y1,Z1,...), where X1, Y1, Z1 are vectors or matrices, plots one or
more lines in three-dimensional space through the points whose coordinates are the elements of X1, Y1, and Z1.
plot3(X1,Y1,Z1,LineSpec,...) creates and displays all lines defined by the Xn,Yn,Zn,LineSpec quads, where LineSpec is a line specification that
determines line style, marker symbol, and color of the plotted lines.
plot3(...,'PropertyName',PropertyValue,...) sets properties to the specified property values for all Line graphics objects created by plot3. h = plot3(...) returns a column vector of handles to line graphics objects,
with one handle per line.
Remarks
If one or more of X1, Y1, Z1 is a vector, the vectors are plotted versus the rows or columns of the matrix, depending whether the vectors' lengths equal the number of rows or the number of columns. You can mix Xn,Yn,Zn triples with Xn,Yn,Zn,LineSpec quads, for example,
plot3(X1,Y1,Z1,X2,Y2,Z2,LineSpec,X3,Y3,Z3)
See LineSpec and plot for information on line types and markers.
Examples
Plot a three-dimensional helix.
t = 0:pi/50:10pi; plot3(sin(t),cos(t),t) grid on
2-100
plot3
axis square
35 30 25 20 15 10 5 0 1 0.5 0 0 -0.5 -1 -1 -0.5 0.5 1
See Also
axis, bar3, grid, line, LineSpec, loglog, plot, semilogx, semilogy, subplot
2-101
plotedit
Purpose Syntax
2plotedit
Start plot edit mode to allow editing and annotation of plots
plotedit on plotedit off plotedit plotedit('state') plotedit(h) plotedit(h,'state') plotedit on starts plot edit mode for the current figure, allowing you to use a
Description
graphical interface to annotate and edit plots easily. In plot edit mode, you can label axes, chang line styles, and adding text, line, and arrow annotations.
plotedit off ends plot mode for the current figure. plotedit toggles the plot edit mode for the current figure. plotedit(h) toggles the plot edit mode for the figure specified by figure handle h. plotedit('state') specifies the plotedit state for the current figure. Values for state can be as shown. Value for state on off showtoolsmenu hidetoolsmenu Description
Starts plot edit mode Ends plot edit mode Displays the Tools menu in the menu bar Removes the Tools menu from the menu bar
Note hidetoolsmenu is intended for GUI developers who do not want the Tools menu to appear in applications that use the figure window.
plotedit(h,'state') specifies the plotedit state for figure handle h.
2-102
plotedit
Remarks
Plot Editing Mode Graphical Interface Components
Use these toolbar buttons to add text, arrows, and lines.
To start plot edit mode, click this button. Add objects or edit existing objects in the plot through the Edit, Insert, and Tools menus.
Position labels, legends, and other object by clicking and dragging.
Access object-specific plot edit functions through context-sensitive pop-up menus.
Examples
Start plot edit mode for figure 2:
plotedit(2)
End plot edit mode for figure 2:
plotedit(2, 'off')
Hide the Tools menu for the current figure:
plotedit('hidetoolsmenu')
See Also
axes, line, open, plot, print, saveas, text, propedit
2-103
plotmatrix
Purpose Syntax
2plotmatrix
Draw scatter plots
plotmatrix(X,Y) plotmatrix(...,'LineSpec') [H,AX,BigAx,P] = plotmatrix(...) plotmatrix(X,Y) scatter plots the columns of X against the columns of Y. If X is p-by-m and Y is p-by-n, plotmatrix produces an n-by-m matrix of axes. plotmatrix(Y) is the same as plotmatrix(Y,Y) except that the diagonal is replaced by hist(Y(:,i)). plotmatrix(...,'LineSpec') uses a LineSpec to create the scatter plot.The
Description
default is '.' .
[H,AX,BigAx,P] = plotmatrix(...) returns a matrix of handles to the objects created in H, a matrix of handles to the individual subaxes in AX, a handle to a big (invisible) axes that frames the subaxes in BigAx, and a matrix of handles for the histogram plots in P. BigAx is left as the current axes so that a subsequent title, xlabel, or ylabel commands are centered with respect to
the matrix of axes.
Examples
Generate plots of random data.
x = randn(50,3); y = x*[-1 2 1;2 0 1;1 -2 3;]'; plotmatrix(y,'*r')
2-104
plotmatrix
5
0
-5 10 5 0 -5 10 5 0 -5 -10 -5 0 5 -5 0 5 10 -10 -5 0 5 10
See Also
scatter, scatter3
2-105
plotyy
Purpose Syntax
2plotyy
Create graphs with y axes on both left and right side
plotyy(X1,Y1,X2,Y2) plotyy(X1,Y1,X2,Y2,'function') plotyy(X1,Y1,X2,Y2,'function1','function2') [AX,H1,H2] = plotyy(...) plotyy(X1,Y1,X2,Y2) plots X1 versus Y1 with y-axis labeling on the left and plots X2 versus Y2 with y-axis labeling on the right. plotyy(X1,Y1,X2,Y2,'function') uses the plotting function specified by the string 'function' instead of plot to produce each graph. 'function' can be plot, semilogx, semilogy, loglog, stem or any MATLAB function that accepts the syntax: h = function(x,y) plotyy(X1,Y1,X2,Y2,'function1','function2') uses function1(X1,Y1) to plot the data for the left axis and function2(X2,Y2) to plot the data for the
Description
right axis.
[AX,H1,H2] = plotyy(...) returns the handles of the two axes created in AX and the handles of the graphics objects from each plot in H1 and H2. AX(1) is the left axes and AX(2) is the right axes.
Examples
This example graphs two mathematical functions using plot as the plotting function. The two y-axes enable you to display both sets of data on one graph even though relative values of the data are quite different.
x = 0:0.01:20; y1 = 200*exp(-0.05*x).*sin(x); y2 = 0.8*exp(-0.5*x).*sin(10*x); [AX,H1,H2] = plotyy(x,y1,x,y2,'plot');
You can use the handles returned by plotyy to label the axes and set the line styles used for plotting. With the axes handles you can specify the YLabel properties of the left- and right-side y-axis:
set(get(AX(1),'Ylabel'),'String','Left Y-axis') set(get(AX(2),'Ylabel'),'String','Right Y-axis')
Use the xlabel and title commands to label the x-axis and add a title:
2-106
plotyy
xlabel('Zero to 20 \musec.') title('Labeling plotyy')
Use the line handles to set the LineStyle properties of the left- and right-side plots:
set(H1,'LineStyle','--') set(H2,'LineStyle',':')
Labeling plotyy 200 0.8
150
0.6
100
0.4
50 Left Y-axis
0.2 Right Y-axis
0
0
-50
-0.2
-100
-0.4
-150
-0.6
-200
0
5
10 Zero to 20 sec.
15
-0.8 20
See Also
plot, loglog, semilogx, semilogy, axes properties: XAxisLocation, YAxisLocation
The axes chapter in the Using MATLAB Graphics manual for information on multi-axis axes.
2-107
pol2cart
Purpose Syntax Description
2pol2cart
Transform polar or cylindrical coordinates to Cartesian
[X,Y] = pol2cart(THETA,RHO) [X,Y,Z] = pol2cart(THETA,RHO,Z) [X,Y] = pol2cart(THETA,RHO) transforms the polar coordinate data stored in corresponding elements of THETA and RHO to two-dimensional Cartesian, or xy, coordinates. The arrays THETA and RHO must be the same size (or either can be scalar). The values in THETA must be in radians. [X,Y,Z] = pol2cart(THETA,RHO,Z) transforms the cylindrical coordinate data stored in corresponding elements of THETA, RHO, and Z to three-dimensional Cartesian, or xyz, coordinates. The arrays THETA , RHO, and Z must be the same size (or any can be scalar). The values in THETA must be in
radians.
Algorithm
The mapping from polar and cylindrical coordinates to Cartesian coordinates is:
Y
Z P P Y z
rh
o
theta X
rho theta
X Polar to Cartesian Mapping
theta = atan2(y,x) rho = sqrt(x.^2 + y.^2)
Cylindrical to Cartesian Mapping
theta = atan2(y,x) rho = sqrt(x.^2 + y.^2) z = z
See Also
cart2pol, cart2sph, sph2cart
2-108
polar
Purpose Syntax Description
2polar
Plot polar coordinates
polar(theta,rho) polar(theta,rho,LineSpec)
The polar function accepts polar coordinates, plots them in a Cartesian plane, and draws the polar grid on the plane.
polar(theta,rho) creates a polar coordinate plot of the angle theta versus the radius rho. theta is the angle from the x-axis to the radius vector specified in radians; rho is the length of the radius vector specified in dataspace units. polar(theta,rho,LineSpec) LineSpec specifies the line type, plot symbol, and color for the lines drawn in the polar plot.
Examples
Create a simple polar plot using a dashed, red line: t = 0:.01:2pi;
2-109
polar
polar(t,sin(2t).cos(2t),'--r')
90 0.5 120 0.375 60
150
0.25
30
0.125
180
0
210
330
240 270
300
See Also
cart2pol, compass, LineSpec, plot, pol2cart, rose
2-110
poly
Purpose Syntax Description
2poly
Polynomial with specified roots
p = poly(A) p = poly(r) p = poly(A) where A is an n-by-n matrix returns an n+1 element row vector whose elements are the coefficients of the characteristic polynomial, det ( sl A ) . The coefficients are ordered in descending powers: if a vector c has n+1 components, the polynomial it represents is c 1 s n + ... + c n s + c n + 1 p = poly(r) where r is a vector returns a row vector whose elements are the coefficients of the polynomial whose roots are the elements of r.
Remarks
Note the relationship of this command to
r = roots(p)
which returns a column vector whose elements are the roots of the polynomial specified by the coefficients row vector p. For vectors, roots and poly are inverse functions of each other, up to ordering, scaling, and roundoff error.
Examples
MATLAB displays polynomials as row vectors containing the coefficients ordered by descending powers. The characteristic equation of the matrix
A = 1 4 7 2 5 8 3 6 0
is returned in a row vector by poly:
p = poly(A) p = 1 -6 -72 -27
The roots of this polynomial (eigenvalues of matrix A) are returned in a column vector by roots:
r = roots(p)
2-111
poly
r = 12.1229 -5.7345 -0.3884
Algorithm
The algorithms employed for poly and roots illustrate an interesting aspect of the modern approach to eigenvalue computation. poly(A) generates the characteristic polynomial of A, and roots(poly(A)) finds the roots of that polynomial, which are the eigenvalues of A. But both poly and roots use eig, which is based on similarity transformations. The classical approach, which characterizes eigenvalues as roots of the characteristic polynomial, is actually reversed. If A is an n-by-n matrix, poly(A) produces the coefficients c(1) through c(n+1), with c(1) = 1, in det ( I A ) = c 1 n + ... + c n + c n + 1 The algorithm is
z = eig(A); c = zeros(n+1,1); c(1) = 1; for j = 1:n c(2:j+1) = c(2:j+1)-z(j)*c(1:j); end
This recursion is easily derived by expanding the product. ( 1 ) ( 2 )... ( n ) It is possible to prove that poly(A) produces the coefficients in the characteristic polynomial of a matrix within roundoff error of A. This is true even if the eigenvalues of A are badly conditioned. The traditional algorithms for obtaining the characteristic polynomial, which do not use the eigenvalues, do not have such satisfactory numerical properties.
See Also
conv, polyval, residue, roots
2-112
polyarea
Purpose Syntax Description
2polyarea
Area of polygon
A = polyarea(X,Y) A = polyarea(X,Y,dim) A = polyarea(X,Y) returns the area of the polygon specified by the vertices in the vectors X and Y.
If X and Y are matrices of the same size, then polyarea returns the area of polygons defined by the columns X and Y. If X and Y are multidimensional arrays, polyarea returns the area of the polygons in the first nonsingleton dimension of X and Y.
A = polyarea(X,Y,dim) operates along the dimension specified by scalar dim.
Examples
L = linspace(0,2.*pi,6); xv = cos(L)';yv = sin(L)'; xv = [xv ; xv(1)]; yv = [yv ; yv(1)]; A = polyarea(xv,yv); plot(xv,yv); title(['Area = ' num2str(A)]); axis image
Area = 2.3776 0.8 0.6 0.4 0.2 0 -0.2 -0.4 -0.6 -0.8 -0.5 0 0.5 1
See Also
convhull, inpolygon, rectint
2-113
polyder
Purpose Syntax
2polyder
Polynomial derivative
k = polyder(p) k = polyder(a,b) [q,d] = polyder(b,a)
Description
The polyder function calculates the derivative of polynomials, polynomial products, and polynomial quotients. The operands a, b, and p are vectors whose elements are the coefficients of a polynomial in descending powers.
k = polyder(p) returns the derivative of the polynomial p. k = polyder(a,b) returns the derivative of the product of the polynomials a and b. [q,d] = polyder(b,a) returns the numerator q and denominator d of the derivative of the polynomial quotient b/a.
Examples
The derivative of the product ( 3x 2 + 6x + 9 ) ( x 2 + 2x ) is obtained with
a b k k = [3 6 9]; = [1 2 0]; = polyder(a,b) = 12 36 42
18
This result represents the polynomial 12x 3 + 36x 2 + 42x + 18
See Also
conv, deconv
2-114
polyeig
Purpose Syntax Description
2polyeig
Polynomial eigenvalue problem
[X,e] = polyeig(A0,A1,...Ap) e = polyeig(A0,A1,..,Ap) [X,e] = polyeig(A0,A1,...Ap) solves the polynomial eigenvalue problem of degree p
( A 0 + A 1 + ... + P A p )x = 0 where polynomial degree p is a non-negative integer, and A0,A1,...Ap are input matrices of order n. Output matrix X, of size n-by-n*p, contains eigenvectors in its columns. Output vector e, of length n*p, contains eigenvalues. If lambda is the jth eigenvalue in e, and x is the jth column of eigenvectors in X, then (A0 + lambda*A1 + ... + lambda^p*Ap)*x is approximately 0.
e = polyeig(A0,A1,..,Ap) is a vector of length n*p whose elements are the
eigenvalues of the polynomial eigenvalue problem.
Remarks
Based on the values of p and n, polyeig handles several special cases: p = 0, or polyeig(A) is the standard eigenvalue problem: eig(A). p = 1, or polyeig(A,B) is the generalized eigenvalue problem: eig(A,-B). n = 1, or polyeig(a0,a1,...ap) for scalars a0, a1 ..., ap is the standard polynomial problem: roots([ap ... a1 a0]).
Algorithm
If both A0 and Ap are singular, the problem is potentially ill posed; solutions might not exist or they might not be unique. In this case, the computed solutions may be inaccurate. polyeig attempts to detect this situation and display an appropriate warning message. If either one, but not both, of A0 and Ap is singular, the problem is well posed but some of the eigenvalues may be zero or infinite (Inf). The polyeig function uses the QZ factorization to find intermediate results in the computation of generalized eigenvalues. It uses these intermediate results to determine if the eigenvalues are well-determined. See the descriptions of eig and qz for more on this.
2-115
polyeig
See Also
eig, qz
2-116
polyfit
Purpose Syntax
2polyfit
Polynomial curve fitting
p = polyfit(x,y,n) [p,S] = polyfit(x,y,n) [p,S,mu] = polyfit(x,y,n) p = polyfit(x,y,n) finds the coefficients of a polynomial p(x) of degree n that fits the data, p(x(i)) to y(i), in a least squares sense. The result p is a row vector of length n+1 containing the polynomial coefficients in descending
Description
powers p ( x ) = p1 x n + p2 x n 1 + ... + pn x + pn + 1
[p,S] = polyfit(x,y,n) returns the polynomial coefficients p and a structure S for use with polyval to obtain error estimates or predictions. If the errors in the data y are independent normal with constant variance, polyval produces error bounds that contain at least 50% of the predictions. [p,S,mu] = polyfit(x,y,n) finds the coefficients of a polynomial in
x 1 ^ x = -------------2
where 1 = mean (x) and 2 = std (x) . mu is the two-element vector [ 1, 2 ] . This centering and scaling transformation improves the numerical properties of both the polynomial and the fitting algorithm.
Examples
This example involves fitting the error function, erf(x), by a polynomial in x. This is a risky project because erf(x) is a bounded function, while polynomials are unbounded, so the fit might not be very good. First generate a vector of x points, equally spaced in the interval [ 0, 2.5 ] ; then evaluate erf(x) at those points.
x = (0: 0.1: 2.5)'; y = erf(x);
The coefficients in the approximating polynomial of degree 6 are
p = polyfit(x,y,6)
2-117
polyfit
p = 0.0084 -0.0983 0.4217 -0.7435 0.1471 1.1064 0.0004
There are seven coefficients and the polynomial is 0.0084x 0.0983x + 0.4217x 0.7435x + 0.1471x + 1.1064x + 0.0004 To see how good the fit is, evaluate the polynomial at the data points with
f = polyval(p,x);
6 5 4 3 2
A table showing the data, fit, and error is
table = [x y f y-f] table = 0 0.1000 0.2000 0.3000 0.4000 ... 2.1000 2.2000 2.3000 2.4000 2.5000 0 0.1125 0.2227 0.3286 0.4284 0.9970 0.9981 0.9989 0.9993 0.9996 0.0004 0.1119 0.2223 0.3287 0.4288 0.9969 0.9982 0.9991 0.9995 0.9994 -0.0004 0.0006 0.0004 -0.0001 -0.0004 0.0001 -0.0001 -0.0003 -0.0002 0.0002
So, on this interval, the fit is good to between three and four digits. Beyond this interval the graph shows that the polynomial behavior takes over and the approximation quickly deteriorates.
x = (0: 0.1: 5)'; y = erf(x); f = polyval(p,x); plot(x,y,'o',x,f,'-') axis([0 5 0 2])
2-118
polyfit
2 1.8 1.6 1.4 1.2 1 0.8
o o o o o o o o o o o o o o o o o o o o o o o o o o o o o o o o o o o o o o o o o o o o o o o o
0.6 0.4 0.2
o o
0o 0
0.5
1
1.5
2
2.5
3
3.5
4
4.5
5
Algorithm
The polyfit M-file forms the Vandermonde matrix, V , whose elements are powers of x . v i,
j n = xi j
It then uses the backslash operator, \, to solve the least squares problem Vp y You can modify the M-file to use other functions of x as the basis functions.
See Also
poly, polyval, roots
2-119
polyint
Purpose Syntax Description
2polyint
Integrate polynomial analytically
polyint(p,k) polyint(p) polyint(p,k) returns a polynomial representing the integral of polynomial p, using a scalar constant of integration k. polyint(p) assumes a constant of integration k=0.
See Also
polyder, polyval, polyvalm, polyfit
2-120
polyval
Purpose Syntax
2polyval
Polynomial evaluation
y = polyval(p,x) y = polyval(p,x,[],mu) [y,delta] = polyval(p,x,S) [y,delta] = polyval(p,x,S,mu) y = polyval(p,x) returns the value of a polynomial of degree n evaluated at x. The input argument p is a vector of length n+1 whose elements are the
Description
coefficients in descending powers of the polynomial to be evaluated. y = p1 x n + p2 x n 1 + ... + pn x + pn + 1
x can be a matrix or a vector. In either case, polyval evaluates p at each element of x.
^ y = polyval(p,x,[],mu) uses x = ( x 1 ) / 2 in place of x . In this equation, 1 = mean ( x) and 2 = std ( x) . The centering and scaling parameters mu = [ 1, 2 ] are optional output computed by polyfit.
[y,delta] = polyval(p,x,S) and [y,delta] = polyval(p,x,S,mu) use the optional output structure S generated by polyfit to generate error estimates, ydelta. If the errors in the data input to polyfit are independent normal with constant variance, ydelta contains at least 50% of the predictions.
Remarks Examples
The polyvalm(p,x) function, with x a matrix, evaluates the polynomial in a matrix sense. See polyvalm for more information. The polynomial p ( x ) = 3x + 2x + 1 is evaluated at x = 5, 7, and 9 with
p = [3 2 1]; polyval(p,[5 7 9])
2
which results in
ans = 86 162 262
For another example, see polyfit.
2-121
polyval
See Also
polyfit, polyvalm
2-122
polyvalm
Purpose Syntax Description
2polyvalm
Matrix polynomial evaluation
Y = polyvalm(p,X) Y = polyvalm(p,X) evaluates a polynomial in a matrix sense. This is the same as substituting matrix X in the polynomial p.
Polynomial p is a vector whose elements are the coefficients of a polynomial in descending powers, and X must be a square matrix.
Examples
The Pascal matrices are formed from Pascal's triangle of binomial coefficients. Here is the Pascal matrix of order 4.
X = pascal(4) X = 1 1 1 1 2 3 1 3 6 1 4 10
1 4 10 20
Its characteristic polynomial can be generated with the poly function.
p = poly(X) p = 1 -29
72
-29
1
This represents the polynomial x 4 29x 3 + 72x 2 29x + 1 . Pascal matrices have the curious property that the vector of coefficients of the characteristic polynomial is palindromic; it is the same forward and backward. Evaluating this polynomial at each element is not very interesting.
polyval(p,X) ans = 16 16 16 15 16 -140 16 -563
16 -140 -2549 -12089
16 -563 -12089 -43779
But evaluating it in a matrix sense is interesting.
polyvalm(p,X)
2-123
polyvalm
ans = 0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
The result is the zero matrix. This is an instance of the Cayley-Hamilton theorem: a matrix satisfies its own characteristic equation.
See Also
polyfit, polyval
2-124
pow2
Purpose Syntax Description
2pow2
Base 2 power and scale floating-point numbers
X = pow2(Y) X = pow2(F,E) X = pow2(Y) returns an array X whose elements are 2 raised to the power Y. X = pow2(F,E) computes x = f * 2 for corresponding elements of F and E. The result is computed quickly by simply adding E to the floating-point exponent of F. Arguments F and E are real and integer arrays, respectively.
e
Remarks Examples
This function corresponds to the ANSI C function ldexp() and the IEEE floating-point standard function scalbn(). For IEEE arithmetic, the statement X = pow2(F,E) yields the values:
F 1/2 pi/4 -3/4 1/2 1-eps/2 1/2 E 1 2 2 -51 1024 -1021 X 1 pi -3 eps realmax realmin
See Also
log2, exp, hex2num, realmax, realmin
The arithmetic operators ^ and .^
2-125
ppval
Purpose Syntax Description
2ppval
Evaluate piecewise polynomial.
v = ppval(pp,xx) v = ppval(xx,pp) v = ppval(pp,xx) returns the value at the points xx of the piecewise polynomial contained in pp, as constructed by spline or the spline utility mkpp. v = ppval(xx,pp) returns the same result but can be used with functions like fminbnd, fzero and quad that take a function as an argument.
Examples
Compare the results of integrating the function cos
a = 0; b = 10; int1 = quad(@cos,a,b,[],[]) int1 = -0.5440
with the results of integrating the piecewise polynomial pp that approximates the cosine function by interpolating the computed values x and y.
x = a:b; y = cos(x); pp = spline(x,y); int2 = quad(@ppval,a,b,[],[],pp) int2 = -0.5485 int1 provides the integral of the cosine function over the interval [a,b], while int2 provides the integral over the same interval of the piecewise polynomial pp.
See Also
mkpp, spline, unmkpp
2-126
prefdir
Purpose Syntax
2prefdir
Return directory containing preferences, history, and .ini files
prefdir d = prefdir d = prefdir(1) prefdir returns the directory that contains preferences for MATLAB and related products (matlab.prf), the command history (history.m), and the MATLAB initialization file (MATLAB.ini). d = prefdir returns the name of the directory containing preferences and
Description
related files, but does not ensure its existence.
d = prefdir(1) creates a directory for preferences and related files if one does
not exist.
Examples
Run
prefdir
MATLAB returns
ans = C:\WINNT\Profiles\Application Data\MathWorks\MATLAB\R13
Running dir for the directory shows
dir . .. MATLAB.ini cstprefs.mat cwdhistory.m history.m launchpad_cache.txt matlab.prf matlab_help.hst
See Also
"Setting Preferences" in the MATLAB Development Environment documentation
2-127
primes
Purpose Syntax Description Examples
2primes
Generate list of prime numbers
p = primes(n) p = primes(n) returns a row vector of the prime numbers less than or equal to n. A prime number is one that has no factors other than 1 and itself. p = primes(37) p = 2 3 5 7 11 13 17 19 23 29 31 37
See Also
factor
2-128
print, printopt
Purpose Syntax
2print, printopt
Create hardcopy output
print print filename print -ddriver print -dformat print -dformat filename print ... -options [pcmd,dev] = printopt print and printopt produce hardcopy output. All arguments to the print
Description
command are optional. You can use them in any combination or order.
print sends the contents of the current figure, including bitmap
representations of any user interface controls, to the printer using the device and system printing command defined by printopt.
print filename directs the output to the file designated by filename. If filename does not include an extension, print appends an appropriate
extension.
print -ddriver prints the figure using the specified printer driver, (such as color PostScript). If you omit -ddriver, print uses the default value stored in printopt.m. The Printer Driver table lists all supported device types. print -dformat copies the figure to the system clipboard (Windows only). A valid format for this operation is either -dmeta (Windows Enhanced Metafile) or -dbitmap (Windows Bitmap). print -dformat filename exports the figure to the specified file using the specified graphics format, (such as TIFF). The Graphics Format table lists all
supported graphics-file formats.
print -options specifies print options that modify the action of the print command. (For example, the noui option suppresses printing of user interface
controls.) The Options section lists available options.
2-129
print, printopt
print(...) is the function form of print. It enables you to pass variables for
any input arguments. This form is useful passing filenames and handles. See Batch Processing for an example.
[pcmd,dev] = printopt returns strings containing the current system-dependent printing command and output device. printopt is an M-file used by print to produce the hardcopy output. You can edit the M-file printopt.m to set your default printer type and destination. pcmd and dev are platform-dependent strings. pcmd contains the command that print uses to send a file to the printer. dev contains the printer driver or graphics format option for the print command. Their defaults are platform
dependent.
Platform System Printing Command lpr r s COPY /B %s LPT1: Driver or Format dps2 dwin
UNIX Windows
Drivers
The table below shows the complete list of printer drivers supported by MATLAB. If you do not specify a driver, MATLAB uses the default setting shown in the previous table. Some of the drivers are available from a product called Ghostscript, which is shipped with MATLAB. The last column indicates when Ghostscript is used. Some drivers are not available on all platforms. This is noted in the first column of the table.
Printer Driver
PRINT Command Option String -dbj10e -dbj200 -dbjc600 -dbjc800
GhostScript
Canon BubbleJet BJ10e Canon BubbleJet BJ200 color Canon Color BubbleJet BJC-70/BJC-600/BJC-4000 Canon Color BubbleJet BJC-800
Yes Yes Yes Yes
2-130
print, printopt
Printer Driver
PRINT Command Option String -dln03 -depson -deps9high
GhostScript
DEC LN03 Epson and compatible 9- or 24-pin dot matrix print drivers Epson and compatible 9-pin with interleaved lines (triple
Yes Yes Yes Yes Yes Yes Yes Yes Yes
resolution)
Epson LQ-2550 and compatible; color (not supported on
-depsonc
HP-700)
Fujitsu 3400/2400/1200 HP DesignJet 650C color (not supported on Windows or
-depsonc -ddnj650c
DEC Alpha)
HP DeskJet 500 HP DeskJet 500C (creates black-and-white output) HP DeskJet 500C (with 24 bit/pixel color and high-quality Floyd-Steinberg color dithering) (not supported on Windows or DEC Alpha) HP DeskJet 500C/540C color (not supported on Windows or
-ddjet500 -dcdjmono -dcdjcolor
-dcdj500
Yes Yes Yes Yes Yes Yes Yes Yes Yes
DEC Alpha)
HP Deskjet 550C color (not supported on Windows or DEC
-dcdj550
Alpha)
HP DeskJet and DeskJet Plus HP LaserJet HP LaserJet+ HP LaserJet IIP HP LaserJet III HP LaserJet 4.5L and 5P HP LaserJet 5 and 6
-ddeskjet -dlaserjet -dljetplus -dljet2p -dljet3 -dljet4 -dpxlmono
2-131
print, printopt
Printer Driver
PRINT Command Option String -dpaintjet -dpjxl -dpjetxl -dpjxl300
GhostScript
HP PaintJet color HP PaintJet XL color HP PaintJet XL color HP PaintJet XL300 color (not supported on Windows or
Yes Yes Yes Yes No Yes No No No No No No
DEC Alpha)
HPGL for HP 7475A and other compatible plotters.
-dhpgl
(Renderer cannot be set to Z-buffer.)
IBM 9-pin Proprinter PostScript black and white PostScript color PostScript Level 2 black and white PostScript Level 2 color Windows color (Windows only) Windows monochrome (Windows only)
-dibmpro -dps -dpsc -dps2 -dpsc2 -dwinc -dwin
Note Generally, Level 2 PostScript files are smaller and render more quickly when printing than Level 1 PostScript files. However, not all PostScript printers support Level 2, so determine the capabilities of your printer before using those drivers. Level 2 PostScript is the default for UNIX. You can change this default by editing the printopt.m file.
Graphics Format Files
To save your figure as a graphics-format file, specify a format switch and filename. To set the resolution of the output file for a built-in MATLAB format, use the -r switch. (For example, -r300 sets the output resolution to 300 dots per inch.) The -r switch is also supported for Windows Enhanced Metafiles but is not supported for Ghostscript formats.
2-132
print, printopt
The table below shows the supported output formats for exporting from MATLAB and the switch settings to use. In some cases, a format is available both as a MATLAB output filter and as a Ghostscript output filter. The first column indicates this by showing "MATLAB" or "Ghostscript" in parentheses. All formats are supported on both the PC and UNIX platforms.
Graphics Format
Bitmap or Vector
PRINT Command Option String -dbmpmono -dbmp16m -dbmp256
MATLAB or Ghostscript
BMP Monochrome BMP BMP 24-bit BMP BMP 8-bit (256-color) BMP *this format uses a
Bitmap Bitmap Bitmap Bitmap Vector Vector Vector Vector Vector Bitmap Vector Bitmap Bitmap Bitmap Bitmap Bitmap
Ghostscript Ghostscript Ghostscript MATLAB MATLAB MATLAB MATLAB MATLAB MATLAB MATLAB MATLAB MATLAB Ghostscript Ghostscript Ghostscript Ghostscript
fixed colormap
BMP 24-bit EMF EPS black and white EPS color EPS Level 2 black and white EPS Level 2 color HDF 24-bit ILL (Adobe Illustrator) JPEG 24-bit PBM (plain format) 1-bit PBM (raw format) 1-bit PCX 1-bit PCX 24-bit color PCX file format, three 8-bit
-dbmp -dmeta -deps -depsc -deps2 -depsc2 -dhdf -dill -djpeg -dpbm -dpbmraw -dpcxmono -dpcx24b
planes
2-133
print, printopt
Graphics Format
Bitmap or Vector
PRINT Command Option String -dpcx256
MATLAB or Ghostscript
PCX 8-bit Newer color PCX file format
Bitmap Bitmap Bitmap
Ghostscript Ghostscript MATLAB Ghostscript Ghostscript Ghostscript MATLAB Ghostscript Ghostscript MATLAB
(256-color)
PCX Older color PCX file format (EGA/VGA,
-dpcx16
16-color)
PCX 8-bit PDF Color PDF file Format PGM Portable Graymap (plain format) PGM Portable Graymap (raw format) PNG 24-bit PPM Portable Pixmap, plain format PPM Portable Pixmap raw format TIFF 24-bit TIFF preview for EPS Files
-dpcx -dpdf
Bitmap Bitmap Bitmap Bitmap Bitmap Bitmap Bitmap
-dpgm -dpgmraw -dpng -dppm -dppmraw
-dtiff or -dtiffn
-tiff
The TIFF image format is supported on all platforms by almost all word processors for importing images. JPEG is a lossy, highly compressed format that is supported on all platforms for image processing and for inclusion into HTML documents on the World Wide Web. To create these formats, MATLAB renders the figure using the Z-buffer rendering method and the resulting bitmap is then saved to the specified file.
Options
This table summarizes options that you can specify for print. The second column also shows which tutorial sections contain more detailed information.
2-134
print, printopt
The sections listed are located under Printing and Exporting Figures with MATLAB.
Option -adobecset Description
PostScript only. Use PostScript default character set encoding. See "Early PostScript 1 Printers." PostScript only. Append figure to existing PostScript file. See "Settings That Are Driver Specific." PostScript only. Print with CMYK colors instead of RGB. See "Setting CMYK Color." Printing only. Printer driver to use. See Drivers table. Exporting only. Graphics format to use. See Graphics Format Files table. Display the Print Setup dialog. Handle of figure to print. Note that you cannot specify both this option and the -swindowtitle option. See "Which Figure Is Printed." PostScript and Ghostscript only. Use loose bounding box for PostScript. See "Producing Uncropped Figures." Suppress printing of user interface controls. See "Excluding User Interface Controls." Render using the OpenGL algorithm. Note that you cannot specify this method in conjunction with -zbuffer or -painters. See "Selecting a Renderer." Render using the Painter's algorithm. Note that you cannot specify this method in conjunction with -zbuffer or -OpenGL. See "Selecting a Renderer." Specify name of printer to use. See "Selecting Printer." PostScript and Ghostscript only. Specify resolution in dots per inch. See "Setting the Resolution."
-append
-cmyk
-ddriver -dformat -dsetup -fhandle
-loose
-noui
-OpenGL
-painters
-Pprinter -rnumber
2-135
print, printopt
Option -swindowtitle
Description
Specify name of Simulink system window to print. Note that you cannot specify both this option and the -fhandle option. See "Which Figure Is Printed." Windows only. Display the Windows Print dialog box. The v stands for "verbose mode." Render using the Z-buffer algorithm. Note that you cannot specify this method in conjunction with -OpenGL or -painters. See "Selecting a Renderer." MATLAB supports a number of standard paper sizes. You can select from the following list by setting the PaperType property of the figure or selecting a supported paper size from the Print dialog box.
Property Value usletter uslegal tabloid A0 A1 A2 A3 A4 A5 B0 B1 B2 Size (Width-by-Height)
-v
-zbuffer
Paper Sizes
8.5-by-11 inches 11-by-14 inches 11-by-17 inches 841-by-1189mm 594-by-841mm 420-by-594mm 297-by-420mm 210-by-297mm 148-by-210mm 1029-by-1456mm 728-by-1028mm 514-by-728mm
2-136
print, printopt
Property Value B3 B4 B5 arch-A arch-B arch-C arch-D arch-E A B C D E
Size (Width-by-Height)
364-by-514mm 257-by-364mm 182-by-257mm 9-by-12 inches 12-by-18 inches 18-by-24 inches 24-by-36 inches 36-by-48 inches 8.5-by-11 inches 11-by-17 inches 17-by-22 inches 22-by-34 inches 34-by-43 inches
Printing Tips
This section includes information about specific printing issues.
Figures with Resize Functions
The print command produces a warning when you print a figure having a callback routine defined for the figure ResizeFcn. To avoid the warning, set the figure PaperPositionMode property to auto or select Match Figure Screen Size in the File->Page Setup... dialog box.
Troubleshooting MS-Windows Printing
If you encounter problems such as segmentation violations, general protection faults, application errors, or the output does not appear as you expect when using MS-Windows printer drivers, try the following:
2-137
print, printopt
If your printer is PostScript compatible, print with one of the MATLAB built-in PostScript drivers. There are various PostScript device options that you can use with the print command: they all start with -dps. The behavior you are experiencing may occur only with certain versions of the print driver. Contact the print driver vendor for information on how to obtain and install a different driver. Try printing with one of the MATLAB built-in Ghostscript devices. These devices use Ghostscript to convert PostScript files into other formats, such as HP LaserJet, PCX, Canon BubbleJet, and so on. Copy the figure as a Windows Enhanced Metafile using the Edit-->Copy Figure menu item on the figure window menu or the print -dmeta option at the command line. You can then import the file into another application for printing. You can set copy options in the figure's File-->Preferences...-->Copying Options dialog box. The Windows Enhanced Metafile clipboard format produces a better quality image than Windows Bitmap.
Printing MATLAB GUIs
You can generally obtain better results when printing a figure window that contains MATLAB uicontrols by setting these key properties: Set the figure PaperPositionMode property to auto. This ensures the printed version is the same size as the onscreen version. With PaperPositionMode set to auto MATLAB does not resize the figure to fit the current value of the PaperPosition. This is particularly important if you have specified a figure ResizeFcn because if MATLAB resizes the figure during the print operation, the ResizeFcn is automatically called. To set PaperPositionMode on the current figure, use the command:
set(gcf,'PaperPositionMode','auto')
Set the figure InvertHardcopy property to off. By default, MATLAB changes the figure background color of printed output to white, but does not change the color of uicontrols. If you have set the background color to, for example, match the gray of the GUI devices, you must set InvertHardcopy to off to preserve the color scheme. To set InvertHardcopy on the current figure, use the command:
set(gcf,'InvertHardcopy','off')
2-138
print, printopt
Use a color device if you want lines and text that are in color on the screen to be written to the output file as colored objects. Black and white devices convert colored lines and text to black or white to provide the best contrast with the background and to avoid dithering. Use the print command's -loose option to prevent MATLAB from using a bounding box that is tightly wrapped around objects contained in the figure. This is important if you have intentionally used space between uicontrols or axes and the edge of the figure and you want to maintain this appearance in the printed output.
Notes on Printing Interpolated Shading with PostScript Drivers
MATLAB can print surface objects (such as graphs created with surf or mesh) using interpolated colors. However, only patch objects that are composed of triangular faces can be printed using interpolated shading. Printed output is always interpolated in RGB space, not in the colormap colors. This means, if you are using indexed color and interpolated face coloring, the printed output can look different from what is displayed on screen. PostScript files generated for interpolated shading contain the color information of the graphics object's vertices and require the printer to perform the interpolation calculations. This can take an excessive amount of time and in some cases, printers may actually "time-out" before finishing the print job. One solution to this problem is to interpolate the data and generate a greater number of faces, which can then be flat shaded. To ensure that the printed output matches what you see on the screen, print using the -zbuffer option. To obtain higher resolution (for example, to make text look better), use the -r option to increase the resolution. There is, however, a trade-off between the resolution and the size of the created PostScript file, which can be quite large at higher resolutions. The default resolution of 150 dpi generally produces good results. You can reduce the size of the output file by making the figure smaller before printing it and setting the figure PaperPositionMode to auto, or by just setting the PaperPosition property to a smaller size.
2-139
print, printopt
Note that in some UNIX environments, the default lpr command cannot print files larger than 1 Mbyte unless you use the -s option, which MATLAB does by default. See the lpr man page for more information.
Examples
Specifying the Figure to Print
You can print a noncurrent figure by specifying the figure's handle. If a figure has the title "Figure No. 2", its handle is 2. The syntax is,
print -fhandle
This example prints the figure whose handle is 2, regardless of which figure is the current figure.
print -f2
Note Note that you must use the -f option if the figure's handle is hidden (i.e., its HandleVisibility property is set to off).
This example saves the figure with the handle -f2 to a PostScript file named Figure2, which can be printed later.
print -f2 -dps 'Figure2.ps'
If the figure uses noninteger handles, use the figure command to get its value, and then pass it in as the first argument.
h = figure('IntegerHandle','off') print h -depson
You can also pass a figure handle as a variable to the function form of print. For example,
h = figure; plot(1:4,5:8) print(h)
This example uses the function form of print to enable a filename to be passed in as a variable.
filename = 'mydata';
2-140
print, printopt
print('-f3', '-dpsc', filename);
(Because a filename is specified, the figure will be printed to a file.)
Specifying the Model to Print
To print a noncurrent Simulink model, use the -s option with the title of the window. For example, this command prints the Simulink window titled f14.
print -sf14
If the window title includes any spaces, you must call the function form rather than the command form of print. For example, this command saves a Simulink window title Thruster Control.
print('-sThruster Control')
To print the current system use:
print -s
For information about issues specific to printing Simulink windows, see the Simulink documentation. This example prints a surface plot with interpolated shading. Setting the current figure's (gcf) PaperPositionMode to auto enables you to resize the figure window and print it at the size you see on the screen. See Options and the previous section for information on the -zbuffer and -r200 options.
surf(peaks) shading interp set(gcf,'PaperPositionMode','auto') print -dpsc2 -zbuffer -r200
Batch Processing
You can use the function form of print to pass variables containing file names. For example, this for loop creates a series of graphs and prints each one with a different file name.
for k=1:length(fnames) surf(Z(:,:,k)) print('-dtiff','-r200',fnames(k)) end
2-141
print, printopt
Tiff Preview
The command:
print -depsc -tiff -r300 picture1
saves the current figure at 300 dpi, in a color Encapsulated PostScript file named picture1.eps. The -tiff option creates a 72 dpi TIFF preview, which many word processor applications can display on screen after you import the EPS file. This enables you to view the picture on screen within your word processor and print the document to a PostScript printer using a resolution of 300 dpi.
See Also
orient, figure
2-142
printdlg
Purpose Syntax
2printdlg
Display print dialog box
printdlg printdlg(fig) printdlg('-crossplatform',fig) printdlg('-setup',fig) printdlg prints the current figure. printdlg(fig) creates a dialog box from which you can print the figure window identified by the handle fig. Note that uimenus do not print. printdlg('-crossplatform',fig) displays the standard cross-platform
Description
MATLAB printing dialog rather than the built-in printing dialog box for Microsoft Windows computers. Insert this option before the fig argument.
printdlg('-setup',fig) forces the printing dialog to appear in a setup mode.
Here one can set the default printing options without actually printing.
2-143
printpreview
Purpose Syntax Description
2printpreview
Preview figure to be printed
printpreview printpreview(f) printpreview displays a dialog box showing the figure in the currently active figure window as it will be printed. The figure is displayed with a 1/4 size
thumbnail or full size image.
printpreview(f) displays a dialog box showing the figure having the handle f
as it will be printed. You can select any of the following options from the Print Preview dialog box.
Option Button Print... Page Setup... Zoom In Zoom Out Close Description
Close Print Preview and open the Print dialog Open the Page Setup dialog Display a full size image of the page Display a 1/4 scaled image of the page Close the Print Preview dialog
See Also
printdlg, pagesetupdlg
2-144
prod
Purpose Syntax Description
2prod
Product of array elements
B = prod(A) B = prod(A,dim) B = prod(A) returns the products along different dimensions of an array.
If A is a vector, prod(A) returns the product of the elements. If A is a matrix, prod(A) treats the columns of A as vectors, returning a row vector of the products of each column. If A is a multidimensional array, prod(A) treats the values along the first non-singleton dimension as vectors, returning an array of row vectors.
B = prod(A,dim) takes the products along the dimension of A specified by
scalar dim.
Examples
The magic square of order 3 is
M = magic(3) M = 8 3 4 1 5 9 6 7 2
The product of the elements in each column is
prod(M) = 96 45 84
The product of the elements in each row can be obtained by:
prod(M,2) = 48 105 72
See Also
cumprod, diff, sum
2-145
profile
Purpose Graphical Interface Syntax
2profile
Tool for optimizing and debugging M-file code As an alternative to the profile function, select View -> Profiler from the desktop.
profile viewer profile on profile on -detail level profile on -history profile off profile resume profile clear profile report profile report basename profile plot s = profile('status') stats = profile('info')
Description
The profile function helps you debug and optimize M-files by tracking their execution time. For each function in the M-file, profile records information about execution time, number of calls, parent functions, child functions, code line hit count, and code line execution time. Some people use profile simply to see the child functions; see also depfun for that purpose. The Profiler user interface, opened with profile viewer, provides information gathered using the profile function, but presents the information in a different format from profile report.
profile viewer opens the Profiler graphical interface, a tool for assessing
M-file performance to help you identify potential performance improvements. It is based on the results returned by the profile function, but presents the information a different format than the profile report. The report function provides some options not available with the Profiler, including saving the reports to a file.
profile on starts profile, clearing previously recorded profile statistics.
2-146
profile
profile on -detail level starts profile for the set of functions specified by level, clearing previously recorded profile statistics. Value for level mmex Functions profile Gathers Information About
M-functions, M-subfunctions, and MEX-functions; mmex is the default value Same functions as for mmex plus built-in functions such as eig Same functions as for builtin plus built-in operators such as +
builtin
operator
profile on -history starts profile, clearing previously recorded profile statistics, and recording the exact sequence of function calls. The profile
function records up to 10,000 function entry and exit events. For more than 10,000 events, profile continues to record other profile statistics, but not the sequence of calls.
profile off suspends profile. profile resume restarts profile without clearing previously recorded
statistics.
profile clear clears the statistics recorded by profile. profile report suspends profile, generates a profile report in HTML
format, and displays the report in your system's default Web browser. This report contains some different information than what is available in the Profiler reports.
profile report basename suspends profile, generates a profile report in HTML format, saves the report in the file basename in the current directory,
and displays the report in your system's default Web browser. Because the report consists of several files, do not provide an extension for basename.
profile plot suspends profile and displays in a figure window a bar graph of the functions using the most execution time.
2-147
profile
s = profile('status') displays a structure containing the current profile
status. The structure's fields are
Field ProfilerStatus DetailLevel HistoryTracking Values 'on' or 'off' 'mmex', 'builtin', or 'operator' 'on' or 'off'
stats = profile('info') suspends profile and displays a structure containing profile results. Use this function to access the data generated by profile. The structure's fields are Field FunctionTable FunctionHistory ClockPrecision Description
Array containing list of all functions called Array containing function call history Precision of profile's time measurement
Remarks
To see an example of a profile report and profile plot, as well as to learn more about the results and how to use profiling, see "Measuring Performance" and "The profile Function" in MATLAB Programming documentation. Follow these steps to run profile and create a profile report.
1 Run profile for code that computes the Lotka-Volterra predator-prey
Examples
population model.
profile on -detail builtin -history [t,y] = ode23('lotka',[0 2],[20;20]); profile report
The profile report appears in your system's default Web browser, providing information for all M-functions, M-subfunctions, MEX-functions, and built-in functions. The report includes the function call history.
2-148
profile
2 Generate the profile plot.
profile plot
The profile plot appears in a figure window.
3 Because the report and plot features suspend profile, resume its operation
without clearing the statistics already gathered.
profile resume
The profile function continues gathering statistics when you execute the next M-file.
See Also
depdir, depfun, profreport, tic
See "Measuring Performance", "The Profiler", and "The profile Function" in the MATLAB Programming documentation.
2-149
profreport
Purpose Syntax
2profreport
Generate profile report
profreport profreport(basename) profreport(stats) profreport(basename,stats) profreport suspends the profile function, generates a profile report in HTML format using the current profile results, and displays the report in a
Description
Web browser. This presents the information in a different format from the Profiler reports.
profreport(basename) suspends profile, generates a profile report in HTML format using the current profile results, saves the report using the basename
you supply, and displays the report in a Web browser. Because the report consists of several files, do not provide an extension for basename.
profreport(stats) suspends profile, generates a profile report in HTML format using the info results from profile, and displays the report in a Web browser. Here, stats is the profile information structure returned by stats = profile('info'). profreport(basename,stats) suspends profile, generates a profile report in HTML format using the stats result from profile, saves the report using the basename you supply, and displays the report in a Web browser. Here, stats is the profile information structure returned by stats = profile('info').
Because the report consists of several files, do not provide an extension for basename.
Examples
Run profile and view the structure containing profile results.
1 Run profile for code that computes the Lotka-Volterra predator-prey
population model.
profile on -detail builtin -history [t,y] = ode23('lotka',[0 2],[20;20]);
2-150
profreport
2 View the structure containing the profile results.
stats = profile('info')
MATLAB returns
stats = FunctionTable: [42x1 FunctionHistory: ClockPrecision: Name: struct] [2x830 double] 0.0100 'MATLAB'
3 View the contents of the second element in the FunctionTable structure.
stats.FunctionTable(2)
MATLAB returns
ans = FunctionName: FileName: Type: NumCalls: TotalTime: TotalRecursiveTime: Children: Parents: ExecutedLines: 'horzcat' '' 'Builtin-function' 43 0 0 [0x1 struct] [2x1 struct] [0x3 double]
4 Display the profile report from the structure.
profreport(stats)
MATLAB displays the profile report in a Web browser.
See Also
profile
"Measuring Performance" and "The profile Function" in MATLAB Programming documentation
2-151
propedit
Purpose Syntax Description
2propedit
Starts the Property Editor
propedit propedit(HandleList) propedit starts the Property Editor, a graphical user interface to the
properties of Handle Graphics objects. If you call it without any input arguments, the Property Editor displays the properties of the current figure, if there are more than one figure displayed, or the root object, if there is no currently active figure.
propedit(HandleList) edits the properties for the object (or objects) in HandleList.
Note Starting the Property Editor enables plot editing mode for the figure.
2-152
propedit
Remarks
Property Editor Graphical User Interface Components
Use these buttons to move back and forth among the graphics objects you have edited. Use the navigation bar to select the object you want to edit. Click on a tab to view a group of properties.
Click here to view a list of values for this field.
Click Apply to apply your changes without dismissing the Property Editor. Click Cancel to dismiss the Property Editor without applying your changes. Click OK to apply your changes and dismiss the Property Editor. Check this box to see the effect of your changes as you make them. Click Help to get information about particular properties.
See Also
plotedit
2-153
propedit (COM)
Purpose Syntax Arguments Description
2propedit (COM)
Request the control to display its built-in property page
propedit(h) h
Handle for a MATLAB COM control object. Request the control to display its built-in property page. Note that some controls do not have a built-in property page. For those objects, this command will fail. Create a Microsoft Calendar control and display its property page:
cal = actxcontrol('mscal.calendar', [0 0 500 500]); propedit(cal)
Examples
See Also
inspect, get
2-154
psi
Purpose Syntax
2psi
Psi (polygamma) function
Y = psi(X) Y = psi(k,X) Y = psi(k0:k1,X) Y = psi(X) evaluates the function for each element of array X. X must be real and nonnegative. The function, also known as the digamma function, is the logarithmic derivative of the gamma function
Description
( x ) = digamma ( x ) d ( log ( ( x ) ) ) = --------------------------------dx d(( x)) / dx = ---------------------------( x)
Y = psi(k,X) evaluates the kth derivative of at the elements of X. psi(0,X) is the digamma function, psi(1,X) is the trigamma function, psi(2,X) is the
tetragamma function, etc.
Y = psi(k0:k1,X) evaluates derivatives of order k0 through k1 at X. Y(k,j) is the (k-1+k0)th derivative of , evaluated at X(j).
Examples
Example 1. Use the psi function to calculate Euler's constant, .
format long -psi(1) ans = 0.57721566490153 -psi(0,1) ans = 0.57721566490153
Example 2. The trigamma function of 2, psi(1,2), is the same as ( / 6 ) 1 .
format long psi(1,2) ans = 0.64493406684823
2
2-155
psi
pi^2/6 - 1 ans = 0.64493406684823
Example 3. This code produces the first page of Table 6.1 in Abramowitz and
Stegun [].
x = (1:.005:1.250)'; [x gamma(x) gammaln(x) psi(0:1,x)' x-1]
Example 4. This code produces a portion of Table 6.2 in [].
psi(2:3,1:.01:2)'
See Also References
gamma, gammainc, gammaln
Abramowitz, M. and I. A. Stegun, Handbook of Mathematical Functions, Dover Publlications, 1965, Sections 6.3 and 6.4.
2-156
pwd
Purpose Graphical Interface Syntax Description
2pwd
Display current directory As an alternative to the pwd function, use the Current Directory field in the MATLAB desktop toolbar.
pwd s = pwd pwd displays the current working directory. s = pwd returns the current directory to the variable s.
See Also
cd, dir, path, what
2-157
qmr
Purpose Syntax
2qmr
Quasi-Minimal Residual method
x = qmr(A,b) qmr(A,b,tol) qmr(A,b,tol,maxit) qmr(A,b,tol,maxit,M) qmr(A,b,tol,maxit,M1,M2) qmr(A,b,tol,maxit,M1,M2,x0) qmr(afun,b,tol,maxit,m1fun,m2fun,x0,p1,p2,...) [x,flag] = qmr(A,b,...) [x,flag,relres] = qmr(A,b,...) [x,flag,relres,iter] = qmr(A,b,...) [x,flag,relres,iter,resvec] = qmr(A,b,...) x = qmr(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.
Description
If qmr converges, a message to that effect is displayed. If qmr 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.
qmr(A,b,tol) specifies the tolerance of the method. If tol is [], then qmr uses the default, 1e-6. qmr(A,b,tol,maxit) specifies the maximum number of iterations. If maxit is [], then qmr uses the default, min(n,20). qmr(A,b,tol,maxit,M) and qmr(A,b,tol,maxit,M1,M2) use preconditioners M or M = M1*M2 and effectively solve the system inv(M)*A*x = inv(M)*b for x. If M is [] then qmr applies no preconditioner. M can be a function mfun such that mfun(x) returns M\x and mfun(x,'transp') returns M'\x. qmr(A,b,tol,maxit,M1,M2,x0) specifies the initial guess. If x0 is [], then qmr
uses the default, an all zero vector.
2-158
qmr
qmr(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] = qmr(A,b,...) also returns a convergence flag.
Flag 0
Convergence qmr converged to the desired tolerance tol within maxit
iterations.
1 2 3 qmr iterated maxit times but did not converge.
Preconditioner M was ill-conditioned. The method stagnated. (Two consecutive iterates were the same.) One of the scalar quantities calculated during qmr became too small or too large to continue computing.
4
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] = qmr(A,b,...) also returns the relative residual norm(b-A*x)/norm(b). If flag is 0, relres <= tol. [x,flag,relres,iter] = qmr(A,b,...) also returns the iteration number at which x was computed, where 0 <= iter <= maxit. [x,flag,relres,iter,resvec] = qmr(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);
2-159
qmr
tol = 1e-8; maxit = 15; M1 = spdiags([on/(-2) on],-1:0,n,n); M2 = spdiags([4*on -on],0:1,n,n); x = qmr(A,b,tol,maxit,M1,M2,[]);
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 qmr
x1 = qmr(@afun,b,tol,maxit,M1,M2,[],n);
Example 2.
load west0479; A = west0479; b = sum(A,2); [x,flag] = qmr(A,b) flag is 1 because qmr does not converge to the default tolerance 1e-6 within the
default 20 iterations.
[L1,U1] = luinc(A,1e-5); [x1,flag1] = qmr(A,b,1e-6,20,L1,U1) flag1 is 2 because the upper triangular U1 has a zero on its diagonal, and qmr fails in the first iteration when it tries to solve a system such as U1*y = r for y using backslash. [L2,U2] = luinc(A,1e-6); [x2,flag2,relres2,iter2,resvec2] = qmr(A,b,1e-15,10,L2,U2) flag2 is 0 because qmr converges to the tolerance of 1.6571e-016 (the value of relres2) at the eighth iteration (the value of iter2) when preconditioned by
2-160
qmr
the incomplete LU factorization with a drop tolerance of 1e-6. resvec2(1) = norm(b) and resvec2(9) = norm(b-A*x2). You can follow the progress of qmr by plotting the relative residuals at each iteration starting from the initial estimate (iterate number 0).
semilogy(0:iter2,resvec2/norm(b),'-o') xlabel('iteration number') ylabel('relative residual')
10
2
10
0
10
-2
10 relative residual
-4
10
-6
10
-8
10
-10
10
-12
10
-14
10
-16
0
1
2
3
4 iteration number
5
6
7
8
See Also
bicg, bicgstab, cgs, gmres, lsqr, luinc, minres, pcg, 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] Freund, Roland W. and Nel M. Nachtigal, "QMR: A quasi-minimal residual method for non-Hermitian linear systems", SIAM Journal: Numer. Math. 60, 1991, pp. 315-339.
2-161
qr
Purpose Syntax
2qr
Orthogonal-triangular decomposition
[Q,R] = qr(A) [Q,R] = qr(A,0) [Q,R,E] = qr(A) [Q,R,E] = qr(A,0) X = qr(A) R = qr(A) [C,R] = qr(A,B) R = qr(A,0) [C,R] = qr(A,B,0)
(full and sparse matrices) (full and sparse matrices) (full matrices) (full matrices) (full matrices) (sparse matrices) (sparse matrices) (sparse matrices) (sparse matrices)
Description
The qr function performs the orthogonal-triangular decomposition of a matrix. This factorization is useful for both square and rectangular matrices. It expresses the matrix as the product of a real orthonormal or complex unitary matrix and an upper triangular matrix.
[Q,R] = qr(A) produces an upper triangular matrix R of the same dimension as A and a unitary matrix Q so that A = Q*R. For sparse matrices, Q is often nearly full. If [m n] = size(A), then Q is m-by-m and R is m-by-n. [Q,R] = qr(A,0) produces an "economy-size" decomposition. If [m n] = size(A), and m > n, then qr computes only the first n columns of of Q and R is n-by-n. If m <= n, it is the same as [Q,R] = qr(A). [Q,R,E] = qr(A) for full matrix A, produces a permutation matrix E, an upper triangular matrix R with decreasing diagonal elements, and a unitary matrix Q so that A*E = Q*R. The column permutation E is chosen so that abs(diag(R))
is decreasing.
[Q,R,E] = qr(A,0) for full matrix A, produces an "economy-size" decomposition in which E is a permutation vector, so that A(:,E) = Q*R. The column permutation E is chosen so that abs(diag(R)) is decreasing. X = qr(A) for full matrix A, returns the output of the LAPACK subroutine DGEQRF or ZGEQRF. triu(qr(A)) is R.
2-162
qr
R = qr(A) for sparse matrix A, produces only an upper triangular matrix, R. The matrix R provides a Cholesky factorization for the matrix associated with
the normal equations,
R'*R = A'*A
This approach avoids the loss of numerical information inherent in the computation of A'*A. It may be preferred to [Q,R] = qr(A) since Q is always nearly full.
[C,R] = qr(A,B) for sparse matrix A, applies the orthogonal transformations to B, producing C = Q'*B without computing Q. B and A must have the same number of rows. R = qr(A,0) and [C,R] = qr(A,B,0) for sparse matrix A, produce "economy-size" results.
For sparse matrices, the Q-less QR factorization allows the solution of sparse least squares problems minimize Ax b with two steps
[C,R] = qr(A,b) x = R\c
If A is sparse but not square, MATLAB uses the two steps above for the linear equation solving backslash operator, i.e., x = A\b.
Examples
Example 1. Start with
A = [ 1 4 7 10 2 5 8 11 3 6 9 12 ]
This is a rank-deficient matrix; the middle column is the average of the other two columns. The rank deficiency is revealed by the factorization:
[Q,R] = qr(A) Q =
2-163
qr
-0.0776 -0.3105 -0.5433 -0.7762 R = -12.8841 0 0 0
-0.8331 -0.4512 -0.0694 0.3124
0.5444 -0.7709 -0.0913 0.3178
0.0605 0.3251 -0.8317 0.4461
-14.5916 -1.0413 0 0
-16.2992 -2.0826 0.0000 0
The triangular structure of R gives it zeros below the diagonal; the zero on the diagonal in R(3,3) implies that R, and consequently A, does not have full rank.
Example 2. This examples uses matrix A from the first example. The QR
factorization is used to solve linear systems with more equations than unknowns. For example, let
b = [1;3;5;7]
The linear system Ax = b represents four equations in only three unknowns. The best solution in a least squares sense is computed by
x = A\b
which produces
Warning: Rank deficient, rank = 2, tol = 1.4594E-014 x = 0.5000 0 0.1667
The quantity tol is a tolerance used to decide if a diagonal element of R is negligible. If [Q,R,E] = qr(A), then
tol = max(size(A))*eps*abs(R(1,1))
The solution x was computed using the factorization and the two steps
y = Q'*b; x = R\y
2-164
qr
The computed solution can be checked by forming Ax . This equals b to within roundoff error, which indicates that even though the simultaneous equations Ax = b are overdetermined and rank deficient, they happen to be consistent. There are infinitely many solution vectors x; the QR factorization has found just one of them.
Algorithm
The qr function uses LAPACK routines to compute the QR decomposition:
Syntax R = qr(A) R = qr(A,0) [Q,R] = qr(A) [Q,R] = qr(A,0) [Q,R,e] = qr(A) [Q,R,e] = qr(A,0)
Real DGEQRF DGEQRF, DORGQR DGEQP3, DORGQR
Complex ZGEQRF ZGEQRF, ZUNGQR ZGEQPF, ZUNGQR
See Also
lu, null, orth, qrdelete, qrinsert, qrupdate
The arithmetic operators \ and /
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-165
qrdelete
Purpose Syntax
2qrdelete
Delete column or row from QR factorization
[Q1,R1] = qrdelete(Q,R,j) [Q1,R1] = qrdelete(Q,R,j,'col') [Q1,R1] = qrdelete(Q,R,j,'row') [Q1,R1] = qrdelete(Q,R,j) returns the QR factorization of the matrix A1, where A1 is A with the column A(:,j) removed and [Q,R] = qr(A) is the QR factorization of A. [Q1,R1] = qrdelete(Q,R,j,'col') is the same as qrdelete(Q,R,j). [Q1,R1] = qrdelete(Q,R,j,'row') returns the QR factorization of the matrix A1, where A1 is A with the row A(j,:) removed and [Q,R] = qr(A) is the QR factorization of A.
Description
Examples
A = magic(5); [Q,R] = qr(A); j = 3; [Q1,R1] = qrdelete(Q,R,j,'row'); Q1 = 0.5274 0.7135 0.3102 0.3413 R1 = 32.2335 0 0 0 -0.5197 0.6911 -0.1982 -0.4616 -0.6697 0.0158 0.4675 0.5768 -0.0578 0.1142 -0.8037 0.5811
26.0908 -19.7045 0 0
19.9482 -10.9891 22.7444 0
21.4063 0.4318 5.8357 -14.5784
23.3297 -1.4873 -3.1977 3.7796
returns a valid QR factorization, although possibly different from
A2 = A; A2(j,:) = []; [Q2,R2] = qr(A2)
2-166
qrdelete
Q2 = -0.5274 -0.7135 -0.3102 -0.3413 R2 = -32.2335 0 0 0
0.5197 -0.6911 0.1982 0.4616
0.6697 -0.0158 -0.4675 -0.5768
-0.0578 0.1142 -0.8037 0.5811
-26.0908 19.7045 0 0
-19.9482 10.9891 -22.7444 0
-21.4063 -0.4318 -5.8357 -14.5784
-23.3297 1.4873 3.1977 3.7796
Algorithm See Also
The qrdelete function uses a series of Givens rotations to zero out the appropriate elements of the factorization.
planerot, qr, qrinsert
2-167
qrinsert
Purpose Syntax
2qrinsert
Insert column or row into QR factorization
[Q1,R1] = qrinsert(Q,R,j,x) [Q1,R1] = qrinsert(Q,R,j,x,'col') [Q1,R1] = qrinsert(Q,R,j,x,'row') [Q1,R1] = qrinsert(Q,R,j,x) returns the QR factorization of the matrix A1, where A1 is A = Q*R with the column x inserted before A(:,j). If A has n columns and j = n+1, then x is inserted after the last column of A. [Q1,R1] = qrinsert(Q,R,j,x,'col') is the same as qrinsert(Q,R,j,x). [Q1,R1] = qrinsert(Q,R,j,x,'row') returns the QR factorization of the matrix A1, where A1 is A = Q*R with an extra row, x, inserted before A(j,:).
Description
Examples
A = magic(5); [Q,R] = qr(A); j = 3; x = 1:5; [Q1,R1] = qrinsert(Q,R,j,x,'row') Q1 = 0.5231 0.7078 0.0308 0.1231 0.3077 0.3385 R1 = 32.4962 0 0 0 0 0 0.5039 -0.6966 0.0592 0.1363 0.1902 0.4500 -0.6750 0.0190 0.0656 0.3542 0.4100 0.4961 0.1205 -0.0788 0.1169 0.6222 0.4161 -0.6366 0.0411 0.0833 0.1527 0.6398 -0.7264 0.1761 0.0225 -0.0150 -0.9769 0.2104 -0.0150 0.0225
26.6801 19.9292 0 0 0 0
21.4795 12.4403 24.4514 0 0 0
23.8182 2.1340 11.8132 20.2382 0 0
26.0031 4.3271 3.9931 10.3392 16.1948 0
returns a valid QR factorization, although possibly different from
2-168
qrinsert
A2 = [A(1:j-1,:); x; A(j:end,:)]; [Q2,R2] = qr(A2) Q2 = -0.5231 -0.7078 -0.0308 -0.1231 -0.3077 -0.3385 R2 = -32.4962 0 0 0 0 0
0.5039 -0.6966 0.0592 0.1363 0.1902 0.4500
0.6750 -0.0190 -0.0656 -0.3542 -0.4100 -0.4961
-0.1205 0.0788 -0.1169 -0.6222 -0.4161 0.6366
0.0411 0.0833 0.1527 0.6398 -0.7264 0.1761
0.0225 -0.0150 -0.9769 0.2104 -0.0150 0.0225
-26.6801 19.9292 0 0 0 0
-21.4795 12.4403 -24.4514 0 0 0
-23.8182 2.1340 -11.8132 -20.2382 0 0
-26.0031 4.3271 -3.9931 -10.3392 16.1948 0
Algorithm
The qrinsert function inserts the values of x into the jth column (row) of R. It then uses a series of Givens rotations to zero out the nonzero elements of R on and below the diagonal in the jth column (row).
planerot, qr, qrdelete
See Also
2-169
qrupdate
Description Syntax Description
2qrupdate
Rank 1 update to QR factorization
[Q1,R1] = qrupdate(Q,R,u,v) [Q1,R1] = qrupdate(Q,R,u,v) when [Q,R] = qr(A) is the original QR factorization of A, returns the QR factorization of A + u*v', where u and v are
column vectors of appropriate lengths.
Remarks Examples
qrupdate works only for full matrices.
The matrix
mu = sqrt(eps) mu = 1.4901e-08 A = [ones(1,4); mu*eye(4)];
is a well-known example in least squares that indicates the dangers of forming A'*A. Instead, we work with the QR factorization orthonormal Q and upper triangular R.
[Q,R] = qr(A);
As we expect, R is upper triangular.
R = -1.0000 0 0 0 0 -1.0000 0.0000 0 0 0 -1.0000 0.0000 0.0000 0 0 -1.0000 0.0000 0.0000 0.0000 0
In this case, the upper triangular entries of R, excluding the first row, are on the order of sqrt(eps). Consider the update vectors
u = [-1 0 0 0 0]'; v = ones(4,1);
2-170
qrupdate
Instead of computing the rather trivial QR factorization of this rank one update to A from scratch with
[QT,RT] = qr(A + u*v') QT = 0 -1 0 0 0 RT = 1.0e-007 * -0.1490 0 0 0 0 0 -0.1490 0 0 0 0 0 -0.1490 0 0 0 0 0 -0.1490 0 0 0 -1 0 0 0 0 0 -1 0 0 0 0 0 -1 1 0 0 0 0
we may use qrupdate.
[Q1,R1] = qrupdate(Q,R,u,v) Q1 = -0.0000 1.0000 0.0000 0.0000 -0.0000 R1 = 1.0e-007 * 0.1490 0.0000 0 0.1490 0 0 -0.0000 -0.0000 1.0000 0.0000 -0.0000 -0.0000 -0.0000 -0.0000 1.0000 -0.0000 -0.0000 -0.0000 -0.0000 -0.0000 1.0000 1.0000 0.0000 0.0000 0.0000 0.0000
0.0000 0.0000 0.1490
0.0000 0.0000 0.0000
2-171
qrupdate
0 0
0 0
0 0
0.1490 0
Note that both factorizations are correct, even though they are different.
Algorithm
qrupdate uses the algorithm in section 12.5.1 of the third edition of Matrix Computations by Golub and van Loan. qrupdate is useful since, if we take N = max(m,n), then computing the new QR factorization from scratch is roughly an O ( N 3 ) algorithm, while simply updating the existing factors in this way is an O ( N 2 ) algorithm.
References See Also
[1] Golub, Gene H. and Charles Van Loan, Matrix Computations, Third Edition, Johns Hopkins University Press, Baltimore, 1996
cholupdate, qr
2-172
quad, quad8
Purpose
2quad, quad8
Numerically evaluate integral, adaptive Simpson quadrature
Note The quad8 function, which implemented a higher order method, is obsolete. The quadl function is its recommended replacement.
Syntax
q = quad(fun,a,b) q = quad(fun,a,b,tol) q = quad(fun,a,b,tol,trace) q = quad(fun,a,b,tol,trace,p1,p2,...) [q,fcnt] = quadl(fun,a,b,...)
Description
Quadrature is a numerical method used to find the area under the graph of a function, that is, to compute a definite integral. q =
a f ( x ) dx
b
q = quad(fun,a,b) approximates the integral of function fun from a to b to within an error of 10-6 using recursive adaptive Simpson quadrature. fun accepts a vector x and returns a vector y, the function fun evaluated at each element of x. q = quad(fun,a,b,tol) uses an absolute error tolerance tol instead of the default which is 1.0e-6. Larger values of tol result in fewer function
evaluations and faster computation, but less accurate results. In MATLAB version 5.3 and earlier, the quad function used a less reliable algorithm and a default relative tolerance of 1.0e-3.
q = quad(fun,a,b,tol,trace) with non-zero trace shows the values of [fcnt a b-a Q] during the recursion. q = quad(fun,a,b,tol,trace,p1,p2,...) provides for additional arguments p1,p2,... to be passed directly to function fun, fun(x,p1,p2,...). Pass empty matrices for tol or trace to use the default values. [q,fcnt] = quad(...) returns the number of function evaluations.
2-173
quad, quad8
The function quadl may be more efficient with high accuracies and smooth integrands.
Examples
The function fun can be An inline object
F = inline('1./(x.^3-2*x-5)'); Q = quad(F,0,2);
A function handle
Q = quad(@myfun,0,2);
where myfun.m is an M-file.
function y = myfun(x) y = 1./(x.^3-2*x-5);
Algorithm Diagnostics
quad implements a low order method using an adaptive recursive Simpson's
rule.
quad may issue one of the following warnings: 'Minimum step size reached' indicates that the recursive interval
subdivision has produced a subinterval whose length is on the order of roundoff error in the length of the original interval. A nonintegrable singularity is possible.
'Maximum function count exceeded' indicates that the integrand has been evaluated more than 10,000 times. A nonintegrable singularity is likely. 'Infinite or Not-a-Number function value encountered' indicates a
floating point overflow or division by zero during the evaluation of the integrand in the interior of the interval.
See Also References
dblquad, inline, quadl, triplequad, @ (function handle)
[1] Gander, W. and W. Gautschi, "Adaptive Quadrature Revisited", BIT, Vol. 40, 2000, pp. 84-101. This document is also available at http://www.inf.ethz.ch/personal/gander.
2-174
quadl
Purpose Syntax
2quadl
Numerically evaluate integral, adaptive Lobatto quadrature
q = quadl(fun,a,b) q = quadl(fun,a,b,tol) q = quadl(fun,a,b,tol,trace) q = quadl(fun,a,b,tol,trace,p1,p2,...) [q,fcnt] = quadl(fun,a,b,...) q = quadl(fun,a,b) approximates the integral of function fun from a to b, to within an error of 10-6 using recursive adaptive Lobatto quadrature. fun accepts a vector x and returns a vector y, the function fun evaluated at each element of x. q = quadl(fun,a,b,tol) uses an absolute error tolerance of tol instead of the default, which is 1.0e-6. Larger values of tol result in fewer function evaluations and faster computation, but less accurate results. quadl(fun,a,b,tol,trace) with non-zero trace shows the values of [fcnt a b-a q] during the recursion. quadl(fun,a,b,tol,trace,p1,p2,...) provides for additional arguments p1,p2,... to be passed directly to function fun, fun(x,p1,p2,...). Pass empty matrices for tol or trace to use the default values. [q,fcnt] = quadl(...) returns the number of function evaluations.
Description
Use array operators .*, ./ and .^ in the definition of fun so that it can be evaluated with a vector argument. The function quad may be more efficient with low accuracies or nonsmooth integrands.
Examples
The function fun can be: An inline object
F = inline('1./(x.^3-2*x-5)'); Q = quadl(F,0,2);
2-175
quadl
A function handle
Q = quadl(@myfun,0,2);
where myfun.m is an M-file.
function y = myfun(x) y = 1./(x.^3-2*x-5);
Algorithm Diagnostics
quadl implements a high order method using an adaptive Gauss/Lobatto
qudrature rule.
quadl may issue one of the following warnings: 'Minimum step size reached' indicates that the recursive interval
subdivision has produced a subinterval whose length is on the order of roundoff error in the length of the original interval. A nonintegrable singularity is possible.
'Maximum function count exceeded' indicates that the integrand has been evaluated more than 10,000 times. A nonintegrable singularity is likely. 'Infinite or Not-a-Number function value encountered' indicates a
floating point overflow or division by zero during the evaluation of the integrand in the interior of the interval.
See Also References
dblquad, inline, quad, triplequad, @ (function handle)
[1] Gander, W. and W. Gautschi, "Adaptive Quadrature Revisited", BIT, Vol. 40, 2000, pp. 84-101. This document is also available at http://www.inf.ethz.ch/personal/gander.
2-176
questdlg
Purpose Syntax
2questdlg
Create and display question dialog box
button = questdlg('qstring') button = questdlg('qstring','title') button = questdlg('qstring','title','default') button = questdlg('qstring','title','str1','str2','default') button = questdlg('qstring','title','str1','str2','str3','default') button = questdlg('qstring') displays a modal dialog presenting the question 'qstring'. The dialog has three default buttons, Yes, No, and Cancel. If the user presses one of these three buttons, button is set to the name of the button pressed. If the user presses the close button on the dialog, button
Description
is set to the empty string. If the user presses the Return key, button is set to 'Yes'. 'qstring' is a cell array or a string that automatically wraps to fit within the dialog box.
button = questdlg('qstring','title') displays a question dialog with 'title' displayed in the dialog's title bar. button = questdlg('qstring','title','default') specifies which push button is the default in the event that the Return key is pressed. 'default' must be 'Yes', 'No', or 'Cancel'. button = questdlg('qstring','title','str1','str2','default') creates a question dialog box with two push buttons labeled 'str1' and 'str2'. 'default' specifies the default button selection and must be 'str1' or 'str2'. button = questdlg('qstring','title','str1','str2','str3','default') creates a question dialog box with three push buttons labeled 'str1', 'str2', and 'str3'. 'default' specifies the default button selection and must be 'str1', 'str2', or 'str3'.
In all cases where 'default' is specified, if'default' is not set to one of the button names, pressing the Return key displays a warning and the dialog remains open.
2-177
questdlg
Example
Create a question dialog asking the user whether to continue a hypothetical operation:
button = questdlg('Do you want to continue?',... 'Continue Operation','Yes','No','Help','No'); if strcmp(button,'Yes') disp('Creating file') elseif strcmp(button,'No') disp('Canceled file operation') elseif strcmp(button,'Help') disp('Sorry, no help available') end
See Also
dialog, errordlg, helpdlg, inputdlg, msgbox, warndlg
"Predefined Dialog Boxes" for related functions
2-178
quit
Purpose Graphical Interface Syntax
2quit
Terminate MATLAB As an alternative to the quit function, use the close box or select Exit
MATLAB from the File menu in the MATLAB desktop.
quit quit cancel quit force quit terminates MATLAB after running finish.m, if finish.m exists. The workspace is not automatically saved by quit. To save the workspace or perform other actions when quitting, create a finish.m file to perform those actions. If an error occurs while finish.m is running, quit is canceled so that you can correct your finish.m file without losing your workspace. quit cancel is for use in finish.m and cancels quitting. It has no effect
Description
anywhere else.
quit force bypasses finish.m and terminates MATLAB. Use this to override finish.m, for example, if an errant finish.m will not let you quit.
Remarks
When using Handle Graphics in finish.m, use uiwait, waitfor, or drawnow so that figures are visible. See the reference pages for these functions for more information.
2-179
quit
Examples
Two sample finish.m files are included with MATLAB. Use them to help you create your own finish.m, or rename one of the files to finish.m to use it. finishsav.m--Saves the workspace to a MAT-file when MATLAB quits. finishdlg.m--Displays a dialog allowing you to cancel quitting; it uses quit cancel and contains the following code:
button = questdlg('Ready to quit?', ... 'Exit Dialog','Yes','No','No'); switch button case 'Yes', disp('Exiting MATLAB'); %Save variables to matlab.mat save case 'No', quit cancel; end
See Also
finish, save, startup
2-180
quiver
Purpose Syntax
2quiver
Quiver or velocity plot
quiver(U,V,U,V) quiver(X,Y) quiver(...,scale) quiver(...,LineSpec) quiver(...,LineSpec,'filled') h = quiver(...)
Description
A quiver plot displays velocity vectors as arrows with components (U,V) at the points (X,Y). For example, the first vector is defined by componets U(1),V(1) and is displayed at the point X(1),Y(1).
quiver(X,Y,U,V) plots vectors as arrows at the coordinates specifide in each corresponding pair of elements in X and Y. The matirces X, Y, U, and V must all
be the same size and contain corresponding position and velocity components.
Expanding X and Y Coordinates
MATLAB expandes X and Y, if they are not matrices. This expansion is equivalent to calling meshgrid to generate matrices from vectors:
[X,Y] = meshgrid(X,Y) quiver(X,Y,U,V)
In this case, the following must be true:
length(X) = n and length(Y) = m, where [m,n] = size(U) = size(V)
The vector X corresponds to the columns of U and V, and vector Y corresponds to the rows of U and V.
quiver(U,V) draws vectors specified by U and V at equally spaced points in the
x-y plane.
quiver(...,scale) automatically scales the arrows to fit within the grid and then stretches them by the factor scale. scale = 2 doubles their relative length and scale = 0.5 halves the length. Use scale = 0 to plot the velocity
vectors without the automatic scaling.
2-181
quiver
quiver(...,LineSpec) specifies line style, marker symbol, and color using any valid LineSpec. quiver draws the markers at the origin of the vectors. quiver(...,LineSpec,'filled') fills markers specified by LineSpec. h = quiver(...) returns a vector of line handles.
Examples
Plot the gradient field of the function z = xe ( x
[X,Y] = meshgrid(2:.2:2); Z = X.exp(X.^2 Y.^2); [DX,DY] = gradient(Z,.2,.2); contour(X,Y,Z) hold on quiver(X,Y,DX,DY) colormap hsv grid off hold off
2
2
y2 )
.
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
See Also
contour, LineSpec, plot, quiver3
"Direction and Velocity Plots" for related functions
2-182
quiver
Two-Dimensional Quiver Plots for more examples
2-183
quiver3
Purpose Syntax
2quiver3
Three-dimensional velocity plot
quiver3(X,Y,Z,U,V,W) quiver3(Z,U,V,W) quiver3(...,scale) quiver3(...,LineSpec) quiver3(...,LineSpec,'filled') h = quiver3(...)
Description
A three-dimensional quiver plot displays vectors with components (u,v,w) at the points (x,y,z).
quiver3(X,Y,Z,U,V,W) plots vectors with components (u,v,w) at the points (x,y,z). The matrices X, Y, Z, U, V, W must all be the same size and contain the
corresponding position and vector components.
quiver3(Z,U,V,W) plots the vectors at the equally spaced surface points specified by matrix Z. quiver3 automatically scales the vectors based on the
distance between them to prevent them from overlapping.
quiver3(...,scale) automatically scales the vectors to prevent them from overlapping, then multiplies them by scale. scale = 2 doubles their relative length and scale = 0.5 halves them. Use scale = 0 to plot the vectors without
the automatic scaling.
quiver3(...,LineSpec) specify line type and color using any valid LineSpec. quiver3(...,LineSpec,'filled') fills markers specified by LineSpec. h = quiver3(...) returns a vector of line handles.
Examples
Plot the surface normals of the function
z = xe ( x
2
y2 ) .
[X,Y] = meshgrid(2:0.25:2,1:0.2:1); Z = X.* exp(X.^2 Y.^2); [U,V,W] = surfnorm(X,Y,Z); quiver3(X,Y,Z,U,V,W,0.5); hold on surf(X,Y,Z); colormap hsv
2-184
quiver3
view(-35,45) axis ([-2 2 -1 1 -.6 .6]) hold off
0.6 0.4 0.2 0 -0.2 -0.4 1 0.5 0 -0.5 -1 -1 -2 0 1 2
See Also
axis, contour, LineSpec, plot, plot3, quiver, surfnorm, view
"Direction and Velocity Plots" for related functions Three-Dimensional Quiver Plots for more examples
2-185
qz
Purpose Syntax
2qz
QZ factorization for generalized eigenvalues
[AA,BB,Q,Z,] = qz(A,B) [AA,BB,Q,Z,V,W] = qz(A,B) qz(A,B,flag)
Description
The qz function gives access to intermediate results in the computation of generalized eigenvalues.
[AA,BB,Q,Z] = qz(A,B) for square matrices A and B, produces upper quasitriangular matrices AA and BB, and unitary matrices Q and Z such that Q*A*Z = AA, and Q*B*Z = BB. For complex matrices, AA and BB are triangular. [AA,BB,Q,Z,V,W] = qz(A,B) also produces matrices V and W whose columns
are generalized eigenvectors.
qz(A,B,flag) for real matrices A and B, produces one of two decompositions depending on the value of flag: 'complex'
Produces a possibly complex decomposition with a triangular AA. For compatibility with earlier versions, 'complex' is the default. Produces a real decomposition with a quasitriangular AA, containing 1-by-1 and 2-by-2 blocks on its diagonal.
'real'
If AA is triangular, the diagonal elements of AA and BB, = diag (AA ) and = diag (BB ) , are the generalized eigenvalues that satisfy
A*V* = B*V*
*W ' *A = *W ' *B The eigenvalues produced by = eig (A, B ) are the ratios of the s and s. = ./ If AA is triangular, the diagonal elements of AA and BB,
2-186
qz
alpha = diag(AA) beta = diag(BB)
are the generalized eigenvalues that satisfy
A*V*diag(beta) = B*V*diag(alpha) diag(beta)*W'*A = diag(alpha)*W'*B
The eigenvalues produced by
lambda = eig(A,B)
are the element-wise ratios of alpha and beta.
lambda = alpha ./ beta
If AA is not triangular, it is necessary to further reduce the 2-by-2 blocks to obtain the eigenvalues of the full system.
Algorithm
For real QZ on real A and real B, eig uses the LAPACK DGGES routine. If you request the fifth output V, eig also uses DTGEVC. For complex QZ on real or complex A and B, eig uses the LAPACK ZGGES routine. If you request the fifth output V, eig also uses ZTGEVC.
See Also References
eig
[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-187
rand
Purpose Syntax
2rand
Uniformly distributed random numbers and arrays
Y = rand(n) Y = rand(m,n) Y = rand([m n]) Y = rand(m,n,p,...) Y = rand([m n p...]) Y = rand(size(A)) rand s = rand('state')
Description
The rand function generates arrays of random numbers whose elements are uniformly distributed in the interval (0,1).
Y = rand(n) returns an n-by-n matrix of random entries. An error message appears if n is not a scalar. Y = rand(m,n) or Y = rand([m n]) returns an m-by-n matrix of random
entries.
Y = rand(m,n,p,...) or Y = rand([m n p...]) generates random arrays. Y = rand(size(A)) returns an array of random entries that is the same size as A. rand, by itself, returns a scalar whose value changes each time it's referenced. s = rand('state') returns a 35-element vector containing the current state
of the uniform generator. To change the state of the generator:
rand('state',s) rand('state',0) rand('state',j)
Resets the state to s. Resets the generator to its initial state. For integer j, resets the generator to its j-th state.
rand('state',sum(100*clock)) Resets it to a different state each time.
2-188
rand
Examples
Example 1. R = rand(3,4) may produce
R = 0.2190 0.0470 0.6789 0.6793 0.9347 0.3835 0.5194 0.8310 0.0346 0.0535 0.5297 0.6711
This code makes a random choice between two equally probable alternatives.
if rand < .5 'heads' else 'tails' end
Example 2. Generate a uniform distribution of random numbers on a specified
interval [a,b]. To do this, multiply the output of rand by (b-a) then add a. For example, to generate a 5-by-5 array of uniformly distributed random numbers on the interval [10,50]
a = 10; b = 50; x = a + (b-a) * rand(5) x = 18.1106 17.9489 34.1517 20.8875 17.9526 10.6110 39.8714 27.8039 47.2726 28.6398 26.7460 43.8489 31.0061 18.1059 36.8855 43.5247 10.7856 37.2511 25.1792 43.2718 30.1125 38.3789 27.1557 22.1847 17.5861
See Also
randn, randperm, sprand, sprandn
2-189
randn
Purpose Syntax
2randn
Normally distributed random numbers and arrays
Y = randn(n) Y = randn(m,n) Y = randn([m n]) Y = randn(m,n,p,...) Y = randn([m n p...]) Y = randn(size(A)) randn s = randn('state')
Description
The randn function generates arrays of random numbers whose elements are 2 normally distributed with mean 0, variance = 1 , and standard deviation = 1.
Y = randn(n) returns an n-by-n matrix of random entries. An error message appears if n is not a scalar. Y = randn(m,n) or Y = randn([m n]) returns an m-by-n matrix of random
entries.
Y = randn(m,n,p,...) or Y = randn([m n p...]) generates random arrays. Y = randn(size(A)) returns an array of random entries that is the same size as A. randn, by itself, returns a scalar whose value changes each time it's referenced. s = randn('state') returns a 2-element vector containing the current state
of the normal generator. To change the state of the generator:
randn('state',s) randn('state',0) randn('state',j) randn('state',sum(100*clock))
Resets the state to s. Resets the generator to its initial state. For integer j, resets the generator to its jth state. Resets it to a different state each time.
2-190
randn
Examples
Example 1. R = randn(3,4) may produce
R = 1.1650 0.6268 0.0751 0.3516 -0.6965 1.6961 0.0591 1.7971 0.2641 0.8717 -1.4462 -0.7012
For a histogram of the randn distribution, see hist.
Example 2. Generate a random distribution with a specific mean and variance
. To do this, multiply the output of randn by the standard deviation , and then add the desired mean. For example, to generate a 5-by-5 array of random numbers with a mean of .6 that are distributed with a variance of 0.1
x = .6 + sqrt(0.1) * randn(5) x = 0.8713 0.9966 0.0960 0.1443 0.7806 0.4735 0.8182 0.8579 0.8251 1.0080 0.8114 0.9766 0.2197 0.5937 0.5504 0.0927 0.6814 0.2659 1.0475 0.3454 0.7672 0.6694 0.3085 -0.0864 0.5813
2
See Also
rand, randperm, sprand, sprandn
2-191
randperm
Purpose Syntax Description Remarks Examples
2randperm
Random permutation
p = randperm(n) p = randperm(n) returns a random permutation of the integers 1:n.
The randperm function calls rand and therefore changes rand's state.
randperm(6) might be the vector [3 2 6 4 1 5]
or it might be some other permutation of 1:6.
See Also
permute
2-192
rank
Purpose Syntax Description
2rank
Rank of a matrix
k = rank(A) k = rank(A,tol)
The rank function provides an estimate of the number of linearly independent rows or columns of a full matrix.
k = rank(A) returns the number of singular values of A that are larger than the default tolerance, max(size(A))*norm(A)*eps. k = rank(A,tol) returns the number of singular values of A that are larger than tol.
Remark Algorithm
Use sprank to determine the structural rank of a sparse matrix. There are a number of ways to compute the rank of a matrix. MATLAB uses the method based on the singular value decomposition, or SVD. The SVD algorithm is the most time consuming, but also the most reliable. The rank algorithm is
s = svd(A); tol = max(size(A))*s(1)*eps; r = sum(s > tol);
See Also References
sprank
[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-193
rat, rats
Purpose Syntax
2rat, rats
Rational fraction approximation
[N,D] = rat(X) [N,D] = rat(X,tol) rat(...) S = rats(X,strlen) S = rats(X)
Description
Even though all floating-point numbers are rational numbers, it is sometimes desirable to approximate them by simple rational numbers, which are fractions whose numerator and denominator are small integers. The rat function attempts to do this. Rational approximations are generated by truncating continued fraction expansions. The rats function calls rat, and returns strings.
[N,D] = rat(X) returns arrays N and D so that N./D approximates X to within the default tolerance, 1.e-6*norm(X(:),1). [N,D] = rat(X,tol) returns N./D approximating X to within tol. rat(X), with no output arguments, simply displays the continued fraction. S = rats(X,strlen) returns a string containing simple rational approximations to the elements of X. Asterisks are used for elements that
cannot be printed in the allotted space, but are not negligible compared to the other elements in X. strlen is the length of each string element returned by the rats function. The default is strlen = 13, which allows 6 elements in 78 spaces.
S = rats(X) returns the same results as those printed by MATLAB with format rat.
Examples
Ordinarily, the statement
s = 1 - 1/2 + 1/3 - 1/4 + 1/5 - 1/6 + 1/7
produces
s = 0.7595
2-194
rat, rats
However, with
format rat
or with
rats(s)
the printed result is
s = 319/420
This is a simple rational number. Its denominator is 420, the least common multiple of the denominators of the terms involved in the original expression. Even though the quantity s is stored internally as a binary floating-point number, the desired rational form can be reconstructed. To see how the rational approximation is generated, the statement rat(s) produces
1 + 1/(-4 + 1/(-6 + 1/(-3 + 1/(-5))))
And the statement
[n,d] = rat(s)
produces
n = 319, d = 420
The mathematical quantity is certainly not a rational number, but the MATLAB quantity pi that approximates it is a rational number. pi is the ratio of a large integer and 252:
14148475504056880/4503599627370496
However, this is not a simple rational number. The value printed for pi with format rat, or with rats(pi), is
355/113
This approximation was known in Euclid's time. Its decimal representation is
3.14159292035398
2-195
rat, rats
and so it agrees with pi to seven significant figures. The statement
rat(pi)
produces
3 + 1/(7 + 1/(16))
This shows how the 355/113 was obtained. The less accurate, but more familiar approximation 22/7 is obtained from the first two terms of this continued fraction.
Algorithm
The rat(X) function approximates each element of X by a continued fraction of the form n 1 -- = d 1 + -------------------------------------------------d 1 d 2 + -----------------------------------1 d + ... + ----- 3 d
k
The d s are obtained by repeatedly picking off the integer part and then taking the reciprocal of the fractional part. The accuracy of the approximation increases exponentially with the number of terms and is worst when X = sqrt(2). For x = sqrt(2), the error with k terms is about 2.68*(.173)^k, so each additional term increases the accuracy by less than one decimal digit. It takes 21 terms to get full floating-point accuracy.
See Also
format
2-196
rbbox
Purpose Syntax
2rbbox
Create rubberband box for area selection
rbbox rbbox(initialRect) rbbox(initialRect,fixedPoint) rbbox(initialRect,fixedPoint,stepSize) finalRect = rbbox(...) rbbox initializes and tracks a rubberband box in the current figure. It sets the
Description
initial rectangular size of the box to 0, anchors the box at the figure's CurrentPoint, and begins tracking from this point.
rbbox(initialRect) specifies the initial location and size of the rubberband box as [x y width height], where x and y define the lower-left corner, and width and height define the size. initialRect is in the units specified by the current figure's Units property, and measured from the lower-left corner of the
figure window. The corner of the box closest to the pointer position follows the pointer until rbbox receives a button-up event.
rbbox(initialRect,fixedPoint) specifies the corner of the box that remains fixed. All arguments are in the units specified by the current figure's Units
property, and measured from the lower-left corner of the figure window. fixedPoint is a two-element vector, [x y]. The tracking point is the corner diametrically opposite the anchored corner defined by fixedPoint.
rbbox(initialRect,fixedPoint,stepSize) specifies how frequently the rubberband box is updated. When the tracking point exceeds stepSize figure units, rbbox redraws the rubberband box. The default stepsize is 1. finalRect = rbbox(...) returns a four-element vector, [x y width height], where x and y are the x and y components of the lower-left corner of the box, and width and height are the dimensions of the box.
Remarks
rbbox is useful for defining and resizing a rectangular region:
For box definition, initialRect is [x y 0 0], where (x,y) is the figure's CurrentPoint.
2-197
rbbox
For box resizing, initialRect defines the rectangular region that you resize (e.g., a legend). fixedPoint is the corner diametrically opposite the tracking point.
rbbox returns immediately if a button is not currently pressed. Therefore, you use rbbox with waitforbuttonpress so that the mouse button is down when rbbox is called. rbbox returns when you release the mouse button.
Examples
Assuming the current view is view(2), use the current axes' CurrentPoint property to determine the extent of the rectangle in dataspace units:
k = waitforbuttonpress; point1 = get(gca,'CurrentPoint'); finalRect = rbbox; point2 = get(gca,'CurrentPoint'); point1 = point1(1,1:2); point2 = point2(1,1:2); p1 = min(point1,point2); offset = abs(point1-point2); % button down detected % return figure units % button up detected % extract x and y
% calculate locations % and dimensions
x = [p1(1) p1(1)+offset(1) p1(1)+offset(1) p1(1) p1(1)]; y = [p1(2) p1(2) p1(2)+offset(2) p1(2)+offset(2) p1(2)]; hold on axis manual plot(x,y)
% redraw in dataspace units
See Also
axis, dragrect, waitforbuttonpress
"View Control" for related functions
2-198
rcond
Purpose Syntax Description
2rcond
Matrix reciprocal condition number estimate
c = rcond(A) c = rcond(A) returns an estimate for the reciprocal of the condition of A in 1-norm using the LAPACK condition estimator. If A is well conditioned, rcond(A) is near 1.0. If A is badly conditioned, rcond(A) is near 0.0. Compared to cond, rcond is a more efficient, but less reliable, method of estimating the
condition of a matrix.
Algorithm
rcond uses LAPACK routines to compute the estimate of the reciprocal
condition number:
Matrix
Routine DLANGE, DGETRF, DGECON ZLANGE, ZGETRF, ZGECON
Real Complex
See Also References
cond, condest, norm, normest, rank, svd
[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-199
readasync
Purpose Syntax Arguments
2readasync
Read data asynchronously from the device
readasync(obj) readasync(obj,size) obj size
A serial port object. The number of bytes to read from the device.
Description
readasync(obj) initiates an asynchronous read operation. readasync(obj,size) asynchronously reads, at most, the number of bytes given by size. If size is greater than the difference between the InputBufferSize property value and the BytesAvailable property value, an
error is returned.
Remarks
Before you can read data, you must connect obj to the device with the fopen function. A connected serial port object has a Status property value of open. An error is returned if you attempt to perform a read operation while obj is not connected to the device. You should use readasync only when you configure the ReadAsyncMode property to manual. readasync is ignored if used when ReadAsyncMode is continuous. The TransferStatus property indicates if an asynchronous read or write operation is in progress. You can write data while an asynchronous read is in progress because serial ports have separate read and write pins. You can stop asynchronous read and write operations with the stopasync function. You can monitor the amount of data stored in the input buffer with the BytesAvailable property. Additionally, you can use the BytesAvailableFcn property to execute an M-file callback function when the terminator or the specified amount of data is read.
Rules for Completing an Asynchronous Read Operation
An asynchronous read operation with readasync completes when one of these conditions is met: The terminator specified by the Terminator property is read.
2-200
readasync
The time specified by the Timeout property passes. The specified number of bytes is read. The input buffer is filled (if size is not specified). Because readasync checks for the terminator, this function can be slow. To increase speed, you might want to configure ReadAsyncMode to continuous and continuously return data to the input buffer as soon as it is available from the device.
Example
This example creates the serial port object s, connects s to a Tektronix TDS 210 oscilloscope, configures s to read data asynchronously only if readasync is issued, and configures the instrument to return the peak-to-peak value of the signal on channel 1.
s = serial('COM1'); fopen(s) s.ReadAsyncMode = 'manual'; fprintf(s,'Measurement:Meas1:Source CH1') fprintf(s,'Measurement:Meas1:Type Pk2Pk') fprintf(s,'Measurement:Meas1:Value?')
Begin reading data asynchronously from the instrument using readasync. When the read operation is complete, return the data to the MATLAB workspace using fscanf.
readasync(s) s.BytesAvailable ans = 15 out = fscanf(s) out = 2.0399999619E0 fclose(s)
See Also
Functions
fopen, stopasync
Properties
BytesAvailable, BytesAvailableFcn, ReadAsyncMode, Status, TransferStatus
2-201
real
Purpose Syntax Description Examples See Also
2real
Real part of complex number
X = real(Z) X = real(Z) returns the real part of the elements of the complex array Z. real(2+3*i) is 2. abs, angle, conj, i, j, imag
2-202
reallog
Purpose Syntax Description
2reallog
Natural logarithm for nonnegative real arrays
Y = reallog(X) Y = reallog(X) returns the natural logarithm of each element in array X. Array X must contain only nonnegative real numbers. The size of Y is the same as the size of X. M = magic(4) M = 16 5 9 4 reallog(M) ans = 2.7726 1.6094 2.1972 1.3863 2 11 7 14 3 10 6 15 13 8 12 1
Examples
0.6931 2.3979 1.9459 2.6391
1.0986 2.3026 1.7918 2.7081
2.5649 2.0794 2.4849 0
See Also
log, realpow, realsqrt
2-203
realmax
Purpose Syntax Description Examples Algorithm
2realmax
Largest positive floating-point number
n = realmax n = realmax returns the largest floating-point number representable on a
particular computer. Anything larger overflows.
realmax is one bit less than 21024 or about 1.7977e+308.
The realmax function is equivalent to pow2(2-eps,maxexp), where maxexp is the largest possible floating-point exponent. Execute type realmax to see maxexp for various computers.
See Also
eps, realmin
2-204
realmin
Purpose Syntax Description
2realmin
Smallest positive floating-point number
n = realmin n = realmin returns the smallest positive normalized floating-point number
on a particular computer. Anything smaller underflows or is an IEEE "denormal."
Examples Algorithm
realmin is 2^(-1022) or about 2.2251e-308.
The realmin function is equivalent to pow2(1,minexp) where minexp is the smallest possible floating-point exponent. Execute type realmin to see minexp for various computers.
See Also
eps, realmax
2-205
realpow
Purpose Syntax Description
2realpow
Array power for real-only output
Z = realpow(X,Y) Z = realpow(X,Y) raises each element of array X to the power of its corresponding element in array Y. Arrays X and Y must be the same size. The range of realpow is the set of all real numbers, i.e., all elements of the output array Z must be real. X = -2*ones(3,3) X = -2 -2 -2 -2 -2 -2 -2 -2 -2
Examples
Y = pascal(3) ans = 1 1 1 1 2 3 1 3 6
realpow(X,Y) ans = -2 -2 -2
-2 4 -8
-2 -8 64
See Also
reallog, realsqrt, .^ (array power operator)
2-206
realsqrt
Purpose Syntax Description
2realsqrt
Square root for nonnegative real arrays
Y = realsqrt(X) Y = realsqrt(X) returns the square root of each element of array X. Array X must contain only nonnegative real numbers. The size of Y is the same as the size of X. M = magic(4) M = 16 5 9 4 2 11 7 14 3 10 6 15 13 8 12 1
Examples
realsqrt(M) ans = 4.0000 2.2361 3.0000 2.0000
1.4142 3.3166 2.6458 3.7417
1.7321 3.1623 2.4495 3.8730
3.6056 2.8284 3.4641 1.0000
See Also
reallog, realpow, sqrt, sqrtm
2-207
record
Purpose Syntax Arguments
2record
Record data and event information to a file
record(obj) record(obj,'switch') obj 'switch'
A serial port object. Switch recording capabilities on or off.
Description
record(obj) toggles the recording state for obj. record(obj,'switch') initiates or terminates recording for obj. switch can be on or off. If switch is on, recording is initiated. If switch is off, recording
is terminated.
Remarks
Before you can record information to disk, obj must be connected to the device with the fopen function. A connected serial port object has a Status property value of open. An error is returned if you attempt to record information while obj is not connected to the device. Each serial port object must record information to a separate file. Recording is automatically terminated when obj is disconnected from the device with fclose. The RecordName and RecordMode properties are read-only while obj is recording, and must be configured before using record. For a detailed description of the record file format and the properties associated with recording data and event information to a file, refer to "Debugging: Recording Information to Disk."
Example
This example creates the serial port object s, connects s to the device, configures s to record information to a file, writes and reads text data, and then disconnects s from the device.
s = serial('COM1'); fopen(s) s.RecordDetail = 'verbose'; s.RecordName = 'MySerialFile.txt'; record(s,'on') fprintf(s,'*IDN?') out = fscanf(s);
2-208
record
record(s,'off') fclose(s)
See Also
Functions
fclose, fopen
Properties
RecordDetail, RecordMode, RecordName, RecordStatus, Status
2-209
rectangle
Purpose Syntax
2rectangle
Create a 2-D rectangle object
rectangle rectangle('Position',[x,y,w,h]) rectangle(...,'Curvature',[x,y]) h = rectangle(...) rectangle draws a rectangle with Position [0,0,1,1] and Curvature [0,0]
Description
(i.e., no curvature).
rectangle('Position',[x,y,w,h]) draws the rectangle from the point x,y and having a width of w and a height of h. Specify values in axes data units.
Note that, to display a rectangle in the specified proportions, you need to set the axes data aspect ratio so that one unit is of equal length along both the x and y axes. You can do this with the command axis equal or daspect([1,1,1]).
rectangle(...,'Curvature',[x,y]) specifies the curvature of the rectangle sides, enabling it to vary from a rectangle to an ellipse. The horizontal curvature x is the fraction of width of the rectangle that is curved along the top and bottom edges. The vertical curvature y is the fraction of the height of the rectangle that is curved along the left and right edges.
The values of x and y can range from 0 (no curvature) to 1 (maximum curvature). A value of [0,0] creates a rectangle with square sides. A value of [1,1] creates an ellipse. If you specify only one value for Curvature, then the same length (in axes data units) is curved along both horizontal and vertical sides. The amount of curvature is determined by the shorter dimension.
h = rectangle(...) returns the handle of the rectangle object created.
Remarks
Rectangle objects are 2-D and can be drawn in an axes only if the view is [0 90] (i.e., view(2)). Rectangles are children of axes and are defined in coordinates of the axes data. This example sets the data aspect ratio to [1,1,1] so that the rectangle displays in the specified proportions (daspect). Note that the horizontal and vertical curvature can be different. Also, note the effects of using a single value for Curvature.
Examples
2-210
rectangle
rectangle('Position',[0.59,0.35,3.75,1.37],... 'Curvature',[0.8,0.4],... 'LineWidth',2,'LineStyle','--') daspect([1,1,1])
2 1.8 1.6 1.4 1.2 1 0.8 0.6 0.4 0.2 0 0.5 1 1.5 2 2.5 3 3.5 4 4.5
Specifying a single value of [0.4] for Curvature produces:
2 1.8 1.6 1.4 1.2 1 0.8 0.6 0.4 0.2 0 0.5 1 1.5 2 2.5 3 3.5 4 4.5
A Curvature of [1] produces a rectangle with the shortest side completely round:
2-211
rectangle
2 1.8 1.6 1.4 1.2 1 0.8 0.6 0.4 0.2 0 0.5 1 1.5 2 2.5 3 3.5 4 4.5
This example creates an ellipse and colors the face red.
rectangle('Position',[1,2,5,10],'Curvature',[1,1],... 'FaceColor','r') daspect([1,1,1]) xlim([0,7]) ylim([1,13])
2-212
rectangle
12
10
8
6
4
2
0
1
2
3
4
5
6
7
See Also Object Hierarchy
line, patch, rectangle properties
"Object Creation Functions" for related functions
Root
Figure
Axes
Uicontrol
Uimenu
Uicontextmenu
Image
Light
Line
Patch
Rectangle
Surface
Text
2-213
rectangle
Setting Default Properties
You can set default rectangle properties on the axes, figure, and root levels.
set(0,'DefaultRectangleProperty',PropertyValue...) set(gcf,'DefaultRectangleProperty',PropertyValue...) set(gca,'DefaultRectangleProperty',PropertyValue...)
Where Property is the name of the rectangle property whose default value you want to set and PropertyValue is the value you are specifying. Use set and get to access the surface properties.
Property List
The following table lists all rectangle properties and provides a brief description of each. The property name links take you to an expanded description of the properties.
Property Description Property Value
Property Name Defining the Rectangle Object Curvature
Degree of horizontal and vertical curvature Method of drawing and erasing the rectangle (useful for animation) Color of rectangle edges Color of rectangle interior Line style of edges Width of edge lines in points Location and width and height of rectangle
Value: two-element vector with values between 0 and 1 Default: [0,0] Values: normal, none, xor,
background Default: normal
EraseMode
EdgeColor
Value: ColorSpec or none Default: ColorSpec [0,0,0] Value: ColorSpec or none Default: none Values: -, --, :, -., none Default: - Value: scalar Default: 0.5 points Value: [x,y,width,height] Default: [0,0,1,1]
FaceColor
LineStyle
LineWidth
Position
2-214
rectangle
Property Name
Property Description
Property Value
General Information About Rectangle Objects Children Parent Selected
Rectangle objects have no children Axes object Indicate if the rectangle is in a "selected" state. User-specified label The type of graphics object (read only) User-specified data Value: handle of axes Value: on, off Default: off Value: any string Default: '' (empty string) Value: the string
'rectangle'
Tag
Type
UserData
Value: any matrix Default: [] (empty matrix)
Properties Related to Callback Routine Execution BusyAction
Specify how to handle callback routine interruption Define a callback routine that executes when a mouse button is pressed on over the rectangle Define a callback routine that executes when a rectangle is created Define a callback routine that executes when the rectangle is deleted (via close or delete) Determine if callback routine can be interrupted Associate a context menu with the rectangle
Value: cancel, queue Default: queue Value: string or function handle Default: '' (empty string) Value: string or function handle Default: '' (empty string) Values: string or function handle Default: '' (empty string) Values: on, off Default: on (can be interrupted) Values: handle of a Uicontextmenu
ButtonDownFcn
CreateFcn
DeleteFcn
Interruptible
UIContextMenu
2-215
rectangle
Property Name Controlling Access to Objects HandleVisibility
Property Description
Property Value
Determines if and when the rectangle's handle is visible to other functions Determines if the rectangle can become the current object (see the Figure CurrentObject property)
Values: on, callback, off Default: on Values: on, off Default: on
HitTest
Controlling the Appearance Clipping
Clipping to axes rectangle Highlight rectangle when selected (Selected property set to on) Make the rectangle visible or invisible
Values: on, off Default: on Values: on, off Default: on Values: on, off Default: on
SelectionHighlight
Visible
2-216
rectangle properties
Modifying Properties
2rectangle 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.
Rectangle Property Descriptions
This section lists property names along with the type of values each accepts. Curly braces { } enclose default values.
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 routes 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 over the rectangle object. 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.
Children
vector of handles
The empty matrix; rectangle objects have no children.
2-217
rectangle properties
Clipping
{on} | off
Clipping mode. MATLAB clips rectangles to the axes plot box by default. If you set Clipping to off, rectangles display outside the axes plot box. This can occur if you create a rectangle, set hold to on, freeze axis scaling (axis manual), and then create a larger rectangle.
CreateFcn
string or function handle
Callback routine executed during object creation. This property defines a callback routine that executes when MATLAB creates a rectangle object. You must define this property as a default value for rectangles. For example, the statement,
set(0,'DefaultRectangleCreateFcn',...
'set(gca,''DataAspectRatio'',[1,1,1])')
defines a default value on the root level that sets the axes DataAspectRatio whenever you create a rectangle object. MATLAB executes this routine after setting all rectangle properties. Setting this property on an existing rectangle object has no effect. The handle of the object whose CreateFcn is being executed is accessible only through the root CallbackObject property, which you can query using gcbo. See Function Handle Callbacks for information on how to use function handles to define the callback function.
Curvature
one- or two-element vector [x,y]
Amount of horizontal and vertical curvature. This property specifies the curvature of the rectangle sides, which enables the shape of the rectangle to vary from rectangular to ellipsoidal. The horizontal curvature x is the fraction of width of the rectangle that is curved along the top and bottom edges. The vertical curvature y is the fraction of the height of the rectangle that is curved along the left and right edges. The values of x and y can range from 0 (no curvature) to 1 (maximum curvature). A value of [0,0] creates a rectangle with square sides. A value of [1,1] creates an ellipse. If you specify only one value for Curvature, then the same length (in axes data units) is curved along both horizontal and vertical sides. The amount of curvature is determined by the shorter dimension.
2-218
rectangle properties
DeleteFcn
string or function handle
Delete rectangle callback routine. A callback routine that executes when you delete the rectangle object (e.g., when you issue a delete command or clear the axes or figure). MATLAB executes the routine before deleting the object's properties so these values are available to the callback routine. The handle of the object whose DeleteFcn is being executed is accessible only through the root CallbackObject property, which you can query using gcbo. See Function Handle Callbacks for information on how to use function handles to define the callback function.
EdgeColor {ColorSpec} | none
Color of the rectangle edges. This property specifies the color of the rectangle edges as a color or specifies that no edges be drawn.
EraseMode {normal} | none | xor | background
Erase mode. This property controls the technique MATLAB uses to draw and erase rectangle objects. Alternative erase modes are useful for creating animated sequences, where control of the way individual objects redraw is necessary to improve performance and obtain the desired effect. normal (the default) Redraw the affected region of the display, performing the three-dimensional analysis necessary to ensure that all objects are rendered correctly. This mode produces the most accurate picture, but is the slowest. The other modes are faster, but do not perform a complete redraw and are therefore less accurate. none Do not erase the rectangle when it is moved or destroyed. While the object is still visible on the screen after erasing with EraseMode none, you cannot print it because MATLAB stores no information about its former location. xor Draw and erase the rectangle by performing an exclusive OR (XOR) with the color of the screen beneath it. This mode does not damage the color of the objects beneath the rectangle. However, the rectangle's color depends on the color of whatever is beneath it on the display. background Erase the rectangle by drawing it in the Axes' background Color, or the Figure background Color if the Axes Color is set to none. This damages objects that are behind the erased rectangle, but rectangles are always properly colored.
2-219
rectangle properties
Printing with Non-normal Erase Modes.
MATLAB always prints Figures as if the EraseMode of all objects is normal. This means graphics objects created with EraseMode set to none, xor, or background can look different on screen than on paper. On screen, MATLAB may mathematically combine layers of colors (e.g., XORing a pixel color with that of the pixel behind it) and ignore three-dimensional sorting to obtain greater rendering speed. However, these techniques are not applied to the printed output. You can use the MATLAB getframe command or other screen capture application to create an image of a Figure containing non-normal mode objects.
FaceColor ColorSpec | {none}
Color of rectangle face. This property specifies the color of the rectangle face, which is not colored by default.
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 evaling 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-220
rectangle 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 rectangle 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 rectangle. If HitTest is off, clicking on the rectangle selects the object below it (which may be the axes containing it).
Interruptible {on} | off
Callback routine interruption mode. The Interruptible property controls whether a rectangle 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.
LineStyle {-} | -- | : | -. | none
Line style of rectangle edge. This property specifies the line style of the edges. The available line styles are:
Symbol Line Style
- --
:
solid line (default) dashed line dotted line dash-dot line
-.
2-221
rectangle properties
Symbol none LineWidth
Line Style
no line scalar
The width of the rectangle edge line. Specify this value in points (1 point = 1/72 inch). The default LineWidth is 0.5 points.
Parent
handle
rectangle's parent. The handle of the rectangle object's parent axes. You can move a rectangle object to another axes by changing this property to the new axes handle.
Position
four-element vector [x,y,width,height]
Location and size of rectangle. This property specifies the location and size of the rectangle in the data units of the axes. The point defined by x, y specifies one corner of the rectangle, and width and height define the size in units along the x and y axes respecitvely.
Selected on | off
Is object selected? When this property is on MATLAB displays selection handles if the SelectionHighlight property is also on. You can, for example, define the ButtonDownFcn to set this property, allowing users to select the object with the mouse.
SelectionHighlight {on} | off
Objects highlight when selected. When the Selected property is on, MATLAB indicates the selected state by drawing handles at each vertex. When SelectionHighlight is off, MATLAB does not draw the handles.
Tag
string
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. You can define Tag as any string.
2-222
rectangle properties
Type
string (read only)
Class of graphics object. For rectangle objects, Type is always the string 'rectangle'.
UIContextMenu
handle of a uicontextmenu object
Associate a context menu with the rectangle. Assign this property the handle of a uicontextmenu object created in the same figure as the rectangle. Use the uicontextmenu function to create the context menu. MATLAB displays the context menu whenever you right-click over the rectangle.
UserData
matrix
User-specified data. Any data you want to associate with the rectangle object. MATLAB does not use this data, but you can access it using the set and get commands.
Visible {on} | off
rectangle visibility. By default, all rectangles are visible. When set to off, the rectangle is not visible, but still exists and you can get and set its properties.
2-223
rectint
Purpose Syntax Description
2rectint
Rectangle intersection area.
area = rectint(A,B) area = rectint(A,B) returns the area of intersection of the rectangles specified by position vectors A and B.
If A and B each specify one rectangle, the output area is a scalar.
A and B can also be matrices, where each row is a position vector. area is then a matrix giving the intersection of all rectangles specified by A with all the rectangles specified by B. That is, if A is n-by-4 and B is m-by-4, then area is an n-by-m matrix where area(i,j) is the intersection area of the rectangles specified by the ith row of A and the jth row of B.
Note A position vector is a four-element vector [x,y,width,height], where the point defined by x and y specifies one corner of the rectangle, and width and height define the size in units along the x and y axes respectively.
See Also
polyarea
2-224
reducepatch
Purpose Syntax
2reducepatch
Reduce the number of patch faces
reducepatch(p,r) nfv = reducepatch(p,r) nfv = reducepatch(fv,r) reducepatch(...,'fast') reducepatch(...,'verbose') nfv = reducepatch(f,v,r) [nf,nv] = reducepatch(...) reducepatch(p,r) reduces the number of faces of the patch identified by handle p, while attempting to preserve the overall shape of the original object. MATLAB interprets the reduction factor r in one of two ways depending on its
Description
value: If r is less than 1, r is interpreted as a fraction of the original number of faces. For example, if you specify r as 0.2, then the number of faces is reduced to 20% of the number in the original patch. If r is greater than or equal to 1, then r is the target number of faces. For example, if you specify r as 400, then the number of faces is reduced until there are 400 faces remaining.
nfv = reducepatch(p,r) returns the reduced set of faces and vertices but does not set the Faces and Vertices properties of patch p. The struct nfv contains the faces and vertices after reduction. nfv = reducepatch(fv,r) performs the reduction on the faces and vertices in the struct fv. nfv = reducepatch(p) or nfv = reducepatch(fv) uses a reduction value of 0.5. reducepatch(...,'fast') assumes the vertices are unique and does not
compute shared vertices.
reducepatch(...,'verbose') prints progress messages to the command
window as the computation progresses.
nfv = reducepatch(f,v,r) performs the reduction on the faces in f and the vertices in v.
2-225
reducepatch
[nf,nv] = reducepatch(...) returns the faces and vertices in the arrays nf and nv.
Remarks
If the patch contains nonshared vertices, MATLAB computes shared vertices before reducing the number of faces. If the faces of the patch are not triangles, MATLAB triangulates the faces before reduction. The faces returned are always defined as triangles. The number of output triangles may not be exactly the number specified with the reduction factor argument (r), particularly if the faces of the original patch are not triangles.
Examples
This example illustrates the effect of reducing the number of faces to only 15% of the original value.
[x,y,z,v] = flow; p = patch(isosurface(x,y,z,v,-3)); set(p,'facecolor','w','EdgeColor','b'); daspect([1,1,1]) view(3) figure; h = axes; p2 = copyobj(p,h); reducepatch(p2,0.15) daspect([1,1,1]) view(3)
2-226
reducepatch
Before Reduction
3 2 1 0 -1 -2 -3 4 2 0 -2 -4 0 4 2 6 8
10
2-227
reducepatch
After Reduction to 15% of Original Number of Faces
3 2 1 0 -1 -2 -3 4 2 0 4 -2 -4 0 2 6 8
10
See Also
isosurface, isocaps, isonormals, smooth3, subvolume, reducevolume
"Volume Visualization" for related functions Vector Field Displayed with Cone Plots for another example
2-228
reducevolume
Purpose Syntax
2reducevolume
Reduce the number of elements in a volume data set
[nx,ny,nz,nv] = reducevolume(X,Y,Z,V,[Rx,Ry,Rz]) [nx,ny,nz,nv] = reducevolume(V,[Rx,Ry,Rz]) nv = reducevolume(...) [nx,ny,nz,nv] = reducevolume(X,Y,Z,V,[Rx,Ry,Rz]) reduces the number of elements in the volume by retaining every Rxth element in the x direction, every Ryth element in the y direction, and every Rzth element in the z direction. If a scalar R is used to indicate the amount or reduction instead of a 3-element vector, MATLAB assumes the reduction to be [R R R].
Description
The arrays X, Y, and Z define the coordinates for the volume V. The reduced volume is returned in nv and the coordinates of the reduced volume are returned in nx, ny, and nz.
[nx,ny,nz,nv] = reducevolume(V,[Rx,Ry,Rz]) assumes the arrays X, Y, and Z are defined as [X,Y,Z] = meshgrid(1:n,1:m,1:p) where [m,n,p] = size(V). nv = reducevolume(...) returns only the reduced volume.
Examples
This example uses a data set that is a collection of MRI slices of a human skull. This data is processed in a variety of ways: The 4-D array is squeezed (squeeze) into three dimensions and then reduced (reducevolume) so that what remains is every 4th element in the x and y directions and every element in the z direction. The reduced data is smoothed (smooth3). The outline of the skull is an isosurface generated as a patch (p1) whose vertex normals are recalculated to improve the appearance when lighting is applied (patch, isosurface, isonormals). A second patch (p2) with an interpolated face color draws the end caps (FaceColor, isocaps). The view of the object is set (view, axis, daspect). A 100-element grayscale colormap provides coloring for the end caps (colormap).
2-229
reducevolume
Adding a light to the right of the camera illuminates the object (camlight, lighting).
load mri D = squeeze(D); [x,y,z,D] = reducevolume(D,[4,4,1]); D = smooth3(D); p1 = patch(isosurface(x,y,z,D, 5,'verbose'),... 'FaceColor','red','EdgeColor','none'); isonormals(x,y,z,D,p1); p2 = patch(isocaps(x,y,z,D, 5),... 'FaceColor','interp','EdgeColor','none'); view(3); axis tight; daspect([1,1,.4]) colormap(gray(100)) camlight; lighting gouraud
See Also
isosurface, isocaps, isonormals, smooth3, subvolume, reducepatch
"Volume Visualization" for related functions
2-230
refresh
Purpose Syntax Description
2refresh
Redraw current figure
refresh refresh(h) refresh erases and redraws the current figure. refresh(h) redraws the figure identified by h.
See Also
"Figure Windows" for related functions
2-231
regexp
Purpose Syntax
2regexp
Match regular expression
start = regexp(str,expr) [start,finish] = regexp(str,expr) [start,finish,tokens] = regexp(str,expr) [...] = regexp(str,expr,'once') start = regexp(str,expr) returns a row vector, start, containing the indices of the substrings in str that match the regular expression string, expr.
Description
When either str or expr is a cell array of strings, regexp returns an m-by-n cell array of row vectors of indices, where m is the the number of strings in str and n is the number of regular expression patterns in expr.
[start,finish] = regexp(str,expr) returns an additional row vector finish, that contains the indices of the last character of the corresponding substrings in start. [start,finish,tokens] = regexp(str,expr) returns a 1-by-n cell array, tokens, of beginining and ending indices of tokens within the corresponding substrings in start and finish. Tokens are denoted by parentheses in the expression, expr. [...] = regexp(str,expr,'once') finds just the first match. (By default, regexp returns all matches.) If no matches are found, then all return values are
empty.
Remarks
See "Regular Expressions", in the MATLAB documentation, for a listing of all regular expression metacharacters supported by MATLAB.
regexp does not support international character sets.
Examples
Example 1
Return a row vector of indices that match words that start with c, end with t, and contain one or more vowels between them:
str = 'bat cat can car coat court cut ct caoueouat'; regexp(str, 'c[aeiou]+t') ans = 5 17 28 35
2-232
regexp
Example 2
Return a cell array of row vectors of indices that match capital letters and whitespaces in the cell array of strings, str:
str = {'Madrid, Spain' 'Romeo and Juliet' 'MATLAB is great'}; s = regexp(str, {'[A-Z]' '\s'});
Capital letters, '[A-Z]', were found at these str indices:
s{:,1} ans = 1 ans = 1 ans = 1
9 11 2 3 4 5 6
Space characters, '\s', were found at these str indices:
s{:,2} ans = 8 ans = 6 ans = 7
10 10
Example 3
Return the starting and ending indices of words containing the letter x:
str = 'regexp helps you relax'; [s,f] = regexp(str, '\w*x\w*') s = 1 18 f = 6 22
2-233
regexp
Example 4
Return the starting and ending indices of substrings contained by the letter s. Also return the starting and ending indices of the token defined within the parentheses:
str = 'six sides of a hexagon'; [s,f,t] = regexp(str, 's(\w*)s') s = 5 f = 9 t = [1x2 double] t{:} ans = 6 8
See Also
regexpi, regexprep, strfind, findstr, strmatch, strcmp, strcmpi, strncmp, strncmpi
2-234
regexpi
Purpose Syntax
2regexpi
Match regular expression, ignoring case
start = regexpi(str,expr) [start,finish] = regexpi(str,expr) [start,finish,tokens] = regexpi(str,expr) [...] = regexpi(str,expr,'once') start = regexpi(str,expr) returns a row vector, start, containing the indices of the substrings in str that match the regular expression string, expr,
Description
regardless of case. When either str or expr is a cell array of strings, regexpi returns an m-by-n cell array of row vectors of indices, where m is the the number of strings in str and n is the number of regular expression patterns in expr.
[start,finish] = regexpi(str,expr) returns an additional row vector finish, that contains the indices of the last character of the corresponding substrings in start. [start,finish,tokens] = regexpi(str,expr) returns a 1-by-n cell array, tokens, of beginining and ending indices of tokens within the corresponding substrings in start and finish. Tokens are denoted by parentheses in the expression, expr. [...] = regexpi(str,expr,'once') finds just the first match. (By default, regexp returns all matches.) If no matches are found, then all return values are
empty.
Remarks
See "Regular Expressions", in the MATLAB documentation, for a listing of all regular expression metacharacters supported by MATLAB.
regexpi does not support international character sets.
Examples
Return a row vector of indices that match words that start with m and end with y, regardless of case:
str = 'My flowers may bloom in May'; pat = 'm\w*y';
2-235
regexpi
regexpi(str, pat) ans = 1 12 25
See Also
regexp, regexprep, strfind, findstr, strmatch, strcmp, strcmpi, strncmp, strncmpi
2-236
regexprep
Purpose Syntax Description
2regexprep
Replace string using regular expression
s = regexprep(str,expr,replace) s = regexprep(str,expr,replace,options) s = regexprep(str,expr,replace) replaces all occurrences of the regular expression, expr, in string, str, with the string, replace. The new string is returned. If no matches are found regexprep returns str unchanged.
When any of str, expr, or replace are cell arrays of strings, regexprep returns an m-by-n-by-p cell array of strings, where m is the number of strings in str, n is the number of regular expressions in expr, and p is the number of strings in replace.
s = regexprep(str,expr,replace,options) By default, regexprep replaces
all matches, is case sensitive, and does not use tokens. You can use one or more of the following options with regexprep.
Option ignorecase preservecase Description
Ignore the case of characters when matching expr to str. Ignore case when matching (as with 'ignorecase'), but override the case of replace characters with the case of corresponding characters in str when replacing. Modify replace to use the tokens delimited by parenthesis in expr such that $1 is the first token, $2 is the second token, ..., and $N is the Nth token. Replace only the first occurrence of expr in str. Replace only the Nth occurrence of expr in str.
tokenize
once N
Remarks
See "Regular Expressions", in the MATLAB documentation, for a listing of all regular expression metacharacters supported by MATLAB.
regexprep does not support international character sets.
2-237
regexprep
Examples Example 1
Perform a case-sensitive replacement on words starting with m and ending with y:
str = 'My flowers may bloom in May'; pat = 'm(\w*)y'; regexprep(str, pat, 'April') ans = My flowers April bloom in May
Replace all words starting with m and ending with y, regardless of case, but maintain the original case in the replacement strings:
regexprep(str, pat, 'April', 'preservecase') ans = April flowers april bloom in April
Example 2
Replace all variations of the words 'walk up' using the letters following walk as a token.
str = 'I walk up, they walked up, we are walking up, she walks.'; pat = 'walk(\w*) up'; regexprep(str, pat, 'ascend$1', 'tokenize') ans = I ascend, they ascended, we are ascending, she walks.
See Also
regexp, regexpi, strfind, findstr, strmatch, strcmp, strcmpi, strncmp, strncmpi
2-238
registerevent (COM)
Purpose Syntax Arguments
2registerevent (COM)
Register an event handler with a control's event
registerevent(h, callback | {event1 eventhandler1; event2 eventhandler2; ...}) h
Handle for a MATLAB COM control object.
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/API documentation for more information on handling control events.
event
Any event associated with h that can be triggered. Specify event using the event 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/API documentation for more information on handling control events.
Description
Register one or more events with a single callback function or with a separate handler function for each event. You can either register events at the time you create the control (using actxcontrol), or register them dynamically at any time after the control has been created (using registerevent). 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
2-239
registerevent (COM)
some cases, using the cell array technique creates more efficient code that results in better performance.
Examples
Create an mwsamp control and list all events associated with the control:
f = figure ('pos', [100 200 200 200]); h = actxcontrol ('mwsamp.mwsampctrl.2', [0 0 200 200], f); events(h) ans = Click = void Click() DblClick = void DblClick() MouseDown = void MouseDown(int16 Button, int16 Shift, Variant x, Variant y)
Register all events with the same callback routine, sampev. Use the eventlisteners function to see the event handler used by each event:
registerevent(h, 'sampev'); eventlisteners(h) ans = 'click' 'sampev' 'dblclick' 'sampev' 'mousedown' 'sampev' unregisterallevents(h);
Register the Click and DblClick events with event handlers myclick and my2click, respectively:
registerevent(h, {'click' 'myclick'; 'dblclick' 'my2click'}); eventlisteners(h) ans = 'click' 'myclick' 'dblclick' 'my2click'
See Also
events, eventlisteners, unregisterevent, unregisterallevents, isevent
2-240
rehash
Purpose Syntax
2rehash
Refresh function and file system path caches
rehash rehash rehash rehash rehash rehash
path toolbox pathreset toolboxreset toolboxcache
Description
rehash with no arguments updates the MATLAB list of known files and classes for directories on the search path that are not in $matlabroot/toolbox. It
compares the timestamps for loaded functions (functions that have been called but not cleared in the current session) against their timestamps on disk. It clears loaded functions if the files on disk are newer. All of this normally happens each time MATLAB displays the Command Window prompt. Therefore, use rehash with no arguments only when you run an M-file that updates another M-file, and the calling file needs to reuse the updated version before it has finished running.
rehash path performs the same updates as rehash, but uses a different
technique for detecting the files and directories that require updates. If you receive a warning during MATLAB startup notifying you that MATLAB could not tell if a directory has changed and you encounter problems with MATLAB using the most current versions of your M-files, run rehash path.
rehash toolbox updates all directories in $matlabroot/toolbox. Run this when you add or remove files in $matlabroot/toolbox during a session by
some means other than MATLAB tools, like the Editor.
rehash pathreset performs the same updates as rehash path, and also
ensures the known files and classes list follows precedence rules for shadowed functions.
rehash toolboxreset performs the same updates as rehash toolbox, and
also ensures the known files and classes list follows precedence rules for shadowed functions.
2-241
rehash
rehash toolboxcache performs the same updates as rehash toolbox, and
also updates the cache file. This is the equivalent of clicking the Update Toolbox Path Cache button in General Preferences.
See Also
addpath, clear, path, rmpath
"Toolbox Path Caching" in MATLAB Development Environment.
2-242
release (COM)
Purpose Syntax Arguments Description
2release (COM)
Release an interface
release(h) h
Handle for a COM object that represents the interface to be released. Release the interface and all resources used by the interface. Each interface handle must be released when you are finished manipulating its properties and invoking its methods. Once an interface has been released, it is no longer valid and subsequent operations on the MATLAB object that represents that interface will result in errors.
Note Releasing the interface will not delete the control itself (see delete), since other interfaces on that object may still be active. See "Releasing Interfaces" in the External Interfaces/API documentation for more information.
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:
2-243
release (COM)
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:
delete(cal); delete(f); clear f;
See Also
delete, save, load, actxcontrol, actxserver
2-244
rem
Purpose Syntax Description
2rem
Remainder after division
R = rem(X,Y) R = rem(X,Y) if Y ~= 0, returns X - n.*Y where n = fix(X./Y). If Y is not an integer and the quotient X./Y is within roundoff error of an integer, then n is that integer. By convention, rem(X,0) is NaN. The inputs X and Y must be real
arrays of the same size, or real scalars.
Remarks
So long as operands X and Y are of the same sign, the statement rem(X,Y) returns the same result as does mod(X,Y). However, for positive X and Y,
rem(-X,Y) = mod(-X,Y)-Y
The rem function returns a result that is between 0 and sign(X)*abs(Y). If Y is zero, rem returns NaN.
See Also
mod
2-245
repmat
Purpose Syntax
2repmat
Replicate and tile an array
B = repmat(A,m,n) B = repmat(A,[m n]) B = repmat(A,[m n p...]) repmat(A,m,n) B = repmat(A,m,n) creates a large matrix B consisting of an m-by-n tiling of copies of A. The statement repmat(A,n) creates an n-by-n tiling. B = repmat(A,[m n]) accomplishes the same result as repmat(A,m,n). B = repmat(A,[m n p...]) produces a multidimensional (m-by-n-by-p-by-...) array composed of copies of A. A may be multidimensional. repmat(A,m,n) when A is a scalar, produces an m-by-n matrix filled with A's value. This can be much faster than a*ones(m,n) when m or n is large.
Description
Examples
In this example, repmat replicates 12 copies of the second-order identity matrix, resulting in a "checkerboard" pattern.
B = repmat(eye(2),3,4) B = 1 0 1 0 1 0 0 1 0 1 0 1 1 0 1 0 1 0 0 1 0 1 0 1 1 0 1 0 1 0 0 1 0 1 0 1 1 0 1 0 1 0 0 1 0 1 0 1
The statement N = repmat(NaN,[2 3]) creates a 2-by-3 matrix of NaNs.
2-246
reset
Purpose Syntax Description
2reset
Reset graphics object properties to their defaults
reset(h) reset(h) resets all properties having factory defaults on the object identified by h. To see the list of factory defaults, use the statement, get(0,'factory')
If h is a figure, MATLAB does not reset Position, Units, PaperPosition, and PaperUnits. If h is an axes, MATLAB does not reset Position and Units.
Examples
reset(gca) resets the properties of the current axes. reset(gcf) resets the properties of the current figure.
See Also
cla, clf, gca, gcf, hold
"Object Manipulation" for related functions
2-247
reshape
Purpose Syntax
2reshape
Reshape array
B B B B B = = = = = reshape(A,m,n) reshape(A,m,n,p,...) reshape(A,[m n p ...]) reshape(A,...,[],...) reshape(A,siz)
Description
B = reshape(A,m,n) returns the m-by-n matrix B whose elements are taken column-wise from A. An error results if A does not have m*n elements. B = reshape(A,m,n,p,...) or B = reshape(A,[m n p ...]) returns an N-D array with the same elements as A but reshaped to have the size m-by-n-by-p-by-... . The product of the specified dimensions, m*n*p*..., must be the same as prod(size(A)). B = reshape(A,...,[],...) calculates the length of the dimension represented by the placeholder [], such that the product of the dimensions equals prod(size(A)). The value of prod(size(A)) must be evenly divisible by the product of the specified dimensions. You can use only one occurence of []. B = reshape(A,siz) returns an N-D array with the same elements as A, but reshaped to siz, a vector representing the dimensions of the reshaped array. The quantity prod(siz) must be the same as prod(size(A)).
Examples
Reshape a 3-by-4 matrix into a 2-by-6 matrix.
A = 1 2 3 4 5 6 7 8 9 10 11 12
B = reshape(A,2,6) B = 1 3 5 7 2 4 6 8 B = reshape(A,2,[]) 9 10 11 12
2-248
reshape
B = 1 2 3 4 5 6 7 8 9 10 11 12
See Also
shiftdim, squeeze
The colon operator :
2-249
residue
Purpose Syntax Description
2residue
Convert between partial fraction expansion and polynomial coefficients
[r,p,k] = residue(b,a) [b,a] = residue(r,p,k)
The residue function converts a quotient of polynomials to pole-residue representation, and back again.
[r,p,k] = residue(b,a) finds the residues, poles, and direct term of a partial
fraction expansion of the ratio of two polynomials, b ( s ) and a ( s ) , of the form b1 s + b2 s + b3 s + ... + bm + 1 b(s) ---------- = -----------------------------------------------------------------------------------------------------n n1 n2 a(s) + a3 s + ... + an + 1 a1 s + a2 s where b j and a j are the jth elements of the input vectors b and a.
[b,a] = residue(r,p,k) converts the partial fraction expansion back to the polynomials with coefficients in b and a.
m m1 m2
Definition
If there are no multiple roots, then r1 r2 rn b(s) ---------- = -------------- + -------------- + ... + --------------- + k ( s ) a(s) s p1 s p2 s pn The number of poles n is
n = length(a)-1 = length(r) = length(p)
The direct term coefficient vector is empty if length(b) < length(a); otherwise
length(k) = length(b)-length(a)+1
If p(j) = ... = p(j+m-1) is a pole of multiplicity m, then the expansion includes terms of the form rj rj+m1 rj+1 -------------- + ---------------------- + ... + ----------------------s p j ( s p )2 ( s p )m
j j
2-250
residue
Arguments
b,a r p k
Vectors that specify the coefficients of the polynomials in descending powers of s Column vector of residues Column vector of poles Row vector of direct terms
Algorithm
It first obtains the poles with roots. Next, if the fraction is nonproper, the direct term k is found using deconv, which performs polynomial long division. Finally, the residues are determined by evaluating the polynomial with individual roots removed. For repeated roots, resi2 computes the residues at the repeated root locations. Numerically, the partial fraction expansion of a ratio of polynomials represents an ill-posed problem. If the denominator polynomial, a ( s ) , is near a polynomial with multiple roots, then small changes in the data, including roundoff errors, can make arbitrarily large changes in the resulting poles and residues. Problem formulations making use of state-space or zero-pole representations are preferable. If the ratio of two polynomials is expressed as b(s) 5s + 3s 2s + 7 ---------- = ---------------------------------------------3 a(s) 4s + 8s + 3 then
b = [ 5 3 -2 7] a = [-4 0 8 3]
3 2
Limitations
Examples
and you can calculate the partial fraction expansion as
[r, p, k] = residue(b,a) r = -1.4167 -0.6653 1.3320
2-251
residue
p = 1.5737 -1.1644 -0.4093 k = -1.2500
Now, convert the partial fraction expansion back to polynomial coefficients.
[b,a] = residue(r,p,k) b = -1.2500 a = 1.0000 -0.0000 -2.0000 -0.7500 -0.7500 0.5000 -1.7500
The result can be expressed as b(s) 1.25s 0.75s + 0.50s 1.75 ---------- = ----------------------------------------------------------------------------------3 a(s) s 2.00s 0.75 Note that the result is normalized for the leading coefficient in the denominator.
3 2
See Also References
deconv, poly, roots
[1] Oppenheim, A.V. and R.W. Schafer, Digital Signal Processing, Prentice-Hall, 1975, p. 56.
2-252
rethrow
Purpose Syntax Description
2rethrow
Reissue error
rethrow(err) rethrow(err) reissues the error specified by err. The currently running M-file terminates and control returns to the keyboard (or to any enclosing catch block). The err argument must be a MATLAB structure containing the following character array fields.
Fieldname message identifier
Description
Text of the error message Message identifier of the error message
See "Message Identifiers" in the MATLAB documentation for more information on the syntax and usage of message identifiers. A convenient way to get a valid err structure for the last error issued is by using the lasterror function.
Examples
rethrow is usually used in conjunction with try-catch statements to reissue an error from a catch block after performing catch-related operations. For
example:
try do_something catch do_cleanup rethrow(lasterror) end
See Also
error, lasterror, lasterr, try, catch, dbstop
2-253
return
Purpose Syntax Description Examples
2return
Return to the invoking function
return return causes a normal return to the invoking function or to the keyboard. It
also terminates keyboard mode. If the determinant function were an M-file, it might use a return statement in handling the special case of an empty matrix as follows:
function d = det(A) %DET det(A) is the determinant of A. if isempty(A) d = 1; return else ... end
See Also
break, continue, disp, end, error, for, if, keyboard, switch, while
2-254
rgb2hsv
Purpose Syntax Description
2rgb2hsv
Convert RGB colormap to HSV colormap
cmap = rgb2hsv(M) cmap = rgb2hsv(M) converts an RGB colormap, M, to an HSV colormap, cmap.
Both colormaps are m-by-3 matrices. The elements of both colormaps are in the range 0 to 1. The columns of the input matrix, M, represent intensities of red, green, and blue, respectively. The columns of the output matrix, cmap, represent hue, saturation, and value, respectively.
hsv_image = rgb2hsv(rgb_image) converts the RGB image to the equivalent
HSV image. RGB is an m-by-n-by-3 image array whose three planes contain the red, green, and blue components for the image. HSV is returned as an m-by-n-by-3 image array whose three planes contain the hue, saturation, and value components for the image.
See Also
brighten, colormap, hsv2rgb,rgbplot
"Color Operations" for related functions
2-255
rgbplot
Purpose Syntax Description
2rgbplot
Plot colormap
rgbplot(cmap) rgbplot(cmap) plots the three columns of cmap, where cmap is an m-by-3 colormap matrix. rgbplot draws the first column in red, the second in green,
and the third in blue.
Examples
Plot the RGB values of the copper colormap.
rgbplot(copper)
1
0.9
0.8
0.7
0.6
0.5
0.4
0.3
0.2
0.1
0
0
10
20
30
40
50
60
70
See Also
colormap
"Color Operations" for related functions
2-256
ribbon
Purpose Syntax
2ribbon
Ribbon plot
ribbon(Y) ribbon(X,Y) ribbon(X,Y,width) h = ribbon(...) ribbon(Y) plots the columns of Y as separate three-dimensional ribbons using X = 1:size(Y,1). ribbon(X,Y) plots X versus the columns of Y as three-dimensional strips. X and Y are vectors of the same size or matrices of the same size. Additionally, X can be a row or a column vector, and Y a matrix with length(X) rows. ribbon(X,Y,width) specifies the width of the ribbons. The default is 0.75. h = ribbon(...) returns a vector of handles to surface graphics objects. ribbon returns one handle per strip.
Description
Examples
Create a ribbon plot of the peaks function.
[x,y] = meshgrid(-3:.5:3,-3:.1:3); z = peaks(x,y); ribbon(y,z) colormap hsv
2-257
ribbon
10
5
0
-5
-10 4 2 0 -2 -4 0 5 10 15
See Also
plot, plot3, surface, waterfall
"Polygons and Surfaces" for related functions
2-258
rmappdata
Purpose Syntax Description See Also
2rmappdata
Remove application-defined data
rmappdata(h,name,value) rmappdata(h,name,value) removes the application-defined data name from the object specified by handle h. getappdata, isappdata, setappdata
2-259
rmdir
Purpose Graphical Interface Syntax
2rmdir
Remove directory As an alternative to the rmdir function, use the delete feature in the Current Directory browser.
rmdir('dirname') rmdir('dirname','s') [status,message,messageid] = rmdir('dirname','s') rmdir('dirname') removes the directory dirname from the current directory. If the directory is not empty, you must use the s argument. If dirname is not in
Description
the current directory, specify the relative path to the current directory or the full path for dirname.
rmdir('dirname','s') removes the directory dirname and its contents from the current directory. This removes all subdirectories and files in the current directory regardless of their write permissions. [status, message, messageid] = rmdir('dirname','s') removes the directory dirname and its contents from the current directory, 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, and message, messageid, and the s input argument are optional.
Examples
Remove Empty Directory
To remove myfiles from the current directory, where myfiles is empty, type
rmdir('myfiles')
If the current directory is matlabr13/work, and myfiles is in d:/matlabr13/work/project/, use the relative path to myfiles
rmdir('project/myfiles')
or the full path to myfiles
rmdir('d:/matlabr13/work/project/myfiles')
2-260
rmdir
Remove Directory and All Contents
To remove myfiles, its subdirectories, and all files in the directories, assuming myfiles is in the current directory, type
rmdir('myfiles','s')
Remove Directory and Return Results
To remove myfiles from the current directory, type
[stat, mess, id]=rmdir('myfiles')
MATLAB returns
stat = 0 mess = The directory is not empty. id = MATLAB:RMDIR:OSError
indicating the directory myfiles is not empty. To remove myfiles and its contents, run
[stat, mess]=rmdir('myfiles','s')
and MATLAB returns
stat = 1 mess = ''
indicating myfiles and its contents were removed.
2-261
rmdir
See Also
cd, copyfile, delete, dir, error, fileattrib, filebrowser, lasterr, mkdir, movefile
2-262
rmfield
Purpose Syntax Description
2rmfield
Remove structure fields
s = rmfield(s,'field') s = rmfield(s,FIELDS) s = rmfield(s,'field') removes the specified field from the structure array s. s = rmfield(s,FIELDS) removes more than one field at a time when FIELDS
is a character array of field names or cell array of strings.
See Also
fieldnames, isfield, orderfields
2-263
rmpath
Purpose Graphical Interface Syntax Description
2rmpath
Remove directories from MATLAB search path As an alternative to the rmpath function, use the Set Path dialog box. To open it, select Set Path from the File menu in the MATLAB desktop.
rmpath('directory') rmpath directory rmpath('directory') removes the specified directory from the current MATLAB search path. Use the full pathname for directory. rmpath directory is the unquoted form of the syntax.
Examples
Remove /usr/local/matlab/mytools from the search path.
rmpath /usr/local/matlab/mytools
See Also
addpath, path, pathtool, rehash
2-264
root object
Purpose Description
2root object
Root object properties The root is a graphics object that corresponds to the computer screen. There is only one root object and it has no parent. The children of the root object are figures. The root object exists when you start MATLAB; you never have to create it and you cannot destroy it. Use set and get to access the root properties.
See Also
Object Hierarchy
diary, echo, figure, format, gcf, get, set
Root
Figure
Axes
Uicontrol
Uimenu
Uicontextmenu
Image
Light
Line
Patch
Rectangle
Surface
Text
Property List
The following table lists all root properties and provides a brief description of each. The property name links take you to an expanded description of the properties. This table does not include properties that are defined for, but not used by, the root object.
Property Description Property Value
Property Name Information about MATLAB state CallbackObject
Handle of object whose callback is executing Handle of current figure
Values: object handle Values: object handle
CurrentFigure
2-265
root object
Property Name ErrorMessage PointerLocation PointerWindow
Property Description
Property Value
Text of last error message Current location of pointer Handle of window containing the pointer Show or hide handles marked as hidden
Value: character string Values: x-, and y-coordinates Values: figure handle Values: on, off Default: off
ShowHiddenHandles
Controlling MATLAB behavior Diary
Enable the diary file Name of the diary file Display each line of script M-file as executed Format used to display numbers
Values: on, off Default: off Values: filename (string) Default: diary Values: on, off Default: off Values: short, shortE, long, longE, bank, hex, +, rat Default: shortE Values: compact, loose Default: loose Values: string Default: english Values: integer Defalut: 2.1478e+009 Values: pixels, normalized, inches, centimeters, points, characters Default: pixels
DiaryFile
Echo
Format
FormatSpacing
Display or omit extra line feed System environment setting Maximum number of nested M-file calls Units for PointerLocation and ScreenSize properties
Language
RecursionLimit
Units
Information about the display
2-266
root object
Property Name FixedWidthFontName
Property Description
Property Value
Value for axes, text, and uicontrol FontName property Depth of the display bitmap Size of the screen
Values: font name Default: Courier Values: bits per pixel Values: [left, bottom, width, height]
ScreenDepth ScreenSize
General Information About Root Objects Children
Handles of all nonhidden Figue objects The root object has no parent This property is not used by the root object. User-specified label The type of graphics object (read only) User-specified data
Values: vector of handles Value: [] (empty matrix)
Parent Selected
Tag
Value: any string Default: '' (empty string) Value: the string 'root' Values: any matrix Default: [] (empty matrix)
Type
UserData
2-267
Root Properties
Modifying Properties
2Root 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.
Root Properties This section lists property names along with the type of values each accepts.
Curly braces { } enclose default values.
BusyAction cancel | {queue}
Not used by the root object.
ButtonDownFcn
string
Not used by the root object.
CallbackObject
handle (read only)
Handle of current callback's object. This property contains the handle of the object whose callback routine is currently executing. If no callback routines are executing, this property contains the empty matrix [ ]. See also the gco command.
CaptureMatrix
(obsolete)
This property has been superseded by the getframe command.
CaptureRect
(obsolete)
This property has been superseded by the getframe command.
Children
vector of handles
Handles of child objects. A vector containing the handles of all nonhidden figure objects. You can change the order of the handles and thereby change the stacking order of the figures on the display.
Clipping {on} | off
Clipping has no effect on the root object.
CreateFcn
The root does not use this property.
2-268
Root Properties
CurrentFigure
figure handle
Handle of the current figure window, which is the one most recently created, clicked in, or made current with the statement:
figure(h)
which restacks the figure to the top of the screen, or
set(0,'CurrentFigure',h)
which does not restack the figures. In these statements, h is the handle of an existing figure. If there are no figure objects,
get(0,'CurrentFigure')
returns the empty matrix. Note, however, that gcf always returns a figure handle, and creates one if there are no figure objects.
DeleteFcn
string
This property is not used since you cannot delete the root object
Diary on | {off}
Diary file mode. When this property is on, MATLAB maintains a file (whose name is specified by the DiaryFile property) that saves a copy of all keyboard input and most of the resulting output. See also the diary command.
DiaryFile
string
Diary filename. The name of the diary file. The default name is diary.
Echo on | {off}
Script echoing mode. When Echo is on, MATLAB displays each line of a script file as it executes. See also the echo command.
ErrorMessage
string
Text of last error message. This property contains the last error message issued by MATLAB.
FixedWidthFontName font name
Fixed-width font to use for axes, text, and uicontrols whose FontName is set to FixedWidth. MATLAB uses the font name specified for this property as the value for axes, text, and uicontrol FontName properties when their FontName property is set to FixedWidth. Specifying the font name with this property
2-269
Root Properties
eliminates the need to hardcode font names in MATLAB applications and thereby enables these applications to run without modification in locales where non-ASCII character sets are required. In these cases, MATLAB attempts to set the value of FixedWidthFontName to the correct value for a given locale. MATLAB application developers should not change this property, but should create axes, text, and uicontrols with FontName properties set to FixedWidth when they want to use a fixed width font for these objects. MATLAB end users can set this property if they do not want to use the preselected value. In locales where Latin-based characters are used, Courier is the default.
Format short | {shortE} | long | longE | bank | hex | + | rat
Output format mode. This property sets the format used to display numbers. See also the format command. short Fixed-point format with 5 digits. shortE Floating-point format with 5 digits. shortG Fixed- or floating-point format displaying as many significant figures as possible with 5 digits. long Scaled fixed-point format with 15 digits. longE Floating-point format with 15 digits. longG Fixed- or floating-point format displaying as many significant figures as possible with 15 digits. bank Fixed-format of dollars and cents. hex Hexadecimal format. + Displays + and symbols. rat Approximation by ratio of small integers.
FormatSpacing compact | {loose}
Output format spacing (see also format command). compact -- Suppress extra line feeds for more compact display. loose -- Display extra line feeds for a more readable display.
2-270
Root Properties
HandleVisibility
{on} | callback | off
This property is not useful on the root object.
HitTest {on} | off
This property is not useful on the root object.
Interruptible {on} | off
This property is not useful on the root object.
Language
string
System environment setting.
Parent
handle
Handle of parent object. This property always contains the empty matrix, as the root object has no parent.
PointerLocation [x,y]
Current location of pointer. A vector containing the x- and y-coordinates of the pointer position, measured from the lower-left corner of the screen. You can move the pointer by changing the values of this property. The Units property determines the units of this measurement. This property always contains the instantaneous pointer location, even if the pointer is not in a MATLAB window. A callback routine querying the PointerLocation can get a different value than the location of the pointer when the callback was triggered. This difference results from delays in callback execution caused by competition for system resources.
PointerWindow
handle (read only)
Handle of window containing the pointer. MATLAB sets this property to the handle of the figure window containing the pointer. If the pointer is not in a MATLAB window, the value of this property is 0. A callback routine querying the PointerWindow can get the wrong window handle if you move the pointer to another window before the callback executes. This error results from delays in callback execution caused by competition for system resources.
RecursionLimit
integer
Number of nested M-file calls. This property sets a limit to the number of nested calls to M-files MATLAB will make before stopping (or potentially running out of memory). By default the value is set to a large value. Setting this
2-271
Root Properties
property to a smaller value (something like 150, for example) should prevent MATLAB from running out of memory and will instead cause MATLAB to issue an error when the limit is reached.
ScreenDepth
bits per pixel
Screen depth. The depth of the display bitmap (i.e., the number of bits per pixel). The maximum number of simultaneously displayed colors on the current graphics device is 2 raised to this power.
ScreenDepth supersedes the BlackAndWhite property. To override automatic
hardware checking, set this property to 1. This value causes MATLAB to assume the display is monochrome. This is useful if MATLAB is running on color hardware but is displaying on a monochrome terminal. Such a situation can cause MATLAB to determine erroneously that the display is color.
ScreenSize
4-element rectangle vector (read only)
Screen size. A four-element vector,
[left,bottom,width,height]
that defines the display size. left and bottom are 0 for all Units except pixels, in which case left and bottom are 1. width and height are the screen dimensions in units specified by the Units property.
Selected on | off
This property has no effect on the root level.
SelectionHighlight {on} | off
This property has no effect on the root level.
ShowHiddenHandles on | {off}
Show or hide handles marked as hidden. When set to on, this property disables handle hiding and exposes all object handles, regardless of the setting of an object's HandleVisibility property. When set to off, all objects so marked remain hidden within the graphics hierarchy.
Tag
string
User-specified object label. The Tag property provides a means to identify graphics objects with a user-specified label. While it is not necessary to identify the root object with a tag (since its handle is always 0), you can use this property to store any string value that you can later retrieve using set.
2-272
Root Properties
Type
string (read only)
Class of graphics object. For the root object, Type is always 'root'.
UIContextMenu
handle
This property has no effect on the root level.
Units {pixels} | normalized | inches | centimeters | points | characters
Unit of measurement. This property specifies the units MATLAB uses to interpret size and location data. All units are measured from the lower-left corner of the screen. Normalized units map the lower-left corner of the screen 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). Characters are units defined by characters from the default system font; the width of one unit is the width of the letter x, the height of one character is the distance between the baselines of two lines of text. This property affects the PointerLocation and ScreenSize properties. If you change the value of Units, it is good practice to return it to its default value after completing your operation so as not to affect other functions that assume Units is set to the default value.
UserData
matrix
User specified data. This property can be any data you want to associate with the root object. MATLAB does not use this property, but you can access it using the set and get functions.
Visible {on} | off
Object visibility. This property has no effect on the root object.
2-273
roots
Purpose Syntax Description
2roots
Polynomial roots
r = roots(c) r = roots(c) returns a column vector whose elements are the roots of the polynomial c.
Row vector c contains the coefficients of a polynomial, ordered in descending powers. If c has n+1 components, the polynomial it represents is c1 s n + ... + cn s + cn + 1 .
Remarks
Note the relationship of this function to p = poly(r), which returns a row vector whose elements are the coefficients of the polynomial. For vectors, roots and poly are inverse functions of each other, up to ordering, scaling, and roundoff error. The polynomial s 3 6s 2 72s 27 is represented in MATLAB as
p = [1 -6 -72 -27]
Examples
The roots of this polynomial are returned in a column vector by
r = roots(p) r = 12.1229 -5.7345 -0.3884
Algorithm
The algorithm simply involves computing the eigenvalues of the companion matrix:
A = diag(ones(n-2,1),-1); A(1,:) = -c(2:n-1)./c(1); eig(A)
It is possible to prove that the results produced are the exact eigenvalues of a matrix within roundoff error of the companion matrix A, but this does not mean that they are the exact roots of a polynomial with coefficients within roundoff error of those in c.
2-274
roots
See Also
fzero, poly, residue
2-275
rose
Purpose Syntax
2rose
Angle histogram
rose(theta) rose(theta,x) rose(theta,nbins) [tout,rout] = rose(...) rose creates an angle histogram, which is a polar plot showing the distribution
Description
of values grouped according to their numeric range. Each group is shown as one bin.
rose(theta) plots an angle histogram showing the distribution of theta in 20 angle bins or less. The vector theta, expressed in radians, determines the angle
from the origin of each bin. The length of each bin reflects the number of elements in theta that fall within a group, which ranges from 0 to the greatest number of elements deposited in any one bin.
rose(theta,x) uses the vector x to specify the number and the locations of bins. length(x) is the number of bins and the values of x specify the center angle of each bin. For example, if x is a five-element vector, rose distributes the elements of theta in five bins centered at the specified x values. rose(theta,nbins) plots nbins equally spaced bins in the range [0, 2*pi]. The default is 20. [tout,rout] = rose(...) returns the vectors tout and rout so polar(tout,rout) generates the histogram for the data. This syntax does not
generate a plot.
Example
Create a rose plot showing the distribution of 50 random numbers.
theta = 2*pi*rand(1,50); rose(theta)
2-276
rose
90 5 120 4 60
3 150 2 30
1
180
0
210
330
240 270
300
See Also
compass, feather, hist, polar
"Histograms" for related functions Histograms in Polar Coordinates for another example
2-277
rosser
Purpose Syntax Description
2rosser
Classic symmetric eigenvalue test problem
A = rosser A = rosser returns the Rosser matrix. This matrix was a challenge for many matrix eigenvalue algorithms. But LAPACK's DSYEV routine used in MATLAB
has no trouble with it. The matrix is 8-by-8 with integer elements. It has: A double eigenvalue Three nearly equal eigenvalues Dominant eigenvalues of opposite sign A zero eigenvalue A small, nonzero eigenvalue
Examples
rosser ans = 611 196 -192 407 -8 -52 -49 29 196 899 113 -192 -71 -43 -8 -44 -192 113 899 196 61 49 8 52 407 -192 196 611 8 44 59 -23 -8 -71 61 8 411 -599 208 208 -52 -43 49 44 -599 411 208 208 -49 -8 8 59 208 208 99 -911 29 -44 52 -23 208 208 -911 99
2-278
rot90
Purpose Syntax Description
2rot90
Rotate matrix 90
B = rot90(A) B = rot90(A,k) B = rot90(A) rotates matrix A counterclockwise by 90 degrees. B = rot90(A,k) rotates matrix A counterclockwise by k*90 degrees, where k is
an integer.
Examples
The matrix
X = 1 4 7 2 5 8 3 6 9
rotated by 90 degrees is
Y = rot90(X) Y = 3 6 2 5 1 4
9 8 7
See Also
flipdim, fliplr, flipud
2-279
rotate
Purpose Syntax Description
2rotate
Rotate object about a specified direction
rotate(h,direction,alpha) rotate(...,origin)
The rotate function rotates a graphics object in three-dimensional space, according to the right-hand rule.
rotate(h,direction,alpha) rotates the graphics object h by alpha degrees. direction is a two- or three-element vector that describes the axis of rotation
in conjunction with the origin.
rotate(...,origin) specifies the origin of the axis of rotation as a
three-element vector. The default origin is the center of the plot box.
Remarks
The graphics object you want rotated must be a child of the same axes. The object's data is modified by the rotation transformation. This is in contrast to view and rotate3d, which only modify the viewpoint. The axis of rotation is defined by an origin and a point P relative to the origin. P is expressed as the spherical coordinates [theta phi], or as Cartesian coordinates.
Z P
Y
ax fr is o ota tion
origin
X The two-element form for direction specifies the axis direction using the spherical coordinates [theta phi]. theta is the angle in the xy plane
2-280
rotate
counterclockwise from the positive x-axis. phi is the elevation of the direction vector from the xy plane.
Z
P
r
phi
th et a
Y
X
The three-element form for direction specifies the axis direction using Cartesian coordinates. The direction vector is the vector from the origin to (X,Y,Z).
Examples
Rotate a graphics object 180 about the x-axis.
h = surf(peaks(20)); rotate(h,[1 0 0],180)
Rotate a surface graphics object 45 about its center in the z direction.
h = surf(peaks(20)); zdir = [0 0 1]; center = [10 10 0]; rotate(h,zdir,45,center)
Remarks See Also
rotate changes the Xdata, Ydata, and Zdata properties of the appropriate
graphics object.
rotate3d, sph2cart, view
The axes CameraPosition, CameraTarget, CameraUpVector, CameraViewAngle "Object Manipulation" for related functions
2-281
rotate3d
Purpose Syntax
2rotate3d
Rotate 3-D view using mouse
rotate3d on rotate3d off rotate3d rotate3d(figure_handle,...) rotate3d(axes_handle,...) rotate3d on enables mouse-base rotation on all axes within the current figure. rotate3d off disables interactive axes rotation in the current figure. rotate3d toggles interactive axes rotation in the current figure. rotate3d(figure_handle,...) enables rotation within the specified figure
Description
instead of the current figure.
rotate3d(axes_handle,...) enables rotation only in the specified axes.
Using rotate3d
When enabled, clicking on an axes draws an animated box, which rotates as the mouse is dragged, showing the view that will result when the mouse button is released. A numeric readout appears in the lower-left corner of the figure during rotation, showing the current azimuth and elevation of the animated box. Releasing the mouse button removes the animated box and the readout, and changes the view of the axes to correspond to the last orientation of the animated box.
See Also
camorbit, rotate, view
Object Manipulation for related functions.
2-282
round
Purpose Syntax Description Examples
2round
Round to nearest integer
Y = round(X) Y = round(X) rounds the elements of X to the nearest integers. For complex X,
the imaginary and real parts are rounded independently.
a = [-1.9, -0.2, 3.4, 5.6, 7.0, 2.4+3.6i] a = Columns 1 through 4 -1.9000 -0.2000 3.4000 Columns 5 through 6 7.0000 2.4000 + 3.6000i round(a) ans = Columns 1 through 4 -2.0000 0 3.0000 Columns 5 through 6 7.0000 2.0000 + 4.0000i
5.6000
6.0000
See Also
ceil, fix, floor
2-283
rref
Purpose Syntax
2rref
Reduced row echelon form
R = rref(A) [R,jb] = rref(A) [R,jb] = rref(A,tol) R = rref(A) produces the reduced row echelon form of A using Gauss Jordan
Description
elimination with partial pivoting. A default tolerance of (max(size(A))*eps *norm(A,inf)) tests for negligible column elements.
[R,jb] = rref(A) also returns a vector jb such that:
r = length(jb) is this algorithm's idea of the rank of A. x(jb) are the pivot variables in a linear system Ax = b. A(:,jb) is a basis for the range of A. R(1:r,jb) is the r-by-r identity matrix.
[R,jb] = rref(A,tol) uses the given tolerance in the rank tests.
Roundoff errors may cause this algorithm to compute a different value for the rank than rank, orth and null.
Note The demo rrefmovie(A) enables you to sequence through the iterations of the algorithm.
Examples
Use rref on a rank-deficient magic square:
A = magic(4), R = rref(A) A = 16 5 9 4 2 11 7 14 3 10 6 15 13 8 12 1
2-284
rref
R = 1 0 0 0 0 1 0 0 0 0 1 0 1 3 -3 0
See Also
inv, lu, rank
2-285
rsf2csf
Purpose Syntax Description
2rsf2csf
Convert real Schur form to complex Schur form
[U,T] = rsf2csf(U,T)
The complex Schur form of a matrix is upper triangular with the eigenvalues of the matrix on the diagonal. The real Schur form has the real eigenvalues on the diagonal and the complex eigenvalues in 2-by-2 blocks on the diagonal.
[U,T] = rsf2csf(U,T) converts the real Schur form to the complex form.
Arguments U and T represent the unitary and Schur forms of a matrix A, respectively, that satisfy the relationships: A = U*T*U' and U'*U = eye(size(A)). See schur for details.
Examples
Given matrix A,
1 1 1 -2 1 2 1 1 1 1 3 1 3 1 1 4
with the eigenvalues
4.8121 1.9202 + 1.4742i 1.9202 + 1.4742i 1.3474
Generating the Schur form of A and converting to the complex Schur form
[u,t] = schur(A); [U,T] = rsf2csf(u,t)
yields a triangular matrix T whose diagonal (underlined here for readability) consists of the eigenvalues of A.
U = -0.4916 -0.4980 -0.6751 -0.2337 -0.2756 -0.1012 0.1842 0.2635 + + 0.4411i 0.2163i 0.3860i 0.6481i 0.2133 -0.1046 -0.1867 0.3134 + + 0.5699i 0.2093i 0.3808i 0.5448i -0.3428 0.8001 -0.4260 0.2466
2-286
rsf2csf
T = 4.8121 0 0 0 -0.9697 + 1.0778i 1.9202 + 1.4742i 0 0 -0.5212 + 2.0051i 2.3355 1.9202 - 1.4742i 0 -1.0067 0.1117 + 1.6547i 0.8002 + 0.2310i 1.3474
See Also
schur
2-287
run
Purpose Syntax Description
2run
Run a script
run scriptname run scriptname runs the MATLAB script specified by scriptname. If scriptname contains the full pathname to the script file, then run changes the
current directory to be the one in which the script file resides, executes the script, and sets the current directory back to what it was. The script is run within the caller's workspace.
run is a convenience function that runs scripts that are not currently on the
path. Typically, you just type the name of a script at the MATLAB prompt to execute it. This works when the script is on your path. Use the cd or addpath function to make a script executable by entering the script name alone.
See Also
cd, addpath
2-288
runtime
Purpose Syntax
2runtime
Emulate the runtime environment in MATLAB and set the global error mode
runtime runtime runtime runtime on off status errormode mode
Description
The runtime command lets you emulate the Runtime Server environment in commercial MATLAB and set the global error mode for a runtime application. Because the Runtime Server disables the command window, it is generally much more convenient to test and debug with MATLAB emulating the Runtime Server than with the Runtime Server variant itself.
runtime on tells commercial MATLAB to begin emulating the Runtime Server.
This means that MATLAB executes neither M-files nor standard P-files. The command line remains accessible.
runtime off returns MATLAB to its ordinary state. runtime status indicates whether MATLAB is emulating the Runtime Server
or not.
runtime errormode mode sets the global error mode to mode. The value of mode can be either continue, quit, or dialog. However, dialog is both the default
error mode and the recommended one. The error mode setting is only effective when the application runs with the Runtime Server; when the application runs with commercial MATLAB emulating the Runtime Server, untrapped errors are always displayed in the command window.
See Also
isruntime
2-289
save
Purpose Graphical Interface Syntax
2save
Save workspace variables on disk As an alternative to the save function, select Save Workspace As from the File menu in the MATLAB desktop, or use the Workspace browser.
save save filename save filename var1 var2 ... save ... option save('filename', ...) save by itself, stores all workspace variables in a binary format in the current directory in a file named matlab.mat. Retrieve the data with load. MAT-files
Description
are double-precision, binary, MATLAB format files. They can be created on one machine and later read by MATLAB on another machine with a different floating-point format, retaining as much accuracy and range as the different formats allow. They can also be manipulated by other programs external to MATLAB.
save filename stores all workspace variables in the current directory in filename.mat. To save to another directory, use the full pathname for the filename. If filename is the special string stdio, the save command sends the
data as standard output.
save filename var1 var2 ... saves only the specified workspace variables in filename.mat. Use the * wildcard to save only those variables that match the specified pattern. For example, save('A*') saves all variables that start with A. save ... option saves the workspace variables in the format specified by option option Argument -append Result: How Data is Stored
The specified existed MAT-file, appended to the end 8-digit ASCII format
-ascii
2-290
save
option Argument -ascii -ascii -ascii -mat -v4 -double -tabs -double -tabs
Result: How Data is Stored
16-digit ASCII format delimits with tabs 16-digit ASCII format, tab delimited Binary MAT-file form (default) A format that MATLAB version 4 can open
Remarks
When saving in ASCII format, consider the following: Each variable to be saved must be either a two dimensional double array or a two dimensional character array. Saving a complex double array causes the imaginary part of the data to be lost, as MATLAB cannot load nonnumeric data ('i'). In order to be able to read the file with the MATLAB load function, all of the variables must have the same number of columns. If you are using a program other than MATLAB to read the saved data this restriction can be relaxed. Each MATLAB character in a character array is converted to a floating point number equal to its internal ASCII code and written out as a floating point number string. There is no information in the save file that indicates whether the value was originally a number or a character. The values of all variables saved merge into a single variable that takes the name of the ASCII file (minus any extension). Therefore, it is advisable to save only one variable at a time. With the v4 flag, you can only save data constructs that are compatible with versions of MATLAB 4. Therefore, you cannot save structures, cell arrays, multidimensional arrays, or objects. In addition, you must use filenames that are supported by MATLAB version 4.
save('filename', ...) is the function form of the syntax.
For more control over the format of the file, MATLAB provides other functions, as listed in "See Also", below.
2-291
save
Algorithm
The binary formats used by save depend on the size and type of each array. Arrays with any noninteger entries and arrays with 10,000 or fewer elements are saved in floating-point formats requiring 8 bytes per real element. Arrays with all integer entries and more than 10,000 elements are saved in the formats shown, requiring fewer bytes per element.
Element Range Bytes per Element
0 to 255 0 to 65535 -32767 to 32767 -231+1 to 231-1 other
1 2 2 4 8
External Interfaces to MATLAB provides details on reading and writing MAT-files from external C or Fortran programs. It is important to use recommended access methods, rather than rely upon the specific MAT-file format, which is likely to change in the future.
Examples
To save all variables from the workspace in binary MAT-file, test.mat, type
save test.mat
To save variables p and q in binary MAT-file, test.mat, type
savefile = 'test.mat'; p = rand(1,10); q = ones(10); save(savefile,'p','q')
To save the variables vol and temp in ASCII format to a file named june10, type
save('d:\mymfiles\june10','vol','temp','-ASCII')
See Also
diary, fprintf, fwrite, load, workspace
2-292
save (COM)
Purpose Syntax Arguments
2save (COM)
Serialize a COM control object to a file
save(h, 'filename') h
Handle for a MATLAB COM control object.
filename
The full path and filename of the serialized data.
Description
Save the COM control object associated with the interface represented by the MATLAB COM object h into a file. The COM save function is only supported for controls at this time.
Examples
Create an mwsamp control and save its original state to the file mwsample:
f = figure('pos', [100 200 200 200]); h = actxcontrol('mwsamp.mwsampctrl.2', [0 0 200 200], f); save(h, 'mwsample')
Now, alter the figure by changing its label and the radius of the circle:
set(h, 'Label', 'Circle'); set(h, 'Radius', 50); Redraw(h);
Using the load function, you can restore the control to its original state:
load(h, 'mwsample'); get(h) ans = Label: 'Label' Radius: 20
See Also
load, actxcontrol, actxserver, release, delete
2-293
save (serial)
Purpose Syntax Arguments
2save (serial)
Save serial port objects and variables to a MAT-file
save filename save filename obj1 obj2... filename obj1 obj2...
The MAT-file name. Serial port objects or arrays of serial port objects.
Description
save filename saves all MATLAB variables to the MAT-file filename. If an extension is not specified for filename, then the .mat extension is used. save filename obj1 obj2... saves the serial port objects obj1 obj2 ... to the
MAT-file filename.
Remarks
You can use save in the functional form as well as the command form shown above. When using the functional form, you must specify the filename and serial port objects as strings. For example. to save the serial port object s to the file MySerial.mat
s = serial('COM1'); save('MySerial','s')
Any data that is associated with the serial port object is not automatically stored in the MAT-file. For example, suppose there is data in the input buffer for obj. To save that data to a MAT-file, you must bring it into the MATLAB workspace using one of the synchronous read functions, and then save to the MAT-file using a separate variable name. You can also save data to a text file with the record function. You return objects and variables to the MATLAB workspace with the load command. Values for read-only properties are restored to their default values upon loading. For example, the Status property is restored to closed. To determine if a property is read-only, examine its reference pages. If you use the help command to display help for save, then you need to supply the pathname shown below.
help serial/private/save
Example
This example illustrates how to use the command and functional form of save.
2-294
save (serial)
s = serial('COM1'); set(s,'BaudRate',2400,'StopBits',1) save MySerial1 s set(s,'BytesAvailableFcn',@mycallback) save('MySerial2','s')
See Also
Functions
load, record
Properties
Status
2-295
saveas
Purpose Syntax Description
2saveas
Save figure or model using specified format
saveas(h,'filename.ext') saveas(h,'filename','format') saveas(h,'filename.ext') saves the figure or model with the handle h to the file filename.ext. The format of the file is determined by the extension, ext. Allowable values for ext are listed in this table. ext Values ai bmp emf eps fig jpg m pbm pcx pgm png ppm tif Format
Adobe Illustrator `88 Windows bitmap Enhanced metafile EPS Level 1 MATLAB figure (invalid for MATLAB models) JPEG image (invalid for MATLAB models) MATLAB M-file (invalid for MATLAB models) Portable bitmap Paintbrush 24-bit Portable Graymap Portable Network Graphics Portable Pixmap TIFF image, compressed
saveas(h,'filename','format') saves the figure or model with the handle h to the file called filename using the specified format. The filename can have
an extension but the extension is not used to define the file format. If no extension is specified, the standard extension corresponding to the specified format is automatically appended to the filename.
2-296
saveas
Allowable values for format are the extensions in the table above and the device types supported by print. The print device types include the formats listed in the table of extensions above as well as additional file formats. Use an extension from the table above or from the list of device types supported by print. When using the print device type to specify format for saveas, do not use the prepended -d.
Remarks
You can use open to open files saved using saveas with an m or fig extension. Other formats are not supported by open. The Save As dialog box you access from the figure window's File menu uses saveas, limiting the file extensions to m and fig. The Export dialog box you access from the figure window's File menu uses saveas with the format argument.
Examples
Example 1 Specify File Extension
Save the current figure that you annotated using the Plot Editor to a file named pred_prey using the MATLAB fig format. This allows you to open the file pred_prey.fig at a later time and continue editing it with the Plot Editor.
saveas(gcf,'pred_prey.fig')
Example 2 Specify File Format but No Extension
Save the current figure, using Adobe Illustrator format, to the file logo. Use the ai extension from the above table to specify the format. The file created is logo.ai.
saveas(gcf,'logo', 'ai')
This is the same as using the Adobe Illustrator format from the print devices table, which is -dill; use doc print or help print to see the table for print device types. The file created is logo.ai. MATLAB automatically appends the ai extension, for an Illustrator format file, because no extension was specified.
saveas(gcf,'logo', 'ill')
Example 3 Specify File Format and Extension
Save the current figure to the file star.eps using the Level 2 Color PostScript format. If you use doc print or help print, you can see from the table for print device types that the device type for this format is -dpsc2. The file created is star.eps.
2-297
saveas
saveas(gcf,'star.eps', 'psc2')
In another example, save the current model to the file trans.tiff using the TIFF format with no compression. From the table for print device types, you can see the device type for this format is -dtiffn. The file created is trans.tiff.
saveas(gcf,'trans.tiff', 'tiffn')
See Also
open, print
"Printing" for related functions
2-298
saveobj
Purpose Syntax Description
2saveobj
Save an object to a MAT-file
B = saveobj(A) B = saveobj(A) is called by the MATLAB save function when object, A, is saved to a .MAT file. This call executes the saveobj method for the object's class, if such a method exists. The return value B is subsequently used by save
to populate the .MAT file. When you issue a save command on an object, MATLAB looks for a method called saveobj in the class directory. You can overload this method to modify the object before the save operation. For example, you could define a saveobj method that saves related data along with the object.
Remarks
saveobj can be overloaded only for user objects. save will not call saveobj for a built-in datatype, such as double, even if @double/saveobj exists. saveobj will be separately invoked for each object to be saved.
A child object does not inherit the saveobj method of its parent class. To implement saveobj for any class, including a class that inherits from a parent, you must define a saveobj method within that class directory.
Examples
The following example shows a saveobj method written for the portfolio class. The method determines if a portfolio object has already been assigned an account number from a previous save operation. If not, saveobj calls getAccountNumber to obtain the number and assigns it to the account_number field. The contents of b is saved to the MAT-file.
function b = saveobj(a) if isempty(a.account_number) a.account_number = getAccountNumber(a); end b = a;
See Also
save, load, loadobj
2-299
scatter
Purpose Syntax
2scatter
2-D Scatter plot
scatter(X,Y,S,C) scatter(X,Y) scatter(X,Y,S) scatter(...,markertype) scatter(...,'filled') h = scatter(...,) scatter(X,Y,S,C) displays colored circles at the locations specified by the vectors X and Y (which must be the same size). S determines the area of each marker (specified in points^2). S can be a vector the same length as X and Y or a scalar. If S is a scalar, MATLAB draws all the
Description
markers the same size.
C determines the colors of each marker. When C is a vector the same length as X and Y, the values in C are linearly mapped to the colors in the current colormap. When C is a length(X)-by-3 matrix, it specifies the colors of the markers as RGB values. C can also be a color string (see ColorSpec for a list of
color string specifiers)
scatter(X,Y) draws the markers in the default size and color. scatter(X,Y,S) draws the markers at the specified sizes (S) with a single
color.
scatter(...,markertype) uses the marker type specified instead of 'o' (see LineSpec for a list of marker specifiers). scatter(...,'filled') fills the markers. h = scatter(...) returns the handles to the line objects created by scatter (see line for a list of properties you can specify using the object handles and set).
Remarks Examples
Use plot for single color, single marker size scatter plots.
load seamount scatter(x,y,5,z)
2-300
scatter
-47.95
-48
-48.05
-48.1
-48.15
-48.2
-48.25
-48.3
-48.35
-48.4
-48.45 210.8
210.9
211
211.1
211.2
211.3
211.4
211.5
211.6
211.7
211.8
See Also
scatter3, plot, plotmatrix
"Specialized Plotting" for related functions
2-301
scatter3
Purpose Syntax
2scatter3
3-D scatter plot
scatter3(X,Y,Z,S,C) scatter3(X,Y,Z) scatter3(X,Y,Z,S) scatter3(...,markertype) scatter3(...,'filled') h = scatter3(...,) scatter3(X,Y,Z,S,C) displays colored circles at the locations specified by the vectors X, Y, and Z (which must all be the same size). S determines the size of each marker (specified in points). S can be a vector the same length as X, Y, and Z or a scalar. If S is a scalar, MATLAB draws all the
Description
markers the same size.
C determines the colors of each marker. When C is a vector the same length as X, Y, and Z, the values in C are linearly mapped to the colors in the current colormap. When C is a length(X)-by-3 matrix, it specifies the colors of the markers as RGB values. C can also be a color string (see ColorSpec for a list of
color string specifiers)
scatter3(X,Y,Z) draws the markers in the default size and color. scatter3(X,Y,Z,S) draws the markers at the specified sizes (S) with a single
color.
scatter3(...,markertype) uses the marker type specified instead of 'o' (see LineSpec for a list of marker specifiers). scatter3(...,'filled') fills the markers. h = scatter3(...) returns the handles to the line objects created by scatter3 (see line for a list of properties you can specify using the object handles and set).
Remarks Examples
Use plot3 for single color, single marker size 3-D scatter plots.
[x,y,z] = sphere(16); X = [x(:)*.5 x(:)*.75 x(:)]; Y = [y(:)*.5 y(:)*.75 y(:)];
2-302
scatter3
Z = [z(:)*.5 z(:)*.75 z(:)]; S = repmat([1 .75 .5]*10,prod(size(x)),1); C = repmat([1 2 3],prod(size(x)),1); scatter3(X(:),Y(:),Z(:),S(:),C(:),'filled'), view(-60,60)
1 0.5 0 -0.5 0.5 -1 1 0.5 0 -0.5 -1 -1 -0.5 0 1
See Also
scatter, plot3
"Scatter Plots" for related functions
2-303
schur
Purpose Syntax
2schur
Schur decomposition
T = schur(A) T = schur(A,flag) [U,T] = schur(A,...)
Description
The schur command computes the Schur form of a matrix.
T = schur(A) returns the Schur matrix T. T = schur(A,flag) for real matrix A, returns a Schur matrix T in one of two forms depending on the value of flag: 'complex' 'real' T is triangular and is complex if A has complex eigenvalues. T has the real eigenvalues on the diagonal and the complex eigenvalues in 2-by-2 blocks on the diagonal. 'real' is the
default. If A is complex, schur returns the complex Schur form in matrix T. The complex Schur form is upper triangular with the eigenvalues of A on the diagonal. The function rsf2csf converts the real Schur form to the complex Schur form.
[U,T] = schur(A,...) also returns a unitary matrix U so that A = U*T*U' and U'*U = eye(size(A)).
Examples
H is a 3-by-3 eigenvalue test matrix: H = [ -149 537 -27 -50 180 -9 -154 546 -25 ]
Its Schur form is
schur(H) ans = 1.0000 0 0
-7.1119 -815.8706 2.0000 -55.0236 0 3.0000
2-304
schur
The eigenvalues, which in this case are 1, 2, and 3, are on the diagonal. The fact that the off-diagonal elements are so large indicates that this matrix has poorly conditioned eigenvalues; small changes in the matrix elements produce relatively large changes in its eigenvalues.
Algorithm
schur uses LAPACK routines to compute the Schur form of a matrix:
Matrix A
Routine DSYTRD, DSTEQR DSYTRD, DORGTR, DSTEQR (with output U) DGEHRD, DHSEQR DGEHRD, DORGHR, DHSEQR (with output U) ZHETRD, ZSTEQR ZHETRD, ZUNGTR, ZSTEQR (with output U) ZGEHRD, ZHSEQR ZGEHRD, ZUNGHR, ZHSEQR (with output U)
Real symmetric Real nonsymmetric Complex Hermitian Non-Hermitian
See Also References
eig, hess, qz, rsf2csf
[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-305
script
Purpose Description
2script
Script M-files A script file is an external file that contains a sequence of MATLAB statements. By typing the filename, subsequent MATLAB input is obtained from the file. Script files have a filename extension of .m and are often called M-files. Scripts are the simplest kind of M-file. They are useful for automating blocks of MATLAB commands, such as computations you have to perform repeatedly from the command line. Scripts can operate on existing data in the workspace, or they can create new data on which to operate. Although scripts do not return output arguments, any variables that they create remain in the workspace so you can use them in further computations. In addition, scripts can produce graphical output using commands like plot. Scripts can contain any series of MATLAB statements. They require no declarations or begin/end delimiters. Like any M-file, scripts can contain comments. Any text following a percent sign (%) on a given line is comment text. Comments can appear on lines by themselves, or you can append them to the end of any executable line.
See Also
echo, function, type
2-306
sec
Purpose Syntax Description
2sec
Secant
Y = sec(X)
The sec function operates element-wise on arrays. The function's domains and ranges include complex values. All angles are in radians.
Y = sec(X) returns an array the same size as X containing the secant of the elements of X.
Examples
Graph the secant over the domains / 2 < x < / 2 and / 2 < x < 3 / 2 .
x1 = -pi/2+0.01:0.01:pi/2-0.01; x2 = pi/2+0.01:0.01:(3*pi/2)-0.01; plot(x1,sec(x1),x2,sec(x2)), grid on
150
100
50
0
-50
-100
-150 -2
-1
0
1
2
3
4
5
The expression sec(pi/2) does not evaluate as infinite but as the reciprocal of the floating-point accuracy eps, because pi is a floating-point approximation to the exact value of .
Definition
The secant can be defined as 1 sec ( z ) = --------------cos ( z )
2-307
sec
Algorithm
sec 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
asec, asech, eps, pi, sech
2-308
sech
Purpose Syntax Description
2 sech
Hyperbolic secant
Y = sech(X)
The sech function operates element-wise on arrays. The function's domains and ranges include complex values. All angles are in radians.
Y = sech(X) returns an array the same size as X containing the hyperbolic secant of the elements of X.
Examples
Graph the hyperbolic secant over the domain 2 x 2.
x = -2*pi:0.01:2*pi; plot(x,sech(x)), grid on
1 0.9 0.8 0.7 0.6 0.5 0.4 0.3 0.2 0.1 0 -8 -6 -4 -2 0 2 4 6 8
Algorithm
sech uses this algorithm.
1 sech ( z ) = -------------------cosh ( z )
Definition
The secant can be defined as 1 sech ( z ) = -------------------cosh ( z )
2-309
sech
Algorithm
sec 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
asec, asech, sec
2-310
selectmoveresize
Purpose Syntax Description
2selectmoveresize
Select, move, resize, or copy axes and uicontrol graphics objects
A = selectmoveresize; set(h,'ButtonDownFcn','selectmoveresize') selectmoveresize is useful as the callback routine for axes and uicontrol
button down functions. When executed, it selects the object and allows you to move, resize, and copy it. For example, this statement sets the ButtonDownFcn of the current axes to selectmoveresize:
set(gca,'ButtonDownFcn','selectmoveresize') A = selectmoveresize returns a structure array containing:
A.Type: a string containing the action type, which can be Select, Move, Resize, or Copy. A.Handles: a list of the selected handles or for a Copy an m-by-2 matrix containing the original handles in the first column and the new handles in the second column.
See Also
The ButtonDownFcn of axes and uicontrol graphics objects "Object Manipulation" for related functions
2-311
semilogx, semilogy
Purpose Syntax
2semilogx, semilogy
Semi-logarithmic plots
semilogx(Y) semilogx(X1,Y1,...) semilogx(X1,Y1,LineSpec,...) semilogx(...,'PropertyName',PropertyValue,...) h = semilogx(...) semilogy(...) h = semilogy(...)
Description
semilogx and semilogy plot data as logarithmic scales for the x- and y-axis, respectively. logarithmic semilogx(Y) creates a plot using a base 10 logarithmic scale for the x-axis and a linear scale for the y-axis. It plots the columns of Y versus their index if Y contains real numbers. semilogx(Y) is equivalent to semilogx(real(Y), imag(Y)) if Y contains complex numbers. semilogx ignores the imaginary
component in all other uses of this function.
semilogx(X1,Y1,...) plots all Xn versus Yn pairs. If only Xn or Yn is a matrix, semilogx plots the vector argument versus the rows or columns of the matrix,
depending on whether the vector's row or column dimension matches the matrix.
semilogx(X1,Y1,LineSpec,...) plots all lines defined by the Xn,Yn,LineSpec triples. LineSpec determines line style, marker symbol, and color of the plotted
lines.
semilogx(...,'PropertyName',PropertyValue,...) sets property values for
all line graphics objects created by semilogx.
semilogy(...) creates a plot using a base 10 logarithmic scale for the y-axis
and a linear scale for the x-axis.
h = semilogx(...) and h = semilogy(...) return a vector of handles to line
graphics objects, one handle per line.
2-312
semilogx, semilogy
Remarks
If you do not specify a color when plotting more than one line, semilogx and semilogy automatically cycle through the colors and line styles in the order specified by the current axes ColorOrder and LineStyleOrder properties. You can mix Xn,Yn pairs with Xn,Yn,LineSpec triples; for example,
semilogx(X1,Y1,X2,Y2,LineSpec,X3,Y3)
Examples
Create a simple semilogy plot.
x = 0:.1:10; semilogy(x,10.^x)
10
10
10
9
10
8
10
7
10
6
10
5
10
4
10
3
10
2
10
1
10
0
0
1
2
3
4
5
6
7
8
9
10
See Also
line, LineSpec, loglog, plot
"Basic Plots and Graphs" for related functions
2-313
send (COM)
Purpose
2send (COM)
Return a list of events that the control can trigger
Note Support for send will be removed in a future release of MATLAB. Use the events function instead of send.
2-314
sendmail
Purpose Syntax Description
2sendmail
Send e-mail message (attachments optional) to list of addresses
sendmail('recipients','subject','message','attachments') sendmail('recipients','subject','message','attachments') sends message to recipients with the specified subject. For recipients, use a
string for a single address, or a cell array of strings for multiple addresses. Optionally specify attachments as a cell array of files to send along with message. If MATLAB cannot read the SMTP mail server from your system registry, you get an error. You need to identify the outgoing SMTP mail server for your electronic mail application, which is usually listed in preferences. Or, consult your e-mail system administrator. Then provide the information to MATLAB using
setpref('Internet','SMTP_Server','myserver.myhost.com');
Examples
Sample message:
sendmail('user@otherdomain.com','Test subject','Test message', {'directory/attach1.html','attach2.doc'});
2-315
serial
Purpose Syntax Arguments
2serial
Create a serial port object
obj = serial('port') obj = serial('port','PropertyName',PropertyValue,...) 'port' 'PropertyName' PropertyValue obj
The serial port name. A serial port property name. A property value supported by PropertyName. The serial port object.
Description
obj = serial('port') creates a serial port object associated with the serial port specified by port. If port does not exist, or if it is in use, you will not be
able to connect the serial port object to the device.
obj = serial('port','PropertyName',PropertyValue,...) creates a serial
port object with the specified property names and property values. If an invalid property name or property value is specified, an error is returned and the serial port object is not created.
Remarks
When you create a serial port object, these property values are automatically configured: The Type property is given by serial. The Name property is given by concatenating Serial with the port specified in the serial function. The Port property is given by the port specified in the serial function. You can specify the property names and property values using any format supported by the set function. For example, you can use property name/property value cell array pairs. Additionally, you can specify property names without regard to case, and you can make use of property name completion. For example, the following commands are all valid.
s = serial('COM1','BaudRate',4800); s = serial('COM1','baudrate',4800); s = serial('COM1','BAUD',4800);
2-316
serial
Refer to "Configuring Property Values" for a list of serial port object properties that you can use with serial. Before you can communicate with the device, it must be connected to obj with the fopen function. A connected serial port object has a Status property value of open. An error is returned if you attempt a read or write operation while the object is not connected to the device. You can connect only one serial port object to a given serial port.
Example
This example creates the serial port object s1 associated with the serial port COM1.
s1 = serial('COM1');
The Type, Name, and Port properties are automatically configured.
get(s1,{'Type','Name','Port'}) ans = 'serial' 'Serial-COM1'
'COM1'
To specify properties during object creation
s2 = serial('COM2','BaudRate',1200,'DataBits',7);
See Also
Functions
fclose, fopen
Properties
Name, Port, Status, Type
2-317
serialbreak
Purpose Syntax Arguments
2serialbreak
Send a break to the device connected to the serial port
serialbreak(obj) serialbreak(obj,time) obj time
A serial port object. The duration of the break, in milliseconds.
Description
serialbreak(obj) sends a break of 10 milliseconds to the device connected to obj. serialbreak(obj,time) sends a break to the device with a duration, in milliseconds, specified by time. Note that the duration of the break might be
inaccurate under some operating systems.
Remarks
For some devices, the break signal provides a way to clear the hardware buffer. Before you can send a break to the device, it must be connected to obj with the fopen function. A connected serial port object has a Status property value of open. An error is returned if you attempt to send a break while obj is not connected to the device.
serialbreak is a synchronous function, and blocks the command line until
execution is complete. If you issue serialbreak while data is being asynchronously written, an error is returned. In this case, you must call the stopasync function or wait for the write operation to complete.
See Also
Functions
fopen, stopasync
Properties
Status
2-318
set
Purpose Syntax
2set
Set object properties
set(H,'PropertyName',PropertyValue,...) set(H,a) set(H,pn,pv...) set(H,pn,<m-by-n cell array>) a= set(h) a= set(0,'Factory') a= set(0,'FactoryObjectTypePropertyName') a= set(h,'Default') a= set(h,'DefaultObjectTypePropertyName') <cell array> = set(h,'PropertyName') set(H,'PropertyName',PropertyValue,...) sets the named properties to the specified values on the object(s) identified by H. H can be a vector of handles, in which case set sets the properties' values for all the objects. set(H,a) sets the named properties to the specified values on the object(s) identified by H. a is a structure array whose field names are the object property
Description
names and whose field values are the values of the corresponding properties.
set(H,pn,pv,...) sets the named properties specified in the cell array pn to the corresponding value in the cell array pv for all objects identified in H. set(H,pn,<m-by-n cell array>) sets n property values on each of m graphics objects, where m = length(H) and n is equal to the number of property names contained in the cell array pn. This allows you to set a given group of properties
to different values on each object.
a = set(h) returns the user-settable properties and possible values for the object identified by h. a is a structure array whose field names are the object's
property names and whose field values are the possible values of the corresponding properties. If you do not specify an output argument, MATLAB displays the information on the screen. h must be scalar.
a = set(0,'Factory') returns the properties whose defaults are user settable for all objects and lists possible values for each property. a is a
structure array whose field names are the object's property names and whose field values are the possible values of the corresponding properties. If you do
2-319
set
not specify an output argument, MATLAB displays the information on the screen.
a = set(0,'FactoryObjectTypePropertyName') returns the possible values
of the named property for the specified object type, if the values are strings. The argument FactoryObjectTypePropertyName is the word Factory concatenated with the object type (e.g., axes) and the property name (e.g., CameraPosition).
a = set(h,'Default') returns the names of properties having default values set on the object identified by h. set also returns the possible values if they are strings. h must be scalar. a = set(h,'DefaultObjectTypePropertyName') returns the possible values
of the named property for the specified object type, if the values are strings. The argument DefaultObjectTypePropertyName is the word Default concatenated with the object type (e.g., axes) and the property name (e.g., CameraPosition). For example, DefaultAxesCameraPosition. h must be scalar.
pv = set(h,'PropertyName') returns the possible values for the named property. If the possible values are strings, set returns each in a cell of the cell array, pv. For other properties, set returns an empty cell array. If you do not
specify an output argument, MATLAB displays the information on the screen. h must be scalar.
Remarks Examples
You can use any combination of property name/property value pairs, structure arrays, and cell arrays in one call to set. Set the Color property of the current axes to blue.
set(gca,'Color','b')
Change all the lines in a plot to black.
plot(peaks) set(findobj('Type','line'),'Color','k')
You can define a group of properties in a structure to better organize your code. For example, these statements define a structure called active, which contains a set of property definitions used for the uicontrol objects in a
2-320
set
particular figure. When this figure becomes the current figure, MATLAB changes colors and enables the controls.
active.BackgroundColor = [.7 .7 .7]; active.Enable = 'on'; active.ForegroundColor = [0 0 0]; if gcf == control_fig_handle set(findobj(control_fig_handle,'Type','uicontrol'),active) end
You can use cell arrays to set properties to different values on each object. For example, these statements define a cell array to set three properties,
PropName(1) = {'BackgroundColor'}; PropName(2) = {'Enable'}; PropName(3) = {'ForegroundColor'};
These statements define a cell array containing three values for each of three objects (i.e., a 3-by-3 cell array).
PropVal(1,1) = {[.5 .5 .5]}; PropVal(1,2) = {'off'}; PropVal(1,3) = {[.9 .9 .9]}; PropVal(2,1) = {[1 0 0]}; PropVal(2,2) = {'on'}; PropVal(2,3) = {[1 1 1]}; PropVal(3,1) = {[.7 .7 .7]}; PropVal(3,2) = {'on'}; PropVal(3,3) = {[0 0 0]};
Now pass the arguments to set,
set(H,PropName,PropVal)
where length(H) = 3 and each element is the handle to a uicontrol.
See Also
findobj, gca, gcf, gco, gcbo, get
"Finding and Identifying Graphics Objects" for related functions
2-321
set (COM)
Purpose Syntax Arguments
2set (COM)
Set an interface property to a specific value
set(h, 'propertyname', value[, 'propertyname2', value2, ...]) h
Handle for a COM object previously returned from actxcontrol, actxserver, get, or invoke.
propertyname
A string that is the name of the property to be set.
value
The value to which the interface property is set.
Description
Set one or more properties of a COM object to the specified value(s). Each propertyname argument must be followed by a value argument. See "Converting Data" in the External Interfaces documentation for information on how MATLAB converts workspace matrices to COM data types.
Examples
Create an mwsamp control and use set to change the Label and Radius properties:
f = figure ('pos', [100 200 200 200]); h = actxcontrol ('mwsamp.mwsampctrl.1', [0 0 200 200], f); set(h, 'Label', 'Click to fire event', 'Radius', 40); invoke(h, 'Redraw');
See Also
get, inspect, isprop, addproperty, deleteproperty
2-322
set (serial)
Purpose Syntax
2set (serial)
Configure or display serial port object properties
set(obj) props = set(obj) set(obj,'PropertyName') props = set(obj,'PropertyName') set(obj,'PropertyName',PropertyValue,...) set(obj,PN,PV) set(obj,S) obj 'PropertyName' PropertyValue PN PV S props
Arguments
A serial port object or an array of serial port objects. A property name for obj. A property value supported by PropertyName. A cell array of property names. A cell array of property values. A structure with property names and property values. A structure array whose field names are the property names for obj, or cell array of possible values.
Description
set(obj) displays all configurable properties values for obj. If a property has
a finite list of possible string values, then these values are also displayed.
props = set(obj) returns all configurable properties and their possible values for obj to props. props is a structure whose field names are the property names of obj, and whose values are cell arrays of possible property values. If
the property does not have a finite set of possible values, then the cell array is empty.
set(obj,'PropertyName') displays the valid values for PropertyName if it
possesses a finite list of string values.
props = set(obj,'PropertyName') returns the valid values for PropertyName to props. props is a cell array of possible string values or an empty cell array if PropertyName does not have a finite list of possible values.
2-323
set (serial)
set(obj,'PropertyName',PropertyValue,...) configures multiple property
values with a single command.
set(obj,PN,PV) configures the properties specified in the cell array of strings PN to the corresponding values in the cell array PV. PN must be a vector. PV can be m-by-n where m is equal to the number of serial port objects in obj and n is equal to the length of PN. set(obj,S) configures the named properties to the specified values for obj. S
is a structure whose field names are serial port object properties, and whose field values are the values of the corresponding properties.
Remarks
Refer to "Configuring Property Values" for a list of serial port object properties that you can configure with set. You can use any combination of property name/property value pairs, structures, and cell arrays in one call to set. Additionally, you can specify a property name without regard to case, and you can make use of property name completion. For example, if s is a serial port object, then the following commands are all valid.
set(s,'BaudRate') set(s,'baudrate') set(s,'BAUD')
If you use the help command to display help for set, then you need to supply the pathname shown below.
help serial/set
Examples
This example illustrates some of the ways you can use set to configure or return property values for the serial port object s.
s = serial('COM1'); set(s,'BaudRate',9600,'Parity','even') set(s,{'StopBits','RecordName'},{2,'sydney.txt'}) set(s,'Parity') [ {none} | odd | even | mark | space ]
See Also
Functions
get
2-324
set (timer)
Purpose Syntax
2set (timer)
Configure or display timer object properties
set(obj) prop_struct = set(obj) set(obj,'PropertyName') prop_cell = set(obj,'PropertyName') set(obj,'PropertyName',PropertyValue,...) set(obj,S) set(obj,PN,PV) set(obj) displays property names and their possible values for all configurable properties of timer object obj. obj must be a single timer object. prop_struct=set(obj) returns the property names and their possible values for all configurable properties of timer object obj. obj must be a single timer object. The return value, prop_struct, is a structure whose field names are the property names of obj, and whose values are cell arrays of possible property
Description
values or empty cell arrays if the property does not have a finite set of possible string values.
set(obj,'PropertyName') displays the possible values for the specified property, PropertyName, of timer object obj. obj must be a single timer object. prop_cell=set(obj,'PropertyName') returns the possible values for the specified property, PropertyName, of timer object obj. obj must be a single timer object. The returned array, prop_cell, is a cell array of possible value strings or an empty cell array if the property does not have a finite set of possible string values. set(obj,'PropertyName',PropertyValue,...) configures the property, PropertyName, to the specified value, PropertyValue, for timer object obj. You
can specify multiple property name/property value pairs in a single statement. obj can be a single timer object or a vector of timer objects, in which case set configures the property values for all the timer objects specified.
set(obj,S) configures the properties of obj, with the values specified in S, where S is a structure whose field names are object property names.
2-325
set (timer)
set(obj,PN,PV) configures the properties specified in the cell array of strings, PN, to the corresponding values in the cell array PV, for the timer object obj. PN must be a vector. If obj is an array of timer objects, PV can be an M-by-N cell
array, where M is equal to the length of timer object array and N is equal to the length of PN. In this case, each timer object is updated with a different set of values for the list of property names contained in PN.
Note Param-value string pairs, structures, and param-value cell array pairs can be use in the same call to set.
Example
Create a timer object.
t = timer;
Display all configurable properties and their possible values.
set(t) BusyMode: [ {drop} | queue | error ] ErrorFcn ExecutionMode: [{singleShot}|fixedSpacing|fixedDelay|fixedRate] LastError: [ {none} | busy | callback ] Name Period StartDelay StartFcn StopFcn Tag TasksToExecute TimerFcn UserData
Retrieve the possible values of the ExecutionMode property.
set(t, 'ExecutionMode') ans = 'singleShot' 'fixedSpacing' 'fixedDelay'
2-326
set (timer)
'fixedRate'
Set the value of a specific timer object property.
set(t, 'ExecutionMode', 'FixedRate')
Set the values of several properties of the timer object.
set(t, 'TimerFcn', 'callbk', 'Period', 10)
Use a cell array to specify the names of the properties you want to set and another cell array to specify the values of these properties.
set(t, {'StartDelay', 'Period'}, {30, 30})
See Also
timer, get
2-327
setappdata
Purpose Syntax Description
2setappdata
Set application-defined data
setappdata(h,name,value) setappdata(h,name,value) sets application-defined data for the object with handle h. The application-defined data, which is created if it does not already exist, is assigned a name and a value. value can be type of data. getappdata, isappdata, rmappdata
See Also
2-328
setdiff
Purpose Syntax
2setdiff
Return the set difference of two vectors
c = setdiff(A,B) c = setdiff(A,B,'rows') [c,i] = setdiff(...) c = setdiff(A,B) returns the values in A that are not in B. The resulting vector is sorted is ascending order. In set theoretic terms, c = A - B. A and B
Description
can be cell arrays of strings.
c = setdiff(A,B,'rows') when A and B are matrices with the same number of columns returns the rows from A that are not in B. [c,i] = setdiff(...) also returns an index vector index such that c = a(i) or c = a(i,:).
Examples
A = magic(5); B = magic(4); [c,i] = setdiff(A(:),B(:)); c' = 17 18 19 20 i' = 1 10 14 18
21 19
22 23
23 2
24 6
25 15
See Also
intersect, ismember, issorted, setxor, union, unique
2-329
setfield
Purpose
2setfield
Set field of structure array
Note setfield is obsolete and will be removed in a future release. Please use dynamic field names instead.
Syntax Description
s = setfield(s,'field',v) s = setfield(s,{i,j},'field',{k},v) s = setfield(s,'field',v), where s is a 1-by-1 structure, sets the contents of the specified field to the value v. This is equivalent to the syntax s.field = v. s = setfield(s,{i,j},'field',{k},v) sets the contents of the specified field to the value v. This is equivalent to the syntax s(i,j).field(k) = v. All
subscripts must be passed as cell arrays--that is, they must be enclosed in curly braces (similar to{i,j} and {k} above). Pass field references as strings.
Examples
Given the structure
mystr(1,1).name mystr(1,1).ID = mystr(2,1).name mystr(2,1).ID = = 'alice'; 0; = 'gertrude'; 1;
You can change the name field of mystr(2,1) using
mystr = setfield(mystr,{2,1},'name','ted'); mystr(2,1).name ans = ted
The following example sets fields of a structure using setfield with variable and quoted field names and additional subscripting arguments.
class = 5; student = 'John_Doe'; grades_Doe = [85,89,76,93,85,91,68,84,95,73]; grades = [];
2-330
setfield
grades = setfield(grades,{class}, student, 'Math',{10,21:30},... grades_Doe);
You can check the outcome using the standard structure syntax.
grades(class).John_Doe.Math(10,21:30) ans = 85 89 76 93 85 91 68 84 95 73
See Also
fieldnames, isfield, orderfields, rmfield
2-331
setstr
Purpose Description
2setstr
Set string flag This MATLAB 4 function has been renamed char in MATLAB 5.
2-332
setxor
Purpose Syntax
2setxor
Set exclusive-or of two vectors
c = setxor(A,B) c = setxor(A,B,'rows') [c,ia,ib] = setxor(...) c = setxor(A,B) returns the values that are not in the intersection of A and B. The resulting vector is sorted. A and B can be cell arrays of strings. c = setxor(A,B,'rows') when A and B are matrices with the same number of columns returns the rows that are not in the intersection of A and B. [c,ia,ib] = setxor(...) also returns index vectors ia and ib such that c is a sorted combination of the elements c = a(ia) and c = b(ib) or, for row combinations, c = a(ia,:) and c = b(ib,:).
Description
Examples
a = [-1 0 1 Inf -Inf NaN]; b = [-2 pi 0 Inf]; c = setxor(a,b) c = -Inf -2.0000 -1.0000 1.0000 3.1416 NaN
See Also
intersect, ismember, issorted, setdiff, union, unique
2-333
shading
Purpose Syntax
2shading
Set color shading properties
shading flat shading faceted shading interp
Description
The shading function controls the color shading of surface and patch graphics objects.
shading flat each mesh line segment and face has a constant color
determined by the color value at the end point of the segment or the corner of the face that has the smallest index or indices.
shading faceted flat shading with superimposed black mesh lines. This is the
default shading mode.
shading interp varies the color in each line segment and face by interpolating
the colormap index or true color value across the line or face.
Examples
Compare a flat, faceted, and interpolated-shaded sphere.
subplot(3,1,1) sphere(16) axis square shading flat title('Flat Shading') subplot(3,1,2) sphere(16) axis square shading faceted title('Faceted Shading') subplot(3,1,3) sphere(16) axis square shading interp title('Interpolated Shading')
2-334
shading
Algorithm
shading sets the EdgeColor and FaceColor properties of all surface and patch graphics objects in the current axes. shading sets the appropriate values,
depending on whether the surface or patch objects represent meshes or solid surfaces.
2-335
shading
See Also
fill, fill3, hidden, mesh, patch, pcolor, surf
The EdgeColor and FaceColor properties for surface and patch graphics objects. "Color Operations" for related functions
2-336
shiftdim
Purpose Syntax Description
2shiftdim
Shift dimensions
B = shiftdim(X,n) [B,nshifts] = shiftdim(X) B = shiftdim(X,n) shifts the dimensions of X by n. When n is positive, shiftdim shifts the dimensions to the left and wraps the n leading dimensions to the end. When n is negative, shiftdim shifts the dimensions to the right and
pads with singletons.
[B,nshifts] = shiftdim(X) returns the array B with the same number of elements as X but with any leading singleton dimensions removed. A singleton dimension is any dimension for which size(A,dim) = 1. nshifts is the number
of dimensions that are removed. If X is a scalar, shiftdim has no effect.
Examples
The shiftdim command is handy for creating functions that, like sum or diff, work along the first nonsingleton dimension.
a = rand(1,1,3,1,2); [b,n] = shiftdim(a); % b is 3-by-1-by-2 and n is 2. c = shiftdim(b,-n); % c == a. d = shiftdim(a,3); % d is 1-by-2-by-1-by-1-by-3.
See Also
circshift, reshape, squeeze
2-337
shrinkfaces
Purpose Syntax
2shrinkfaces
Reduce the size of patch faces
shrinkfaces(p,sf) nfv = shrinkfaces(p,sf) nfv = shrinkfaces(fv,sf) shrinkfaces(p), shrinkfaces(fv) nfv = shrinkfaces(f,v,sf) [nf,nv] = shrinkfaces(...) shrinkfaces(p,sf) shrinks the area of the faces in patch p to shrink factor sf. A shrink factor of 0.6 shrinks each face to 60% of its original area. If the patch contains shared vertices, MATLAB creates nonshared vertices before performing the face-area reduction. nfv = shrinkfaces(p,sf) returns the face and vertex data in the struct nfv, but does not set the Faces and Vertices properties of patch p. nfv = shrinkfaces(fv,sf) uses the face and vertex data from the struct fv. shrinkfaces(p) and shrinkfaces(fv) (without specifying a shrink factor)
Description
assume a shrink factor of 0.3.
nfv = shrinkfaces(f,v,sf) uses the face and vertex data from the arrays f and v. [nf,nv] = shrinkfaces(...) returns the face and vertex data in two separate
arrays instead of a struct.
Examples
This example uses the flow data set, which represents the speed profile of a submerged jet within a infinite tank (type help flow for more information). Two isosurfaces provide a before and after view of the effects of shrinking the face size. First reducevolume samples the flow data at every other point and then isosurface generates the faces and vertices data. The patch command accepts the face/vertex struct and draws the first (p1) isosurface. Use the daspect, view, and axis commands to set up the view and then add a title.
2-338
shrinkfaces
The shrinkfaces command modifies the face/vertex data and passes it directly to patch.
[x,y,z,v] = flow; [x,y,z,v] = reducevolume(x,y,z,v,2); fv = isosurface(x,y,z,v,-3); p1 = patch(fv); set(p1,'FaceColor','red','EdgeColor',[.5,.5,.5]); daspect([1 1 1]); view(3); axis tight title('Original') figure p2 = patch(shrinkfaces(fv,.3)); set(p2,'FaceColor','red','EdgeColor',[.5,.5,.5]); daspect([1 1 1]); view(3); axis tight
2-339
shrinkfaces
title('After Shrinking')
Original
3 2 1 0 -1 -2 -3 3 2 1 0 -1 -2 -3 2 4 6 8
2-340
shrinkfaces
After Shrinking
2 1 0 -1 -2
2 1 0 -1 -2 2 4 6
8
See Also
isosurface, patch, reducevolume, daspect, view, axis
"Volume Visualization" for related functions
2-341
sign
Purpose Syntax Description
2sign
Signum function
Y = sign(X) Y = sign(X) returns an array Y the same size as X, where each element of Y is:
1 if the corresponding element of X is greater than zero 0 if the corresponding element of X equals zero -1 if the corresponding element of X is less than zero For nonzero complex X, sign(X) = X./abs(X).
See Also
abs, conj, imag, real
2-342
sin
Purpose Syntax Description
2sin
Sine
Y = sin(X)
The sin function operates element-wise on arrays. The function's domains and ranges include complex values. All angles are in radians.
Y = sin(X) returns the circular sine of the elements of X.
Examples
Graph the sine function over the domain x .
x = -pi:0.01:pi; plot(x,sin(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 sin(pi) is not exactly zero, but rather a value the size of the floating-point accuracy eps, because pi is only a floating-point approximation to the exact value of .
2-343
sin
Definition
The sine can be defined as sin ( x + iy ) = sin ( x )cosh ( y ) + i cos ( x )sinh ( y ) e iz e iz sin ( z ) = ---------------------2i
Algorithm
sin 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, asinh, sinh
2-344
single
Purpose Syntax Description
2single
Convert to single-precision
B = single(A) B = single(A) converts the matrix A to single-precision, returning that value in B. A can be any numeric object (such as a double). If A is already single-precision, single has no effect. Single-precision quantities require less
storage than double-precision quantities, but have less precision and a smaller range. The single class is primarily meant to be used to store single-precision values. Hence most operations that manipulate arrays without changing their elements are defined. Examples are reshape, size, the relational operators, subscripted assignment and subscripted reference. No math operations are defined for single objects. You can define your own methods for the single class by placing the appropriately named method in an @single directory within a directory on your path.
Examples
a = magic(4); b = single(a); whos Name a b
Size 4x4 4x4
Bytes 128 64
Class double array single array
See Also
double
2-345
sinh
Purpose Syntax Description
2 sinh
Hyperbolic sine
Y = sinh(X)
The sinh function operates element-wise on arrays. The function's domains and ranges include complex values. All angles are in radians.
Y = sinh(X) returns the hyperbolic sine of the elements of X.
Examples
Graph the hyperbolic sine function over the domain 5 x 5 .
x = -5:0.01:5; plot(x,sinh(x)), grid on
80 60 40 20 0 -20 -40 -60 -80 -5
0
5
Definition
The hyperbolic sine can be defined as e z ez sinh ( z ) = -----------------2
Algorithm
sinh 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-346
sinh
See Also
asin, asinh, sin
2-347
size
Purpose Syntax
2size
Array dimensions
d = size(X) [m,n] = size(X) m = size(X,dim) [d1,d2,d3,...,dn] = size(X) d = size(X) returns the sizes of each dimension of array X in a vector d with ndims(X) elements. [m,n] = size(X) returns the size of matrix X in separate variables m and n. m = size(X,dim) returns the size of the dimension of X specified by scalar dim. [d1,d2,d3,...,dn] = size(X) returns the sizes of the first n dimensions of array X in separate variables.
Description
If the number of output arguments n does not equal ndims(X), then for:
n > ndims(X) n < ndims(X) size returns ones in the "extra" variables, i.e., outputs ndims(X)+1 through n. dn contains the product of the sizes of the remaining dimensions of X, i.e., dimensions n+1 through ndims(X).
Note For a Java array, size returns the length of the Java array as the number of rows. The number of columns is always 1. For a Java array of arrays, the result describes only the top level array.
Examples
Example 1. The size of the second dimension of rand(2,3,4) is 3.
m = size(rand(2,3,4),2) m = 3
Here the size is output as a single vector.
2-348
size
d = size(rand(2,3,4)) d = 2 3 4
Here the size of each dimension is assigned to a separate variable.
[m,n,p] = size(rand(2,3,4)) m = 2 n = 3 p = 4
Example 2. If X = ones(3,4,5), then
[d1,d2,d3] = size(X) d1 = 3 d2 = 4 d3 = 5
But when the number of output variables is less than ndims(X):
[d1,d2] = size(X) d1 = 3 d2 = 20
The "extra" dimensions are collapsed into a single product. If n > ndims(X), the "extra" variables all represent singleton dimensions:
[d1,d2,d3,d4,d5,d6] = size(X) d1 = 3 d4 = 1 d5 = 1 d2 = 4 d6 = 1 d3 = 5
2-349
size
See Also
exist, length, whos
2-350
size (serial)
Purpose Syntax
2size (serial)
Size of serial port object array
d = size(obj) [m,n] = size(obj) [m1,m2,...,mn] = size(obj) m = size(obj,dim) obj dim d m
Arguments
A serial port object or an array of serial port objects. The dimension of obj. The number of rows and columns in obj. The number of rows in obj, or the length of the dimension specified by dim. The number of columns in obj. The length of the first N dimensions of obj.
n m1,m2,...,m n
Description
d = size(obj) returns the two-element row vector d containing the number of rows and columns in obj. [m,n] = size(obj) returns the number of rows and columns in separate
output variables.
[m1,m2,m3,...,mn] = size(obj) returns the length of the first n dimensions of obj. m = size(obj,dim) returns the length of the dimension specified by the scalar dim. For example, size(obj,1) returns the number of rows.
See Also
Functions
length
2-351
slice
Purpose Syntax
2slice
Volumetric slice plot
slice(V,sx,sy,sz) slice(X,Y,Z,V,sx,sy,sz) slice(V,XI,YI,ZI) slice(X,Y,Z,V,XI,YI,ZI) slice(...,'method') h = slice(...) slice displays orthogonal slice planes through volumetric data. slice(V,sx,sy,sz) draws slices along the x, y, z directions in the volume V at the points in the vectors sx, sy, and sz. V is an m-by-n-by-p volume array containing data values at the default location X = 1:n, Y = 1:m, Z = 1:p. Each element in the vectors sx, sy, and sz defines a slice plane in the x-, y-, or z-axis
Description
direction.
slice(X,Y,Z,V,sx,sy,sz) draws slices of the volume V. X, Y, and Z are three-dimensional arrays specifying the coordinates for V. X, Y, and Z must be monotonic and orthogonally spaced (as if produced by the function meshgrid). The color at each point is determined by 3-D interpolation into the volume V. slice(V,XI,YI,ZI) draws data in the volume V for the slices defined by XI, YI, and ZI. XI, YI, and ZI are matrices that define a surface, and the volume is evaluated at the surface points. XI, YI, and ZI must all be the same size. slice(X,Y,Z,V,XI,YI,ZI) draws slices through the volume V along the surface defined by the arrays XI, YI, ZI. slice(...,'method') specifies the interpolation method. 'method' is 'linear', 'cubic', or 'nearest'.
linear specifies trilinear interpolation (the default). cubic specifies tricubic interpolation. nearest specifies nearest neighbor interpolation.
h = slice(...) returns a vector of handles to surface graphics objects.
2-352
slice
Remarks Examples
The color drawn at each point is determined by interpolation into the volume V. Visualize the function v = xe ( x
2
y2 z2 )
over the range 2 x 2, 2 y 2, 2 z 2:
[x,y,z] = meshgrid(-2:.2:2,-2:.25:2,-2:.16:2); v = x.*exp(-x.^2-y.^2-z.^2); xslice = [-1.2,.8,2]; yslice = 2; zslice = [-2,0]; slice(x,y,z,v,xslice,yslice,zslice) colormap hsv
2 1.5 1 0.5 0 -0.5 -1 -1.5 -2 2 1 0 1 -1 -2 -2 0 -1 2
z axis sliced at 0 and -2
y axis sliced at 2
x axis sliced at -1.2, .8, and 2
Slicing At Arbitrary Angles
You can also create slices that are oriented in arbitrary planes. To do this, Create a slice surface in the domain of the volume (surf, linspace). Orient this surface with respect the the axes (rotate).
2-353
slice
Get the XData, YData, and ZData of the surface (get). Use this data to draw the slice plane within the volume. For example, these statements slice the volume in the first example with a rotated plane. Placing these commands within a for loop "passes" the plane through the volume along the z-axis.
for i = -2:.5:2 hsp = surf(linspace(-2,2,20),linspace(-2,2,20),zeros(20)+i); rotate(hsp,[1,-1,1],30) xd = get(hsp,'XData'); yd = get(hsp,'YData'); zd = get(hsp,'ZData'); delete(hsp) slice(x,y,z,v,[-2,2],2,-2) % Draw some volume boundaries hold on slice(x,y,z,v,xd,yd,zd) hold off axis tight view(-5,10) drawnow end
The following picture illustrates three positions of the same slice surface as it passes through the volume.
2-354
slice
2 1.5 1 0.5 0 -0.5 -1 -1.5 -2
2 0 -2 -2.5 -2 -1.5 -1 -0.5 0 0.5 1 1.5 2 2.5
Slicing with a Nonplanar Surface
You can slice the volume with any surface. This example probes the volume created in the previous example by passing a spherical slice surface through the volume.
[xsp,ysp,zsp] = sphere; slice(x,y,z,v,[-2,2],2,-2) % Draw some volume boundaries
for i = -3:.2:3 hsp = surface(xsp+i,ysp,zsp); rotate(hsp,[1 0 0],90) xd = get(hsp,'XData'); yd = get(hsp,'YData'); zd = get(hsp,'ZData'); delete(hsp) hold on hslicer = slice(x,y,z,v,xd,yd,zd); axis tight
2-355
slice
xlim([-3,3]) view(-10,35) drawnow delete(hslicer) hold off end
The following picture illustrates three positions of the spherical slice surface as it passes through the volume.
2 1.5 1 0.5 0 -0.5 -1 -1.5 -2 2 1 0 -1 -2 -3 0 1 2 3
-2
-1
See Also
interp3, meshgrid
"Volume Visualization" for related functions Exploring Volumes with Slice Planes for more examples.
2-356
smooth3
Purpose Syntax
2smooth3
Smooth 3-D data
W W W W = = = = smooth3(V) smooth3(V,'filter') smooth3(V,'filter',size) smooth3(V,'filter',size,sd)
Description
W = smooth3(V) smooths the input data V and returns the smoothed data in W. W = smooth3(V,'filter') filter determines the convolution kernel and can
be the strings: 'gaussian' 'box' (default)
W = smooth3(V,'filter',size) sets the size of the convolution kernel (default is [3 3 3]). If size is scalar, then size is interpreted as [size, size, size]. W = smooth3(V,'filter',size,sd) sets an attribute of the convolution kernel. When filter is gaussian, sd is the standard deviation (default is .65).
Examples
This example smooths some random 3-D data and then creates an isosurface with end caps.
rand('seed',0) data = rand(10,10,10); data = smooth3(data,'box',5); p1 = patch(isosurface(data,.5), ... 'FaceColor','blue','EdgeColor','none'); p2 = patch(isocaps(data,.5), ... 'FaceColor','interp','EdgeColor','none'); isonormals(data,p1) view(3); axis vis3d tight camlight; lighting phong
2-357
smooth3
See Also
isocaps, isonormals, isosurface, patch
"Volume Visualization" for related functions See Displaying an Isosurface for another example
2-358
sort
Purpose Syntax
2sort
Sort elements in ascending order
B = sort(A) B = sort(A,dim) [B,INDEX] = sort(A,...) B = sort(A) sorts the elements along different dimensions of an array, and
Description
arranges those elements in ascending order.
If A is a ... sort(A) ...
Vector Matrix Multidimensional array Cell array of strings
Sorts the elements of A in ascending order. Sorts each column of A in ascending order. Sorts A along the first non-singleton dimension, and returns an array of sorted vectors. Sorts the strings in ASCII dictionary order.
Real, complex, and string elements are permitted. For elements of A with identical values, the order of these elements is preserved in the sorted list. When A is complex, the elements are sorted by magnitude, i.e., abs(A), and where magnitudes are equal, further sorted by phase angle, i.e., angle(A), on the interval [ , ] . If A includes any NaN elements, sort places these at the end.
B = sort(A,dim) sorts the elements along the dimension of A specified by a scalar dim. If dim is a vector, sort works iteratively on the specified dimensions. Thus, sort(A,[1 2]) is equivalent to sort(sort(A,2),1). [B,IX] = sort(A,...) also returns an array of indices IX, where size(IX) == size(A). If A is a vector, B = A(IX). If A is an m-by-n matrix, then each column of IX is a permutation vector of the corresponding column of A,
such that
for j = 1:n B(:,j) = A(IX(:,j),j); end
2-359
sort
If A has repeated elements of equal value, the returned indices preserve the original ordering.
Examples
This example sorts a matrix A in each dimension, and then sorts it a third time, requesting an array of indices for the sorted result.
A = [ 3 7 5 0 4 2 ]; sort(A,1) ans = 0 3 sort(A,2) ans = 3 0 5 2 7 4 4 7 2 5
[B,IX] = sort(A,2) B = 3 0 IX = 1 1 3 3 2 2 5 2 7 4
See Also
max, mean, median, min, sortrows
2-360
sortrows
Purpose Syntax
2sortrows
Sort rows in ascending order
B = sortrows(A) B = sortrows(A,column) [B,index] = sortrows(A) B = sortrows(A) sorts the rows of A as a group in ascending order. Argument A must be either a matrix or a column vector.
Description
For strings, this is the familiar dictionary sort. When A is complex, the elements are sorted by magnitude, and, where magnitudes are equal, further sorted by phase angle on the interval [ , ] .
B = sortrows(A,column) sorts the matrix based on the columns specified in the vector column. For example, sortrows(A,[2 3]) sorts the rows of A by the
second column, and where these are equal, further sorts by the third column.
[B,index] = sortrows(A) also returns an index vector index.
If A is a column vector, then B = A(index). If A is an m-by-n matrix, then B = A(index,:).
Examples
Given the 5-by-5 string matrix,
A = ['one ';'two ';'three';'four ';'five '];
The commands B = sortrows(A) and C = sortrows(A,1) yield
B = five four one three two C = four five one two three
See Also
sort
2-361
sound
Purpose Syntax
2sound
Convert vector into sound
sound(y,Fs) sound(y) sound(y,Fs,bits) sound(y,Fs), sends the signal in vector y (with sample frequency Fs) to the speaker on PC and most UNIX platforms. Values in y are assumed to be in the
Description
range 1.0 y 1.0 . Values outside that range are clipped. Stereo sound is played on platforms that support it when y is an n-by-2 matrix.
Note The playback duration that results from setting Fs depends on the sound card you have installed. Most sound cards support sample frequencies of approximately 5-10kHz to 44.1KHz. Sample frequencies outside this range may produce unexpected results.
sound(y) plays the sound at the default sample rate or 8192 Hz. sound(y,Fs,bits) plays the sound using bits number of bits/sample, if possible. Most platforms support bits = 8 or bits = 16.
Remarks See Also
MATLAB supports all Windows-compatible sound devices.
auread, auwrite, soundsc, wavread, wavwrite
2-362
soundsc
Purpose Syntax
2soundsc
Scale data and play as sound
soundsc(y,Fs) soundsc(y) soundsc(y,Fs,bits) soundsc(y,...,slim) soundsc(y,Fs) sends the signal in vector y (with sample frequency Fs) to the speaker on PC and most UNIX platforms. The signal y is scaled to the range
Description
1.0 y 1.0 before it is played, resulting in a sound that is played as loud as possible without clipping.
Note The playback duration that results from setting Fs depends on the sound card you have installed. Most sound cards support sample frequencies of approximately 5-10kHz to 44.1KHz. Sample frequencies outside this range may produce unexpected results.
soundsc(y) plays the sound at the default sample rate or 8192 Hz. soundsc(y,Fs,bits) plays the sound using bits number of bits/sample if possible. Most platforms support bits = 8 or bits = 16. soundsc(y,...,slim) where slim = [slow shigh] maps the values in y between slow and shigh to the full sound range. The default value is slim = [min(y) max(y)].
Remarks See Also
MATLAB supports all Windows-compatible sound devices.
auread, auwrite, sound, wavread, wavwrite
2-363
spalloc
Purpose Syntax Description
2spalloc
Allocate space for sparse matrix
S = spalloc(m,n,nzmax) S = spalloc(m,n,nzmax) creates an all zero sparse matrix S of size m-by-n with room to hold nzmax nonzeros. The matrix can then be generated column
by column without requiring repeated storage allocation as the number of nonzeros grows.
spalloc(m,n,nzmax) is shorthand for sparse([],[],[],m,n,nzmax)
Examples
To generate efficiently a sparse matrix that has an average of at most three nonzero elements per column
S = spalloc(n,n,3*n); for j = 1:n S(:,j) = [zeros(n-3,1)' round(rand(3,1))']'; end
2-364
sparse
Purpose Syntax
2sparse
Create sparse matrix
S S S S S = = = = = sparse(A) sparse(i,j,s,m,n,nzmax) sparse(i,j,s,m,n) sparse(i,j,s) sparse(m,n)
Description
The sparse function generates matrices in the MATLAB sparse storage organization.
S = sparse(A) converts a full matrix to sparse by form squeezing out any zero elements. If S is already sparse, sparse(S) returns S. S = sparse(i,j,s,m,n,nzmax) uses vectors i, j, and s to generate an m-by-n sparse matrix such that S(i(k),j(k)) = s(k), with space allocated for nzmax nonzeros. Vectors i, j, and s are all the same length. Any elements of s that are zero are ignored, along with the corresponding values of i and j. Any elements of s that have duplicate values of i and j are added together.
Note If any value in i or j is larger than the maximum integer size, 2^31-1, then the sparse matrix cannot be constructed.
To simplify this six-argument call, you can pass scalars for the argument s and one of the arguments i or j--in which case they are expanded so that i, j, and s all have the same length.
S = sparse(i,j,s,m,n) uses nzmax = length(s). S = sparse(i,j,s) uses m = max(i) and n = max(j). The maxima are computed before any zeros in s are removed, so one of the rows of [i j s] might be [m n 0]. S = sparse(m,n) abbreviates sparse([],[],[],m,n,0). This generates the ultimate sparse matrix, an m-by-n all zero matrix.
2-365
sparse
Remarks
All of the MATLAB built-in arithmetic, logical, and indexing operations can be applied to sparse matrices, or to mixtures of sparse and full matrices. Operations on sparse matrices return sparse matrices and operations on full matrices return full matrices. In most cases, operations on mixtures of sparse and full matrices return full matrices. The exceptions include situations where the result of a mixed operation is structurally sparse, for example, A.*S is at least as sparse as S.
Examples
S = sparse(1:n,1:n,1) generates a sparse representation of the n-by-n identity matrix. The same S results from S = sparse(eye(n,n)), but this would also temporarily generate a full n-by-n matrix with most of its elements
equal to zero.
B = sparse(10000,10000,pi) is probably not very useful, but is legal and works; it sets up a 10000-by-10000 matrix with only one nonzero element. Don't try full(B); it requires 800 megabytes of storage.
This dissects and then reassembles a sparse matrix:
[i,j,s] = find(S); [m,n] = size(S); S = sparse(i,j,s,m,n);
So does this, if the last row and column have nonzero entries:
[i,j,s] = find(S); S = sparse(i,j,s);
See Also
diag, find, full, nnz, nonzeros, nzmax, spones, sprandn, sprandsym, spy
The sparfun directory
2-366
spaugment
Purpose Syntax Description
2spaugment
Form least squares augmented system
S = spaugment(A,c) S = spaugment(A,c) creates the sparse, square, symmetric indefinite matrix S = [c*I A; A' 0]. The matrix S is related to the least squares problem min norm(b - A*x)
by
r = b - A*x S * [r/c; x] = [b; 0]
The optimum value of the residual scaling factor c, involves min(svd(A)) and norm(r), which are usually too expensive to compute.
S = spaugment(A) without a specified value of c, uses max(max(abs(A)))/1000.
Note In previous versions of MATLAB, the augmented matrix was used by sparse linear equation solvers, \ and /, for nonsquare problems. Now, MATLAB performs a least squares solve using the qr factorization of A instead.
See Also
spparms
2-367
spconvert
Purpose Syntax Description
2spconvert
Import matrix from sparse matrix external format
S = spconvert(D) spconvert is used to create sparse matrices from a simple sparse format easily produced by non-MATLAB sparse programs. spconvert is the second step in
the process:
1 Load an ASCII data file containing [i,j,v] or [i,j,re,im] as rows into a
MATLAB variable.
2 Convert that variable into a MATLAB sparse matrix.
S = spconvert(D) converts a matrix D with rows containing [i,j,s] or [i,j,r,s] to the corresponding sparse matrix. D must have an nnz or nnz+1
row and three or four columns. Three elements per row generate a real matrix and four elements per row generate a complex matrix. A row of the form [m n 0] or [m n 0 0] anywhere in D can be used to specify size(S). If D is already sparse, no conversion is done, so spconvert can be used after D is loaded from either a MAT-file or an ASCII file.
Examples
Suppose the ASCII file uphill.dat contains
1 1 2 1 2 3 1 2 3 4 4 1 2 2 3 3 3 4 4 4 4 4 1.000000000000000 0.500000000000000 0.333333333333333 0.333333333333333 0.250000000000000 0.200000000000000 0.250000000000000 0.200000000000000 0.166666666666667 0.142857142857143 0.000000000000000
Then the statements
load uphill.dat H = spconvert(uphill)
2-368
spconvert
H = (1,1) (1,2) (2,2) (1,3) (2,3) (3,3) (1,4) (2,4) (3,4) (4,4) 1.0000 0.5000 0.3333 0.3333 0.2500 0.2000 0.2500 0.2000 0.1667 0.1429
recreate sparse(triu(hilb(4))), possibly with roundoff errors. In this case, the last line of the input file is not necessary because the earlier lines already specify that the matrix is at least 4-by-4.
2-369
spdiags
Purpose Syntax
2spdiags
Extract and create sparse band and diagonal matrices
[B,d] = spdiags(A) B = spdiags(A,d) A = spdiags(B,d,A) A = spdiags(B,d,m,n)
Description
The spdiags function generalizes the function diag. Four different operations, distinguished by the number of input arguments, are possible:
[B,d] = spdiags(A) extracts all nonzero diagonals from the m-by-n matrix A. B is a min(m,n)-by-p matrix whose columns are the p nonzero diagonals of A. d is a vector of length p whose integer components specify the diagonals in A. B = spdiags(A,d) extracts the diagonals specified by d. A = spdiags(B,d,A) replaces the diagonals specified by d with the columns of B. The output is sparse. A = spdiags(B,d,m,n) creates an m-by-n sparse matrix by taking the columns of B and placing them along the diagonals specified by d.
Note If a column of B is longer than the diagonal it's replacing, spdiags takes elements of super-diagonals from the lower part of the column of B, and elements of sub-diagonals from the upper part of the column of B.
Arguments
The spdiags function deals with three matrices, in various combinations, as both input and output.
A B d
An m-by-n matrix, usually (but not necessarily) sparse, with its nonzero or specified elements located on p diagonals. A min(m,n)-by-p matrix, usually (but not necessarily) full, whose columns are the diagonals of A. A vector of length p whose integer components specify the diagonals in A.
2-370
spdiags
Roughly, A, B, and d are related by
for k = 1:p B(:,k) = diag(A,d(k)) end
Some elements of B, corresponding to positions outside of A, are not defined by these loops. They are not referenced when B is input and are set to zero when B is output.
Examples
Example 1. This example generates a sparse tridiagonal representation of the
classic second difference operator on n points.
e = ones(n,1); A = spdiags([e -2*e e], -1:1, n, n)
Turn it into Wilkinson's test matrix (see gallery):
A = spdiags(abs(-(n-1)/2:(n-1)/2)',0,A)
Finally, recover the three diagonals:
B = spdiags(A)
Example 2. The second example is not square.
A = [11 0 0 41 0 0 0 0 22 0 0 52 0 0 13 0 33 0 0 63 0 0 24 0 44 0 0 74]
Here m = 7, n = 4, and p = 3. The statement [B,d] = spdiags(A) produces d = [-3 0 2]' and
B = [41 52 63 74 11 22 33 44 0 0 13 24]
2-371
spdiags
Conversely, with the above B and d, the expression spdiags(B,d,7,4) reproduces the original A.
Example 3. This example shows how spdiags creates the diagonals when the
columns of B are longer than the diagonals they are replacing.
B = repmat((1:6)',[1 7]) B = 1 2 3 4 5 6 1 2 3 4 5 6 1 2 3 4 5 6 1 2 3 4 5 6 1 2 3 4 5 6 1 2 3 4 5 6 1 2 3 4 5 6
d = [-4 -2 -1 0 3 4 5]; A = spdiags(B,d,6,6); full(A) ans = 1 1 1 0 1 0 0 2 2 2 0 2 0 0 3 3 3 0 4 0 0 4 4 4 5 5 0 0 5 5 6 6 6 0 0 6
See Also
diag
2-372
speye
Purpose Syntax Description
2speye
Sparse identity matrix
S = speye(m,n) S = speye(n) S = speye(m,n) forms an m-by-n sparse matrix with 1s on the main diagonal. S = speye(n) abbreviates speye(n,n).
Examples
I = speye(1000) forms the sparse representation of the 1000-by-1000 identity
matrix, which requires only about 16 kilobytes of storage. This is the same final result as I = sparse(eye(1000,1000)), but the latter requires eight megabytes for temporary storage for the full representation.
See Also
spalloc, spones, spdiags, sprand, sprandn
2-373
spfun
Purpose Syntax Description
2spfun
Apply function to nonzero sparse matrix elements
f = spfun(fun,S)
The spfun function selectively applies a function to only the nonzero elements of a sparse matrix S, preserving the sparsity pattern of the original matrix (except for underflow or if fun returns zero for some nonzero elements of S).
f = spfun(fun,S) evaluates fun(S) on the nonzero elements of S. You can specify fun as a function handle or as an inline object.
Remarks Examples
Functions that operate element-by-element, like those in the elfun directory, are the most appropriate functions to use with spfun. Given the 4-by-4 sparse diagonal matrix
S = spdiags([1:4]',0,4,4) S = (1,1) (2,2) (3,3) (4,4) 1 2 3 4
Because fun returns nonzero values for all nonzero element of S, f = spfun(@exp,S) has the same sparsity pattern as S.
f = (1,1) (2,2) (3,3) (4,4) 2.7183 7.3891 20.0855 54.5982
whereas exp(S) has 1s where S has 0s.
full(exp(S)) ans = 2.7183 1.0000
1.0000 7.3891
1.0000 1.0000
1.0000 1.0000
2-374
spfun
1.0000 1.0000
1.0000 1.0000
20.0855 1.0000
1.0000 54.5982
See Also
function handle (@), inline
2-375
sph2cart
Purpose Syntax Description
2sph2cart
Transform spherical coordinates to Cartesian
[x,y,z] = sph2cart(THETA,PHI,R) [x,y,z] = sph2cart(THETA,PHI,R) transforms the corresponding elements of spherical coordinate arrays to Cartesian, or xyz, coordinates. THETA, PHI, and R must all be the same size. THETA and PHI are angular displacements in
radians from the positive x-axis and from the x-y plane, respectively.
Algorithm
The mapping from spherical coordinates to three-dimensional Cartesian coordinates is
Z
P
r
phi
th eta
Y
x = r .* cos(phi) .* cos(theta) y = r .* cos(phi) .* sin(theta) z = r .* sin(phi)
X
See Also
cart2pol, cart2sph, pol2cart
2-376
sphere
Purpose Syntax
2sphere
Generate sphere
sphere sphere(n) [X,Y,Z] = sphere(...)
Description
The sphere function generates the x-, y-, and z-coordinates of a unit sphere for use with surf and mesh.
sphere generates a sphere consisting of 20-by-20 faces. sphere(n) draws a surf plot of an n-by-n sphere in the current figure. [X,Y,Z] = sphere(n) returns the coordinates of a sphere in three matrices that are (n+1)by(n+1) in size. You draw the sphere with surf(X,Y,Z) or mesh(X,Y,Z).
Examples
Generate and plot a sphere.
sphere axis equal
1
0.5
0
-0.5
-1 1 0.5 0 0 -0.5 -1 -1 -0.5 0.5 1
2-377
sphere
See Also
cylinder, axis equal
"Polygons and Surfaces" for related functions
2-378
spinmap
Purpose Syntax
2spinmap
Spin colormap
spinmap spinmap(t) spinmap(t,inc) spinmap('inf')
Description
The spinmap function shifts the colormap RGB values by some incremental value. For example, if the increment equals 1, color 1 becomes color 2, color 2 becomes color 3, etc.
spinmap cyclically rotates the colormap for approximately five seconds using
an incremental value of 2.
spinmap(t) rotates the colormap for approximately 10*t seconds. The amount of time specified by t depends on your hardware configuration (e.g., if you are
running MATLAB over a network).
spinmap(t,inc) rotates the colormap for approximately 10*t seconds and specifies an increment inc by which the colormap shifts. When inc is 1, the
rotation appears smoother than the default (i.e., 2). Increments greater than 2 are less smooth than the default. A negative increment (e.g., 2) rotates the colormap in a negative direction.
spinmap('inf') rotates the colormap for an infinite amount of time. To break
the loop, press Ctrl-C.
See Also
colormap, colormapeditor
"Color Operations" for related functions
2-379
spline
Purpose Syntax Description
2spline
Cubic spline data interpolation
yy = spline(x,y,xx) pp = spline(x,y) yy = spline(x,y,xx) uses cubic spline interpolation to find yy, the values of the underlying function y at the points in the vector xx. The vector x specifies the points at which the data y is given. If y is a matrix, then the data is taken to be vector-valued and interpolation is performed for each row of y. For this case, length(x) must equal size(y,2), and yy is size(y,1)-by-length(xx).
Note This is the opposite of the interp1(x,y,xx,'spline') function which performs the interpolation for each column of matrix y. For this function, length(x) must equal size(y,1), and the resulting yy is length(xx)-by-size(y,2).
pp = spline(x,y) returns the piecewise polynomial form of the cubic spline interpolant for later use with ppval and the spline utility unmkpp.
Ordinarily, the not-a-knot end conditions are used. However, if y contains two more values than x has entries, then the first and last value in y are used as the endslopes for the cubic spline. Namely:
f(x) = y(:,2:end-1), df(min(x)) = y(:,1), df(max(x)) = y(:,end)
Examples
Example 1. This generates a sine curve, then samples the spline over a finer
mesh.
x = 0:10; y = sin(x); xx = 0:.25:10; yy = spline(x,y,xx); plot(x,y,'o',xx,yy)
2-380
spline
1
0.8
0.6
0.4
0.2
0
-0.2
-0.4
-0.6
-0.8
-1
0
1
2
3
4
5
6
7
8
9
10
Example 2. This illustrates the use of clamped or complete spline interpolation
where end slopes are prescribed. Zero slopes at the ends of an interpolant to the values of a certain distribution are enforced.
x = -4:4; y = [0 .15 1.12 2.36 2.36 1.46 .49 .06 0]; cs = spline(x,[0 y 0]); xx = linspace(-4,4,101); plot(x,y,'o',xx,ppval(cs,xx),'-');
2-381
spline
3
2.5
2
1.5
1
0.5
0
-0.5 -4
-3
-2
-1
0
1
2
3
4
Example 3. The two vectors
t = 1900:10:1990; p = [ 75.995 91.972 150.697 179.323 105.711 203.212 123.203 226.505 131.669 ... 249.633 ];
represent the census years from 1900 to 1990 and the corresponding United States population in millions of people. The expression
spline(t,p,2000)
uses the cubic spline to extrapolate and predict the population in the year 2000. The result is
ans = 270.6060
Example 4. The statements
x = pi*[0:.5:2]; y = [0 1 0 -1 0 1 0 1 0 -1 pp = spline(x,y); 1 0 0; 1];
2-382
spline
yy = ppval(pp, linspace(0,2*pi,101)); plot(yy(1,:),yy(2,:),'-b',y(1,2:5),y(2,2:5),'or'), axis equal
generate the plot of a circle, with the five data points y(:,2),...,y(:,6) marked with o's. Note that this y contains two more values (i.e., two more columns) than does x, hence y(:,1) and y(:,end) are used as endslopes.
1
0.8
0.6
0.4
0.2
0
-0.2
-0.4
-0.6
-0.8
-1
-1
-0.5
0
0.5
1
Algorithm
A tridiagonal linear system (with, possibly, several right sides) is being solved for the information needed to describe the coefficients of the various cubic polynomials which make up the interpolating spline. spline uses the functions ppval, mkpp, and unmkpp. These routines form a small suite of functions for working with piecewise polynomials. For access to more advanced features, see the M-file help for these functions and the Spline Toolbox.
interp1, ppval, mkpp, unmkpp
See Also References
[1] de Boor, C., A Practical Guide to Splines, Springer-Verlag, 1978.
2-383
spones
Purpose Syntax Description Examples
2spones
Replace nonzero sparse matrix elements with ones
R = spones(S) R = spones(S) generates a matrix R with the same sparsity structure as S, but with 1's in the nonzero positions. c = sum(spones(S)) is the number of nonzeros in each column. r = sum(spones(S'))' is the number of nonzeros in each row. sum(c) and sum(r) are equal, and are equal to nnz(S).
See Also
nnz, spalloc, spfun
2-384
spparms
Purpose Syntax
2spparms
Set parameters for sparse matrix routines
spparms('key',value) spparms values = spparms [keys,values] = spparms spparms(values) value = spparms('key') spparms('default') spparms('tight') spparms('key',value) sets one or more of the tunable parameters used in the sparse routines, particularly the minimum degree orderings, colmmd and symmmd. In ordinary use, you should never need to deal with this function.
Description
The meanings of the key parameters are
'spumoni'
Sparse Monitor flag:
0 1 2
Produces no diagnostic output, the default Produces information about choice of algorithm based on matrix structure, and about storage allocation Also produces very detailed information about the sparse matrix algorithms
'thr_rel', 'thr_abs' 'exact_d' 'supernd' 'rreduce' 'wh_frac' 'autommd'
Minimum degree threshold is
thr_rel*mindegree + thr_abs.
Nonzero to use exact degrees in minimum degree. Zero to use approximate degrees. If positive, minimum degree amalgamates the supernodes every supernd stages. If positive, minimum degree does row reduction every rreduce stages. Rows with density > wh_frac are ignored in colmmd. Nonzero to use minimum degree (MMD) orderings with Cholesky- and QR-based \ and /.
2-385
spparms
'autoamd' 'piv_tol' 'bandden'
Nonzero to use colamd ordering with the UMFPACK LU-based \ and /. Pivot tolerance used by the UMFPACK LU-based \ and /. Band density used by LAPACK-based \ and / for banded matrices. Band density is defined as (# nonzeros in the band)/(# nonzeros in a full band). If bandden = 1.0, never use band solver. If bandden = 0.0, always use band solver. Default is 0.5.
Note Cholesky-based \ and / on symmetric positive definite matrices use symmmd. LU-based \ and / (UMFPACK) on square matrices use a modified colamd. QR-based \ and / on rectangular matrices use colmmd.
spparms, by itself, prints a description of the current settings. values = spparms returns a vector whose components give the current
settings.
[keys,values] = spparms returns that vector, and also returns a character
matrix whose rows are the keywords for the parameters.
spparms(values), with no output argument, sets all the parameters to the
values specified by the argument vector.
value = spparms('key') returns the current setting of one parameter. spparms('default') sets all the parameters to their default settings. spparms('tight') sets the minimum degree ordering parameters to their
tight settings, which can lead to orderings with less fill-in, but which make the ordering functions themselves use more execution time. The key parameters for default and tight settings are
2-386
spparms
Keyword values(1) values(2) values(3) values(4) values(5) values(6) values(7) values(8) values(9) values(10) values(11) 'spumoni' 'thr_rel' 'thr_abs' 'exact_d' 'supernd' 'rreduce' 'wh_frac' 'autommd' 'autoamd' 'piv_tol' 'bandden'
Default
Tight
0.0 1.1 1.0 0.0 3.0 3.0 0.5 1.0 1.0 0.1 0.5 1.0 0.0 1.0 1.0 1.0 0.5
Notes
Sparse A\b on symmetric positive definite A uses symmmd and chol. Sparse A\b on general square A uses UMFPACK and its modified colamd reordering. colamd does not used the parameters above, other than 'autoamd' which turns the preordering on or off, and 'piv_tol' which controls the pivot tolerance. UMFPACK also responds to 'spumoni', as do the majority of the built-in sparse matrix functions.
See Also References
\, chol, colamd, colmmd, symmmd
[1] Gilbert, John R., Cleve Moler, and Robert Schreiber, "Sparse Matrices in MATLAB: Design and Implementation," SIAM Journal on Matrix Analysis and Applications, Vol. 13, 1992, pp. 333-356. [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-387
sprand
Purpose Syntax
2sprand
Sparse uniformly distributed random matrix
R = sprand(S) R = sprand(m,n,density) R = sprand(m,n,density,rc) R = sprand(S) has the same sparsity structure as S, but uniformly distributed random entries. R = sprand(m,n,density) is a random, m-by-n, sparse matrix with approximately density*m*n uniformly distributed nonzero entries (0 <= density <= 1). R = sprand(m,n,density,rc) also has reciprocal condition number approximately equal to rc. R is constructed from a sum of matrices of rank one.
Description
If rc is a vector of length lr, where lr <= min(m,n), then R has rc as its first lr singular values, all others are zero. In this case, R is generated by random plane rotations applied to a diagonal matrix with the given singular values. It has a great deal of topological and algebraic structure.
See Also
sprandn, sprandsym
2-388
sprandn
Purpose Syntax
2sprandn
Sparse normally distributed random matrix
R = sprandn(S) R = sprandn(m,n,density) R = sprandn(m,n,density,rc) R = sprandn(S) has the same sparsity structure as S, but normally distributed random entries with mean 0 and variance 1. R = sprandn(m,n,density) is a random, m-by-n, sparse matrix with approximately density*m*n normally distributed nonzero entries (0 <= density <= 1). R = sprandn(m,n,density,rc) also has reciprocal condition number approximately equal to rc. R is constructed from a sum of matrices of rank one.
Description
If rc is a vector of length lr, where lr <= min(m,n), then R has rc as its first lr singular values, all others are zero. In this case, R is generated by random plane rotations applied to a diagonal matrix with the given singular values. It has a great deal of topological and algebraic structure.
See Also
sprand, sprandsym
2-389
sprandsym
Purpose Syntax
2sprandsym
Sparse symmetric random matrix
R R R R = = = = sprandsym(S) sprandsym(n,density) sprandsym(n,density,rc) sprandsym(n,density,rc,kind)
Description
R = sprandsym(S) returns a symmetric random matrix whose lower triangle and diagonal have the same structure as S. Its elements are normally distributed, with mean 0 and variance 1. R = sprandsym(n,density) returns a symmetric random, n-by-n, sparse matrix with approximately density*n*n nonzeros; each entry is the sum of one or more normally distributed random samples, and (0 <= density <= 1). R = sprandsym(n,density,rc) returns a matrix with a reciprocal condition number equal to rc. The distribution of entries is nonuniform; it is roughly
symmetric about 0; all are in [ 1, 1 ] . If rc is a vector of length n, then R has eigenvalues rc. Thus, if rc is a positive (nonnegative) vector then R is a positive definite matrix. In either case, R is generated by random Jacobi rotations applied to a diagonal matrix with the given eigenvalues or condition number. It has a great deal of topological and algebraic structure.
R = sprandsym(n,density,rc,kind) returns a positive definite matrix. Argument kind can be:
1 to generate R by random Jacobi rotation of a positive definite diagonal matrix. R has the desired condition number exactly. 2 to generate an R that is a shifted sum of outer products. R has the desired condition number only approximately, but has less structure. 3 to generate an R that has the same structure as the matrix S and approximate condition number 1/rc. density is ignored.
See Also
sprand, sprandn
2-390
sprank
Purpose Syntax Description
2sprank
Structural rank
r = sprank(A) r = sprank(A) is the structural rank of the sparse matrix A. Also known as
maximum traversal, maximum assignment, and size of a maximum matching in the bipartite graph of A. Always sprank(A) >= rank(full(A)), and in exact arithmetic sprank(A) == rank(full(sprandn(A))) with probability one.
Examples
A = [1 2
0 0
2 4
0 0 ];
A = sparse(A); sprank(A) ans = 2 rank(full(A)) ans = 1
See Also
dmperm
2-391
sprintf
Purpose Syntax Description
2sprintf
Write formatted data to a string
[s,errmsg] = sprintf(format,A,...) [s,errmsg] = sprintf(format,A,...) formats the data in matrix A (and in any additional matrix arguments) under control of the specified format string, and returns it in the MATLAB string variable s. The sprintf function returns an error message string errmsg if an error occurred. errmsg is an empty matrix
if no error occurred.
sprintf is the same as fprintf except that it returns the data in a MATLAB
string variable rather than writing it to a file.
Format String
The format argument is a string containing C language conversion specifications. A conversion specification controls the notation, alignment, significant digits, field width, and other aspects of output format. The format string can contain escape characters to represent non-printing characters such as newline characters and tabs. Conversion specifications begin with the % character and contain these optional and required elements: Flags (optional) Width and precision fields (optional) A subtype specifier (optional) Conversion character (required) You specify these elements in the following order:
Start of conversion specification Flags Field width Precision
%12.5e
Conversion character
2-392
sprintf
Flags
You can control the alignment of the output using any of these optional flags.
Character Description Example %5.2d
A minus sign () A plus sign (+) Zero (0)
Left-justifies the converted argument in its field. Always prints a sign character (+ or ). Pad with zeros rather than spaces.
%+5.2d %05.2d
Field Width and Precision Specifications
You can control the width and precision of the output by including these options in the format string.
Character Description Example %6f
Field width Precision
A digit string specifying the minimum number of digits to be printed. A digit string including a period (.) specifying the number of digits to be printed to the right of the decimal point.
%6.2f
Conversion Characters
Conversion characters specify the notation of the output.
Specifier %c %d %e Description
Single character Decimal notation (signed) Exponential notation (using a lowercase e as in 3.1415e+00) Exponential notation (using an uppercase E as in 3.1415E+00)
%E
2-393
sprintf
Specifier %f %g
Description
Fixed-point notation The more compact of %e or %f, as defined in [2]. Insignificant zeros do not print. Same as %g, but using an uppercase E Octal notation (unsigned) String of characters Decimal notation (unsigned) Hexadecimal notation (using lowercase letters af) Hexadecimal notation (using uppercase letters AF)
%G %o %s %u %x %X
The following tables describe the nonalphanumeric characters found in format specification strings.
Escape Characters
This table lists the escape character sequences you use to specify non-printing characters in a format specification.
Character \b \f \n \r \t \\ Description
Backspace Form feed New line Carriage return Horizontal tab Backslash
2-394
sprintf
Character
Description
\'' or '' (two single quotes)
%%
Single quotation mark
Percent character
Remarks
The sprintf function behaves like its ANSI C language namesake with these exceptions and extensions. If you use sprintf to convert a MATLAB double into an integer, and the double contains a value that cannot be represented as an integer (for example, it contains a fraction), MATLAB ignores the specified conversion and outputs the value in exponential format. To successfully perform this conversion, use the fix, floor, ceil, or round functions to change the value in the double into a value that can be represented as an integer before passing it to sprintf. The following, non-standard subtype specifiers are supported for the conversion characters %o, %u, %x, and %X.
b
The underlying C data type is a double rather than an unsigned integer. For example, to print a double-precision value in hexadecimal, use a format like '%bx'. The underlying C data type is a float rather than an unsigned integer.
t
For example, to print a double value in hexadecimal use the format '%bx' The sprintf function is vectorized for nonscalar arguments. The function recycles the format string through the elements of A (columnwise) until all the elements are used up. The function then continues in a similar manner through any additional matrix arguments. If %s is used to print part of a nonscalar double argument, the following behavior occurs:
a. Successive values are printed as long as they are integers and in the range
of a valid character. The first invalid character terminates the printing for
2-395
sprintf
this %s specifier and is used for a later specifier. For example, pi terminates the string below and is printed using %f format.
Str = [65 66 67 pi]; sprintf('%s %f', Str) ans = ABC 3.141593 b. If the first value to print is not a valid character, then just that value is printed for this %s specifier using an e conversion as a warning to the user. For example, pi is formatted by %s below in exponential notation, and 65, though representing a valid character, is formatted as fixed-point (%f). Str = [pi 65 66 67]; sprintf('%s %f %s', Str) ans = 3.141593e+000 65.000000 BC c. One exception is zero which is a valid character. If zero is found first, %s
prints nothing and the value is skipped. If zero is found after at least one valid character, it terminates the printing for this %s specifier and is used for a later specifier. sprintf prints negative zero and exponents differently on some platforms, as shown in the following tables.
Negative Zero Printed with %e, %E, %f, %g, or %G Display of Negative Zero Platform %e or %E %f %g or %G
PC SGI HP700 Others
0.000000e+000 0.000000e+00 -0.000000e+00 -0.000000e+00
0.000000 0.000000 -0.000000 -0.000000
0 0 0 -0
2-396
sprintf
Exponents Printed with %e, %E, %g, or %G Platform Minimum Digits in Exponent Example 1.23e+004 1.23e+04
PC UNIX
3 2
You can resolve this difference in exponents by post-processing the results of sprintf. For example, to make the PC output look like that of UNIX, use
a = sprintf('%e', 12345.678); if ispc, a = strrep(a, 'e+0', 'e+'); end
Examples
Command sprintf('%0.5g',(1+sqrt(5))/2) sprintf('%0.5g',1/eps) sprintf('%15.5f',1/eps) sprintf('%d',round(pi)) sprintf('%s','hello') sprintf('The array is %dx%d.',2,3) sprintf('\n') Result 1.618 4.5036e+15 4503599627370496.00000 3 hello The array is 2x3
Line termination character on all platforms
See Also References
int2str, num2str, sscanf
[1] Kernighan, B.W. and D.M. Ritchie, The C Programming Language, Second Edition, Prentice-Hall, Inc., 1988. [2] ANSI specification X3.159-1989: "Programming Language C," ANSI, 1430 Broadway, New York, NY 10018.
2-397
spy
Purpose Syntax
2spy
Visualize sparsity pattern
spy(S) spy(S,markersize) spy(S,'LineSpec') spy(S,'LineSpec',markersize) spy(S) plots the sparsity pattern of any matrix S. spy(S,markersize), where markersize is an integer, plots the sparsity
Description
pattern using markers of the specified point size.
spy(S,'LineSpec'), where LineSpec is a string, uses the specified plot marker
type and color.
spy(S,'LineSpec',markersize) uses the specified type, color, and size for the
plot markers.
S is usually a sparse matrix, but full matrices are acceptable, in which case the
locations of the nonzero elements are plotted.
Note spy replaces format +, which takes much more space to display essentially the same information.
Examples
This example plots the 60-by-60 sparse adjacency matrix of the connectivity graph of the Buckminster Fuller geodesic dome. This matrix also represents the soccer ball and the carbon-60 molecule.
B = bucky; spy(B)
2-398
spy
0
10
20
30
40
50
60 0
10
20
30 nz = 180
40
50
60
See Also
find, gplot, LineSpec, symamd, symmmd, symrcm
2-399
sqrt
Purpose Syntax Description Remarks Examples
2sqrt
Square root
B = sqrt(X) B = sqrt(X) returns the square root of each element of the array X. For the elements of X that are negative or complex, sqrt(X) produces complex results.
See sqrtm for the matrix square root.
sqrt((-2:2)') ans = 0 + 1.4142i 0 + 1.0000i 0 1.0000 1.4142 sqrtm
See Also
2-400
sqrtm
Purpose Syntax
2sqrtm
Matrix square root
X = sqrtm(A) [X,resnorm] = sqrtm(A) [X,alpha,condest] = sqrtm(A) X = sqrtm(A) is the principal square root of the matrix A, i.e. X*X = A. X is the unique square root for which every eigenvalue has nonnegative real part. If A has any eigenvalues with negative real parts then a complex result is produced. If A is singular then A may not have a square root. A warning is
Description
printed if exact singularity is detected.
[X, resnorm] = sqrtm(A) does not print any warning, and returns the residual, norm(A-X^2,'fro')/norm(A,'fro'). [X, alpha, condest] = sqrtm(A) returns a stability factor alpha and an estimate condest of the matrix square root condition number of X. The residual norm(A-X^2,'fro')/norm(A,'fro') is bounded approximately by n*alpha*eps and the Frobenius norm relative error in X is bounded approximately by n*alpha*condest*eps, where n = max(size(A)).
Remarks
If X is real, symmetric and positive definite, or complex, Hermitian and positive definite, then so is the computed matrix square root. Some matrices, like X = [0 1; 0 0], do not have any square roots, real or complex, and sqrtm cannot be expected to produce one.
Examples
Example 1. A matrix representation of the fourth difference operator is
X = 5 -4 1 0 0 -4 6 -4 1 0 1 -4 6 -4 1 0 1 -4 6 -4 0 0 1 -4 5
This matrix is symmetric and positive definite. Its unique positive definite square root, Y = sqrtm(X), is a representation of the second difference operator.
2-401
sqrtm
Y = 2 -1 0 -0 -0 -1 2 -1 0 -0 -0 -1 2 -1 -0 -0 0 -1 2 -1 -0 -0 0 -1 2
Example 2. The matrix
X = 7 15 10 22
has four square roots. Two of them are
Y1 = 1.5667 2.6112 1.7408 4.1779
and
Y2 = 1 3 2 4
The other two are -Y1 and -Y2. All four can be obtained from the eigenvalues and vectors of X.
[V,D] = eig(X); D = 0.1386 0 0 28.8614
The four square roots of the diagonal matrix D result from the four choices of sign in
S = 0.3723 0 0 5.3723
All four Ys are of the form
Y = V*S/V
2-402
sqrtm
The sqrtm function chooses the two plus signs and produces Y1, even though Y2 is more natural because its entries are integers.
See Also
expm, funm, logm
2-403
squeeze
Purpose Syntax Description
2squeeze
Remove singleton dimensions
B = squeeze(A) B = squeeze(A) returns an array B with the same elements as A, but with all
singleton dimensions removed. A singleton dimension is any dimension for which size(A,dim) = 1.
Examples
Consider the 2-by-1-by-3 array Y = rand(2,1,3). This array has a singleton column dimension -- that is, there's only one column per page.
Y = Y(:,:,1) = 0.5194 0.8310 Y(:,:,3) = 0.5297 0.6711 Y(:,:,2) = 0.0346 0.0535
The command Z = squeeze(Y) yields a 2-by-3 matrix:
Z = 0.5194 0.8310 0.0346 0.0535 0.5297 0.6711
See Also
reshape, shiftdim
2-404
sscanf
Purpose Syntax
2sscanf
Read string under format control
A = sscanf(s,format) A = sscanf(s,format,size) [A,count,errmsg,nextindex] = sscanf(...) A = sscanf(s,format) reads data from the MATLAB string variable s, converts it according to the specified format string, and returns it in matrix A. format is a string specifying the format of the data to be read. See "Remarks" for details. sscanf is the same as fscanf except that it reads the data from a
Description
MATLAB string variable rather than reading it from a file.
A = sscanf(s,format,size) reads the amount of data specified by size and converts it according to the specified format string. size is an argument that determines how much data is read. Valid options are
n inf
Read n elements into a column vector. Read to the end of the file, resulting in a column vector containing the same number of elements as are in the file. Read enough elements to fill an m-by-n matrix, filling the matrix in column order. n can be Inf, but not m.
[m,n]
If the matrix A results from using character conversions only and size is not of the form [M,N], a row vector is returned.
sscanf differs from its C language namesakes scanf() and fscanf() in an
important respect -- it is vectorized in order to return a matrix argument. The format string is cycled through the file until an end-of-file is reached or the amount of data specified by size is read in.
[A,count,errmsg,nextindex] = sscanf(...) reads data from the MATLAB string variable s, converts it according to the specified format string, and returns it in matrix A. count is an optional output argument that returns the number of elements successfully read. errmsg is an optional output argument
that returns an error message string if an error occurred or an empty matrix if an error did not occur. nextindex is an optional output argument specifying one more than the number of characters scanned in s.
2-405
sscanf
Remarks
When MATLAB reads a specified file, it attempts to match the data in the file to the format string. If a match occurs, the data is written into the matrix in column order. If a partial match occurs, only the matching data is written to the matrix, and the read operation stops. The format string consists of ordinary characters and/or conversion specifications. Conversion specifications indicate the type of data to be matched and involve the character %, optional width fields, and conversion characters, organized as shown below: %12.5e }
Initial % characte r Conversion character
Flag
Field width and precision
Add one or more of these characters between the % and the conversion character. An asterisk (*) A digit string A letter Skip over the matched value if the value is matched but not stored in the output matrix. Maximum field width. The size of the receiving object; for example, h for short as in %hd for a short integer, or l for long as in %ld for a long integer or %lg for a double floating-point number.
Valid conversion characters are as shown.
%c %d %e, %f, %g %i %o %s
Sequence of characters; number specified by field width Decimal numbers Floating-point numbers Signed integer Signed octal integer A series of non-whitespace characters
2-406
sscanf
%u %x [...]
Signed decimal integer Signed hexadecimal integer Sequence of characters (scanlist)
If %s is used, an element read may use several MATLAB matrix elements, each holding one character. Use %c to read space characters, or %s to skip all white space. Mixing character and numeric conversion specifications cause the resulting matrix to be numeric and any characters read to appear as their ASCII values, one character per MATLAB matrix element. For more information about format strings, refer to the scanf() and fscanf() routines in a C language reference manual.
Examples
The statements
s = '2.7183 3.1416'; A = sscanf(s,'%f')
create a two-element vector containing poor approximations to e and pi.
See Also
eval, sprintf, textread
2-407
stairs
Purpose Syntax
2stairs
Stairstep plot
stairs(Y) stairs(X,Y) stairs(...,LineSpec) [xb,yb] = stairs(Y) [xb,yb] = stairs(X,Y)
Description
Stairstep plots are useful for drawing time-history plots of digitally sampled data systems.
stairs(Y) draws a stairstep plot of the elements of Y. When Y is a vector, the x-axis scale ranges from 1 to size(Y). When Y is a matrix, the x-axis scale ranges from 1 to the number of rows in Y. stairs(X,Y) plots X versus the columns of Y. X and Y are vectors of the same size or matrices of the same size. Additionally, X can be a row or a column vector, and Y a matrix with length(X) rows. stairs(...,LineSpec) specifies a line style, marker symbol, and color for the plot (see LineSpec for more information). [xb,yb] = stairs(Y) and [xb,yb] = stairs(x,Y) do not draw graphs, but return vectors xb and yb such that plot(xb,yb) plots the stairstep graph.
Examples
Create a stairstep plot of a sine wave.
x = 0:.25:10; stairs(x,sin(x))
2-408
stairs
1 0.8 0.6 0.4 0.2 0 -0.2 -0.4 -0.6 -0.8 -1 0 2 4 6 8 10
See Also
bar, hist
"Discrete Data Plots" for related functions
2-409
start
Purpose Syntax Description
2start
Start timer(s) running
start(obj) start(obj) starts the timer running, represented by the timer object, obj. If obj is an array of timer objects, start starts all the timers. Use the timer
function to create a timer object.
start sets the Running property of the timer object, obj, to 'on', initiates TimerFcn callbacks, and executes the StartFcn callback.
The timer stops running if one of the following conditions apply: The number of TimerFcn callbacks specified in TasksToExecute have been executed. The stop(obj) command is issued. An error occurred while executing a TimerFcn callback.
See Also
timer, stop
2-410
startat
Purpose Syntax
2startat
Start timer(s) running at the specified time
startat(obj,time) startat(obj,S) startat(obj,S,pivotyear) startat(obj,Y,M,D) startat(obj,[Y,M,D]) startat(obj,Y,M,D,H,MI,S) startat(obj,[Y,M,D,H,MI,S]) startat(obj,time) starts the timer running, represented by the timer object obj, at the time specified by the serial date number time. If obj is an array of timer objects, startat starts all the timers running at the specified time. Use the timer function to create the timer object. startat sets the Running property of the timer object, obj, to 'on', initiates TimerFcn callbacks, and executes the StartFcn callback.
Description
The serial date number, time, indicates the number of days that have elapsed since 1-Jan-0000 (starting at 1). See datenum for additional information about serial date numbers.
startat(obj,S) starts the timer running at the time specified by the date string S. The date string must use date format 0, 1, 2, 6, 13, 14, 15, 16, or 23, as defined by the datestr function. Date strings with two-character years are
interpreted to be within the 100 years centered around the current year.
startat(obj,S,pivotyear) 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. startat(obj,Y,M,D) startat(obj,[Y,M,D]) start the timer at the year (Y), month (M), and day (D) specified. Y, M, and D must be arrays of the same size (or they can be a scalar). startat(obj,Y,M,D,H,MI,S) startat(obj,[Y,M,D,H,MI,S]) start the timer at the year (Y), month (M), day(D), hour(H), minute(MI), and second(S) specified. Y, M, D, H, MI, and S must
be arrays of the same size (or they can be a scalar). Values outside the normal range of each array are automatically carried to the next unit (for example
2-411
startat
month values greater than 12 are carried to years). Month values less than 1 are set to be 1; all other units can wrap and have valid negative values. The timer stops running if one of the following conditions apply: The number of TimerFcn callbacks specified in TasksToExecute have been executed. The stop(obj) command is issued. An error occurred while executing a TimerFcn callback.
Example
This example uses a timer object to execute a function at a specified time.
t1=timer('TimerFcn','disp(''it is 10 o''''clock'')'); startat(t1,'10:00:00');
This example uses a timer to display a message when an hour has elapsed.
t2=timer('TimerFcn','disp(''It has been an hour now.'')'); startat(t2,now+1/24);
See Also
datenum, datestr, now, timer, start, stop
2-412
std
Purpose Syntax
2std
Standard deviation
s = std(X) s = std(X,flag) s = std(X,flag,dim)
Definition
There are two common textbook definitions for the standard deviation s of a data vector X. 1 n (1) s = -----------( x i x ) 2 n 1i = 1
1 -2
1 (2) s = -n where 1 x = -n
( xi
i=1
n
2 x )2
1 --
xi
i=1
n
and n is the number of elements in the sample. The two forms of the equation differ only in n 1 versus n in the divisor.
Description
s = std(X), where X is a vector, returns the standard deviation using (1) 2 above. If X is a random sample of data from a normal distribution, s is the best
unbiased estimate of its variance. If X is a matrix, std(X) returns a row vector containing the standard deviation of the elements of each column of X. If X is a multidimensional array, std(X) is the standard deviation of th elements along the first nonsingleton dimension of X.
s = std(X,flag) for flag = 0, is the same as std(X). For flag = 1, std(X,1)
returns the standard deviation using (2) above, producing the second moment of the sample about its mean.
2-413
std
s = std(X,flag,dim) computes the standard deviations along the dimension of X specified by scalar dim.
Examples
For matrix X
X = 1 7 5 15 9 22
s = std(X,0,1) s = 4.2426 7.0711 s = std(X,0,2) s = 4.000 7.5056
9.1924
See Also
corrcoef, cov, mean, median
2-414
stem
Purpose Syntax
2stem
Plot discrete sequence data
stem(Y) stem(X,Y) stem(...,'fill') stem(...,LineSpec) h = stem(...)
Description
A two-dimensional stem plot displays data as lines extending from a baseline along the x-axis. A circle (the default) or other marker whose y-position represents the data value terminates each stem.
stem(Y) plots the data sequence Y as stems that extend from equally spaced and automatically generated values along the x-axis. When Y is a matrix, stem
plots all elements in a row against the same x value.
stem(X,Y) plots X versus the columns of Y. X and Y are vectors or matrices of the same size. Additionally, X can be a row or a column vector and Y a matrix with length(X) rows. stem(...,'fill') specifies whether to color the circle at the end of the stem. stem(...,LineSpec) specifies the line style, marker symbol, and color for the stem and top marker (the base line is not affected). See LineSpec for more
information.
h = stem(...) returns handles to three line graphics objects:
h(1) the marker symbol at the top of each stem h(2) the stem line h(3) the base line
Examples
Create a stem plot of a circular function.
y = linspace(0,2*pi,10); h = stem(cos(y),'fill','-.'); set(h(3),'Color','r','LineWidth',2) % Set base line properties axis ([0 11 -1 1])
2-415
stem
1
0.8
0.6
0.4
0.2
0
-0.2
-0.4
-0.6
-0.8
-1
0
1
2
3
4
5
6
7
8
9
10
11
See Also
bar, plot, stairs, stem3
"Discrete Data Plots" for related functions. See Two Dimensional Stem Plots for more examples using the stem function.
2-416
stem3
Purpose Syntax
2stem3
Plot three-dimensional discrete sequence data
stem3(Z) stem3(X,Y,Z) stem3(...,'fill') stem3(...,LineSpec) h = stem3(...)
Description
Three-dimensional stem plots display lines extending from the xy-plane. A circle (the default) or other marker symbol whose z-position represents the data value terminates each stem.
stem3(Z) plots the data sequence Z as stems that extend from the xy-plane. x and y are generated automatically. When Z is a row vector, stem3 plots all elements at equally spaced x values against the same y value. When Z is a column vector, stem3 plots all elements at equally spaced y values against the
same x value.
stem3(X,Y,Z) plots the data sequence Z at values specified by X and Y. X, Y, and Z must all be vectors or matrices of the same size. stem3(...,'fill') specifies whether to color the interior of the circle at the
end of the stem.
stem3(...,LineSpec) specifies the line style, marker symbol, and color for the stems. See LineSpec for more information. h = stem3(...) returns handles to line graphics objects.
Examples
Create a three-dimensional stem plot to visualize a function of two variables.
X = linspace(0,1,10); Y = X./2; Z = sin(X) + cos(Y); stem3(X,Y,Z,'fill') view(-25,30)
2-417
stem3
:
2 1.5 1 0.5 0 0.5 0.4 0.3 0.2 0.1 0 0 0.2 0.4 0.6 0.8 1
See Also
bar, plot, stairs, stem
"Discrete Data Plots" for related functions See Three-Dimensional Stem Plots for more examples
2-418
stop
Purpose Syntax Description
2stop
Stop timer(s)
stop(obj) stop(obj) stops the timer, represented by the timer object, obj. If obj is an array of timer objects, the stop function stops them all. Use the timer function
to create a timer object. The stop function sets the Running property of the timer object, obj, to 'off', halts further TimerFcn callbacks, and executes the StopFcn callback.
See Also
timer, start
2-419
stopasync
Purpose Syntax Arguments Description Remarks
2stopasync
Stop asynchronous read and write operations
stopasync(obj) obj
A serial port object or an array of serial port objects.
stopasync(obj) stops any asynchronous read or write operation that is in progress for obj.
You can write data asynchronously using the fprintf or fwrite functions. You can read data asynchronously using the readasync function, or by configuring the ReadAsyncMode property to continuous. In-progress asynchronous operations are indicated by the TransferStatus property. If obj is an array of serial port objects and one of the objects cannot be stopped, the remaining objects in the array are stopped and a warning is returned. After an object stops: Its TransferStatus property is configured to idle. Its ReadAsyncMode property is configured to manual. The data in its output buffer is flushed. Data in the input buffer is not flushed. You can return this data to the MATLAB workspace using any of the synchronous read functions. If you execute the readasync function, or configure the ReadAsyncMode property to continuous, then the new data is appended to the existing data in the input buffer.
See Also
Functions
fprintf, fwrite, readasync
Properties
ReadAsyncMode, TransferStatus
2-420
str2double
Purpose Syntax Description
2str2double
Convert string to double-precision value
x = str2double('str') X = str2double(C) X = str2double('str') converts the string str, which should be an ASCII
character representation of a real or complex scalar value, to the MATLAB double-precision representation. The string may contain digits, a comma (thousands separator), a decimal point, a leading + or - sign, an e preceeding a power of 10 scale factor, and an i for a complex unit. If str does not represent a valid scalar value, str2double returns NaN.
X = str2double(C) converts the strings in the cell array of strings C to double-precision. The matrix X returned will be the same size as C.
Examples
Here are some valid str2double conversions.
str2double('123.45e7') str2double('123 + 45i') str2double('3.14159') str2double('2.7i - 3.14') str2double({'2.71' '3.1415'}) str2double('1,200.34')
See Also
char, hex2num, num2str, str2num
2-421
str2func
Purpose Syntax Description
2str2func
Constructs a function handle from a function name string
fhandle = str2func('str') str2func('str') constructs a function handle, fhandle, for the function named in the string, 'str'.
You can create a function handle using either the @function syntax or the str2func command. You can also perform this operation on a cell array of strings. In this case, an array of function handles is returned.
Examples
To create a function handle from the function name, 'humps'
fhandle = str2func('humps') fhandle = @humps
To create an array of function handles from a cell array of function names
fh_array = str2func({'sin' 'cos' 'tan'}) fh_array = @sin @cos @tan
See Also
function_handle, func2str, functions
2-422
str2mat
Purpose Syntax Description
2str2mat
Form a blank padded character matrix from strings
S = str2mat(T1,T2,T3,..) S = str2mat(T1,T2,T3,..) forms the matrix S containing the text strings T1,T2,T3,... as rows. The function automatically pads each string with
blanks in order to form a valid matrix. Each text parameter, Ti, can itself be a string matrix. This allows the creation of arbitrarily large string matrices. Empty strings are significant.
Note This routine will become obsolete in a future version. Use char instead.
Remarks Examples
str2mat differs from strvcat in that empty strings produce blank rows in the output. In strvcat, empty strings are ignored. x = str2mat('36842','39751','38453','90307'); whos x Name x x(2,3) ans = 7
Size 4x5
Bytes 40
Class char array
See Also
char, strvcat
2-423
str2num
Purpose Syntax Description
2str2num
String to number conversion
x = str2num('str') x = str2num('str') converts the string str, which is an ASCII character representation of a numeric value, to numeric representation. The string can contain:
Digits A decimal point A leading + or - sign A letter e or d preceding a power of 10 scale factor A letter i or j indicating a complex or imaginary number. The str2num function can also convert string matrices.
Examples
str2num('3.14159e0') is approximately .
To convert a string matrix:
str2num(['1 2';'3 4']) ans = 1 3 2 4
See Also
num2str, hex2num, sscanf, sparse, special characters
2-424
strcat
Purpose Syntax Description
2strcat
String concatenation
t = strcat(s1,s2,s3,...) t = strcat(s1,s2,s3,...) horizontally concatenates corresponding rows of the character arrays s1, s2, s3, etc. All input arrays must have the same number of rows (or any can be a single string). When the inputs are all character arrays, the output is also a character array.
When any of the inputs is a cell array of strings, strcat returns a cell array of strings formed by concatenating corresponding elements of s1, s2, etc. The inputs must all have the same size (or any can be a scalar). Any of the inputs can also be character arrays. Trailing spaces in character array inputs are ignored and do not appear in the output. This is not true for inputs that are cell arrays of strings. Use the concatenation syntax [s1 s2 s3 ...] to preserve trailing spaces.
Remarks
strcat and matrix operation are different for strings that contain trailing
spaces:
a = 'hello ' b = 'goodbye' strcat(a,b) ans = hellogoodbye [a b] ans = hello goodbye
Examples
Given two 1-by-2 cell arrays a and b,
a = 'abcde' 'fghi' b = 'jkl' 'mn'
the command t = strcat(a,b) yields:
t = 'abcdejkl' 'fghimn'
Given the 1-by-1 cell array c = {`Q'}, the command t = strcat(a,b,c) yields:
2-425
strcat
t = 'abcdejklQ' 'fghimnQ'
See Also
strvcat, cat, cellstr
2-426
strcmp
Purpose Syntax Description
2strcmp
Compare strings
k = strcmp('str1','str2') TF = strcmp(S,T) k = strcmp('str1','str2') compares the strings str1 and str2 and returns logical true (1) if the two are identical, and logical false (0) otherwise. TF = strcmp(S,T) where either S or T is a cell array of strings, returns an array TF the same size as S and T containing 1 for those elements of S and T that match, and 0 otherwise. S and T must be the same size (or one can be a scalar cell). Either one can also be a character array with the right number of rows.
Remarks
Note that the value returned by strcmp is not the same as the C language convention. In addition, the strcmp function is case sensitive; any leading and trailing blanks in either of the strings are explicitly included in the comparison.
strcmp is intended for comparison of character data. When used to compare numeric data, strcmp returns 0.
Examples
strcmp('Yes','No') = 0 strcmp('Yes','Yes') = 1 A = 'MATLAB' 'Toolboxes' B = 'Handle Graphics' 'Toolboxes' C = 'Signal Processing' 'MATLAB' strcmp(A,B) ans = 0 0 'Image Processing' 'SIMULINK' 'Real Time Workshop' 'The MathWorks' 'SIMULINK' 'The MathWorks'
2-427
strcmp
1
1
strcmp(A,C) ans = 0 0 0 0
See Also
strcmpi, strncmp, strncmpi, strmatch, strfind, findstr, regexp, regexpi, regexprep
2-428
strcmpi
Purpose Syntax Description
2strcmpi
Compare strings ignoring case
strcmpi(str1,str2) strcmpi(S,T) strcmpi(str1,str2) returns 1 if strings str1 and str2 are the same except
for case and 0 otherwise.
strcmpi(S,T) when either S or T is a cell array of strings, returns an array the same size as S and T containing 1 for those elements of S and T that match except for case, and 0 otherwise. S and T must be the same size (or one can be a scalar cell). Either one can also be a character array with the right number of rows.
Remarks
strcmpi is intended for comparison of character data. When used to compare numeric data, strcmpi returns 0. strcmpi supports international character sets.
See Also
strcmp, strncmpi, strncmp, strmatch, strfind, findstr, regexp, regexpi, regexprep
2-429
stream2
Purpose Syntax
2stream2
Compute 2-D stream line data
XY = stream2(x,y,u,v,startx,starty) XY = stream2(u,v,startx,starty) XY = stream2(...,options) XY = stream2(x,y,u,v,startx,starty) computes stream lines from vector data u and v. The arrays x and y define the coordinates for u and v and must be monotonic and 2-D plaid (such as the data produced by meshgrid). startx and starty define the starting positions of the stream lines. The section "Starting
Description
Points for Stream Plots" in Visualization Techniques provides more information on defining starting points. The returned value XY contains a cell array of vertex arrays.
XY = stream2(u,v,startx,starty) assumes the arrays x and y are defined as [x,y] = meshgrid(1:n,1:m) where [m,n] = size(u). XY = stream2(...,options) specifies the options used when creating the stream lines. Define options as a one or two element vector containing the step
size or the step size and the maximum number of vertices in a stream line:
[stepsize]
or
[stepsize, max_number_vertices]
If you do not specify a value, MATLAB uses the default: stepsize = 0.1 (one tenth of a cell) maximum number of vertices = 10000 Use the streamline command to plot the data returned by stream2.
Examples
This example draws 2-D stream lines from data representing air currents over regions of North America.
load wind [sx,sy] = meshgrid(80,20:10:50); streamline(stream2(x(:,:,5),y(:,:,5),u(:,:,5),v(:,:,5),sx,sy));
2-430
stream2
See Also
coneplot, stream3, streamline
"Volume Visualization" for related functions Specifying Starting Points for Stream Plots for related information
2-431
stream3
Purpose Syntax Description
2stream3
Compute 3-D stream line data
XYZ = stream3(X,Y,Z,U,V,W,startx,starty,startz) XYZ = stream3(U,V,W,startx,starty,startz) XYZ = stream3(X,Y,Z,U,V,W,startx,starty,startz) computes stream lines from vector data U, V, W. The arrays X, Y, Z define the coordinates for U, V, W and must be monotonic and 3-D plaid (such as the data produced by meshgrid). startx, starty, and startz define the starting positions of the stream lines. The section "Starting Points for Stream Plots" in Visualization Techniques provides more information on defining starting points.
The returned value XYZ contains a cell array of vertex arrays.
XYZ = stream3(U,V,W,startx,starty,startz) assumes the arrays X, Y, and Z are defined as [X,Y,Z] = meshgrid(1:N,1:M,1:P) where [M,N,P] = size(U). XYZ = stream3(...,options) specifies the options used when creating the stream lines. Define options as a one or two element vector containing the step
size or the step size and the maximum number of vertices in a stream line:
[stepsize]
or
[stepsize, max_number_vertices]
If you do not specify values, MATLAB uses the default: stepsize = 0.1 (one tenth of a cell) maximum number of vertices = 10000 Use the streamline command to plot the data returned by stream3.
Examples
This example draws 3-D stream lines from data representing air currents over regions of North America.
load wind [sx sy sz] = meshgrid(80,20:10:50,0:5:15); streamline(stream3(x,y,z,u,v,w,sx,sy,sz)) view(3)
2-432
stream3
See Also
coneplot, stream2, streamline
"Volume Visualization" for related functions Specifying Starting Points for Stream Plots for related information
2-433
streamline
Purpose Syntax
2streamline
Draw stream lines from 2-D or 3-D vector data
h h h h h h h = = = = = = = streamline(X,Y,Z,U,V,W,startx,starty,startz) streamline(U,V,W,startx,starty,startz) streamline(XYZ) streamline(X,Y,U,V,startx,starty) streamline(U,V,startx,starty) streamline(XY) streamline(...,options)
Description
h = streamline(X,Y,Z,U,V,W,startx,starty,startz) draws stream lines from 3-D vector data U, V, W. The arrays X, Y, Z define the coordinates for U, V, W and must be monotonic and 3-D plaid (such as the data produced by meshgrid). startx, starty, startz define the starting positions of the stream lines. The
section "Starting Points for Stream Plots" in Visualization Techniques provides more information on defining starting points. The output argument h contains a vector of line handles, one handle for each stream line.
h = streamline(U,V,W,startx,starty,startz) assumes the arrays X, Y, and Z are defined as [X,Y,Z] = meshgrid(1:N,1:M,1:P) where [M,N,P] = size(U). h = streamline(XYZ) assumes XYZ is a precomputed cell array of vertex arrays (as produced by stream3). h = streamline(X,Y,U,V,startx,starty) draws stream lines from 2-D vector data U, V. The arrays X, Y define the coordinates for U, V and must be monotonic and 2-D plaid (such as the data produced by meshgrid). startx and starty define the starting positions of the stream lines. The output argument h
contains a vector of line handles, one handle for each stream line.
h = streamline(U,V,startx,starty) assumes the arrays X and Y are defined as [X,Y] = meshgrid(1:N,1:M) where [M,N] = size(U). h = streamline(XY) assumes XY is a precomputed cell array of vertex arrays (as produced by stream2).
2-434
streamline
streamline(...,options) specifies the options used when creating the stream lines. Define options as a one or two element vector containing the step
size or the step size and the maximum number of vertices in a stream line:
[stepsize]
or
[stepsize, max_number_vertices]
If you do not specify values, MATLAB uses the default: stepsize = 0.1 (one tenth of a cell) maximum number of vertices = 1000
Examples
This example draws stream lines from data representing air currents over a region of North America. Loading the wind data set creates the variables x, y, z, u, v, and w in the MATLAB workspace. The plane of stream lines indicates the flow of air from the west to the east (the x direction) beginning at x = 80 (which is close to the minimum value of the x coordinates). The y and z coordinate starting points are multivalued and approximately span the range of these coordinates. meshgrid generates the starting positions of the stream lines.
load wind [sx,sy,sz] = meshgrid(80,20:10:50,0:5:15); h = streamline(x,y,z,u,v,w,sx,sy,sz); set(h,'Color','red') view(3)
See Also
coneplot, stream2, stream3, streamparticles
"Volume Visualization" for related functions Specifying Starting Points for Stream Plots for related information Stream Line Plots of Vecotr Data for another example
2-435
streamparticles
Purpose Syntax
2streamparticles
Display stream particles
streamparticles(vertices) streamparticles(vertices,n) streamparticles(...,'PropertyName',PropertyValue,...) streamparticles(line_handle,...) h = streamparticles(...) streamparticles(vertices) draws stream particles of a vector field. Stream
Description
particles are usually represented by markers and can show the position and velocity of a streamline. vertices is a cell array of 2-D or 3-D vertices (as if produced by stream2 or stream3).
streamparticles(vertices,n) uses n to determine how many stream particles to draw. The ParticleAlignment property controls how n is
interpreted. If ParticleAlignment is set to off (the default) and n is greater than 1, then approximately n particles are drawn evenly spaced over the streamline vertices. If n is less than or equal to 1, n is interpreted as a fraction of the original stream vertices; for example, if n is 0.2, approximately 20% of the vertices are used.
n determines the upper bound for the number of particles drawn. Note that the actual number of particles may deviate from n by as much as a factor of 2.
If ParticleAlignment is on, n determines the number of particles on the streamline having the most vertices and sets the spacing on the other streamlines to this value. The default value is n = 1.
streamparticles(...,'PropertyName',PropertyValue,...) controls the
stream particles using named properties and specified values. Any unspecified properties have default values. MATLAB ignores the case of property names.
Stream Particle Properties
Animate Stream particle motion [non-negative integer]
The number of times to animate the stream particles. The default is 0, which does not animate. Inf animates until you enter ctrl-c.
2-436
streamparticles
FrameRate Animation frames per second [non-negative integer]
This property specifies the number of frames per second for the animation. Inf, the default draws the animation as fast as possible. Note that speed of the animation may be limited by the speed of the computer. In such cases, the value of FrameRate can not necessarily be achieved.
ParticleAlignment Align particles with stream lines [ on | {off} ]
Set this property to on to draw particles at the beginning of each the stream line. This property controls how streamparticles interprets the argument n (number of stream particles). Stream particles are line objects. In addition to stream particle properties, you can specify any line object property, such as Marker and EraseMode. streamparticles sets the following line properties when called.
Line Property EraseMode LineStyle Marker MarkerEdgeColor MarkerFaceColor Value Set by streamparticles xor none o none red
You can override any of these properties by specifying a property name and value as arguments to streamparticles. For example, this statement uses RGB values to set the MarkerFaceColor to medium gray:
streamparticles(vertices,'MarkerFaceColor',[.5 .5 .5]) streamparticles(line_handle,...) uses the line object identified by line_handle to draw the stream particles. h = streamparticles(...) returns a vector of handles to the line objects it
creates.
Examples
This example combines stream lines with stream particle animation. The interpstreamspeed function determines the vertices along the stream lines
2-437
streamparticles
where stream particles will be drawn during the animation, thereby controlling the speed of the animation. Setting the axes DrawMode property to fast provides faster rendering.
load wind [sx sy sz] = meshgrid(80,20:1:55,5); verts = stream3(x,y,z,u,v,w,sx,sy,sz); sl = streamline(verts); iverts = interpstreamspeed(x,y,z,u,v,w,verts,.025); axis tight; view(30,30); daspect([1 1 .125]) camproj perspective; camva(8) set(gca,'DrawMode','fast') box on streamparticles(iverts,35,'animate',10,'ParticleAlignment','on' )
The following picture is a static view of the animation.
This example uses the stream lines in the z = 5 plane to animate the flow along these lines with steamparticles.
load wind daspect([1 1 1]); view(2) [verts averts] = streamslice(x,y,z,u,v,w,[],[],[5]);
2-438
streamparticles
sl = streamline([verts averts]); axis tight off; set(sl,'Visible','off') iverts = interpstreamspeed(x,y,z,u,v,w,verts,.05); set(gca,'DrawMode','fast','Position',[0 0 1 1],'ZLim',[4.9 5.1]) set(gcf,'Color','black') streamparticles(iverts, 200, ... 'Animate',100,'FrameRate',40, ... 'MarkerSize',10,'MarkerFaceColor','yellow')
See Also
interpstreamspeed, stream3, streamline
"Volume Visualization" for related functions Creating Stream Particle Animations for more details Specifying Starting Points for Stream Plots for related information
2-439
streamribbon
Purpose Syntax
2streamribbon
Creates a 3-D stream ribbon plot
streamribbon(X,Y,Z,U,V,W,startx,starty,startz) streamribbon(U,V,W,startx,starty,startz) streamribbon(vertices,X,Y,Z,cav,speed) streamribbon(vertices,cav,speed) streamribbon(vertices,twistangle) streamribbon(...,width) h = streamribbon(...) streamribbon(X,Y,Z,U,V,W,startx,starty,startz) draws stream ribbons from vector volume data 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). startx, starty, and startz define the starting positions of the stream ribbons at the center of the ribbons. The section "Starting Points for Stream Plots" in Visualization Techniques provides more information on defining starting points.
Description
The twist of the ribbons is proportional to the curl of the vector field. The width of the ribbons is calculated automatically. Generally, you should set the DataAspectRatio (daspect) before calling streamribbon.
streamribbon(U,V,W,startx,starty,startz) 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).
streamribbon(vertices,X,Y,Z,cav,speed) assumes precomputed streamline vertices, curl angular velocity, and flow speed. vertices is a cell array of stream line vertices (as produced by stream3). X, Y, Z, cav, and speed
are 3-D arrays.
streamribbon(vertices,cav,speed) assumes X, Y, and Z are determined by
the expression:
[X,Y,Z] = meshgrid(1:n,1:m,1:p)
2-440
streamribbon
where [m,n,p] = size(cav)
streamribbon(vertices,twistangle) uses the cell array of vectors twistangle for the twist of the ribbons (in radians). The size of each corresponding element of vertices and twistangle must be equal. streamribbon(...,width) sets the width of the ribbons to width. h = streamribbon(...) returns a vector of handles (one per start point) to surface objects.
Examples
This example uses stream ribbons to indicate the flow in the wind data set. Inputs include the coordinates, vector field components, and starting location for the stream ribbons.
load wind [sx sy sz] = meshgrid(80,20:10:50,0:5:15); daspect([1 1 1]) streamribbon(x,y,z,u,v,w,sx,sy,sz); %-----Define viewing and lighting axis tight shading interp; view(3); camlight; lighting gouraud
2-441
streamribbon
This example uses precalculated vertex data (stream3), curl average velocity (curl), and speed ( u + v + w ). Using precalculated data enables you to use values other than those calculated from the single data source. In this case, the speed is reduced by a factor of 10 compared to the previous example.
load wind [sx sy sz] = meshgrid(80,20:10:50,0:5:15); daspect([1 1 1]) verts = stream3(x,y,z,u,v,w,sx,sy,sz); cav = curl(x,y,z,u,v,w); spd = sqrt(u.^2 + v.^2 + w.^2).*.1; streamribbon(verts,x,y,z,cav,spd); %-----Define viewing and lighting axis tight shading interp view(3) camlight; lighting gouraud
2 2 2
2-442
streamribbon
This example specifies a twist angle for the stream ribbon.
t = 0:.15:15; verts = {[cos(t)' sin(t)' (t/3)']}; twistangle = {cos(t)'}; daspect([1 1 1]) streamribbon(verts,twistangle); %-----Define viewing and lighting axis tight shading interp; view(3); camlight; lighting gouraud
2-443
streamribbon
This example combines cone plots (coneplot) and stream ribbon plots in one graph.
%-----Define 3-D arrays x, y, z, u, v, w xmin = -7; xmax = 7; ymin = -7; ymax = 7; zmin = -7; zmax = 7; x = linspace(xmin,xmax,30); y = linspace(ymin,ymax,20); z = linspace(zmin,zmax,20); [x y z] = meshgrid(x,y,z); u = y; v = -x; w = 0*x+1; daspect([1 1 1]); [cx cy cz] = meshgrid(linspace(xmin,xmax,30),... linspace(ymin,ymax,30),[-3 4]); h = coneplot(x,y,z,u,v,w,cx,cy,cz,'quiver'); set(h,'color','k'); %-----Plot two sets of streamribbons [sx sy sz] = meshgrid([-1 0 1],[-1 0 1],-6); streamribbon(x,y,z,u,v,w,sx,sy,sz); [sx sy sz] = meshgrid([1:6],[0],-6); streamribbon(x,y,z,u,v,w,sx,sy,sz);
2-444
streamribbon
%-----Define viewing and lighting shading interp view(-30,10) ; axis off tight camproj perspective; camva(66); camlookat; camdolly(0,0,.5,'fixtarget') camlight
See also
curl, streamtube, streamline, stream3
"Volume Visualization" for related functions Displaying Curl with Stream Ribbons for another example Specifying Starting Points for Stream Plots for related information
2-445
streamslice
Purpose Syntax
2streamslice
Draws stream lines in slice planes
streamslice(X,Y,Z,U,V,W,startx,starty,startz) streamslice(U,V,W,startx,starty,startz) streamslice(X,Y,U,V) streamslice(U,V) streamslice(...,density) streamslice(...,'arrowmode') streamslice(...,'method') h = streamslice(...) [vertices arrowvertices] = streamslice(...) streamslice(X,Y,Z,U,V,W,startx,starty,startz) draws well spaced streamlines (with direction arrows) from vector data U, V, W in axis aligned x-, y-, z-planes at the points in the vectors startx, starty, startz. (The section
Description
"Starting Points for Stream Plots" in Visualization Techniques provides more information on defining starting points.) 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). U, V, W must be m-by-n-by-p volume arrays. You should not assumed that the flow is parallel to the slice plane. For example, in a stream slice at a constant z, the z component of the vector field, W, is ignored when calculating the streamlines for that plane. Stream slices are useful for determining where to start stream lines, stream tubes, and stream ribbons.
streamslice(U,V,W,startx,starty,startz) 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).
streamslice(X,Y,U,V) draws well spaced stream lines (with direction arrows) from vector volume data 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). streamslice(U,V) assumes X, Y, and Z are determined by the expression: [X,Y,Z] = meshgrid(1:n,1:m,1:p)
2-446
streamslice
where [m,n,p] = size(U)
streamslice(...,density) modifies the automatic spacing of the stream lines. density must be greater than 0. The default value is 1; higher values produce more stream lines on each plane. For example, 2 produces
approximately twice as many stream lines, while 0.5 produces approximately half as many.
streamslice(...,'arrowsmode') determines if direction arrows are present or not. arrowmode can be:
arrows draw direction arrows on the streamlines (default) noarrows does not draw direction arrows
streamslice(...,'method') specifies the interpolation method to use. method
can be: linear linear interpolation (default) cubic cubic interpolation nearest nearest neighbor interpolation See interp3 for more information interpolation methods.
h = streamslice(...) returns a vector of handles to the line objects created. [vertices arrowvertices] = streamslice(...) returns two cell arrays of vertices for drawing the stream lines and the arrows. You can pass these values to any of the stream line drawing functions (streamline, streamribbon, streamtube)
Examples
This example creates a stream slice in the wind data set at z = 5.
load wind daspect([1 1 1]) streamslice(x,y,z,u,v,w,[],[],[5]) axis tight
2-447
streamslice
This example uses streamslice to calculate vertex data for the stream lines and the direction arrows. This data is then used by streamline to plot the lines and arrows. Slice planes illustrating with color the wind speed ( u + v + w ) are drawn by slice in the same planes.
load wind daspect([1 1 1]) [verts averts] = streamslice(u,v,w,10,10,10); streamline([verts averts]) spd = sqrt(u.^2 + v.^2 + w.^2); hold on; slice(spd,10,10,10); colormap(hot) shading interp view(30,50); axis(volumebounds(spd)); camlight; material([.5 1 0])
2 2 2
2-448
streamslice
This example superimposes contour lines on a surface and then uses streamslice to draw lines that indicate the gradient of the surface. interp2 is used to find the points for the lines that lie on the surface.
z = peaks; surf(z) shading interp hold on [c ch] = contour3(z,20); set(ch,'edgecolor','b') [u v] = gradient(z); h = streamslice(-u,-v); set(h,'color','k') for i=1:length(h); zi = interp2(z,get(h(i),'xdata'),get(h(i),'ydata')); set(h(i),'zdata',zi); end view(30,50); axis tight
2-449
streamslice
See also
contourslice, slice, streamline, volumebounds
"Volume Visualization" for related functions Specifying Starting Points for Stream Plots for related information
2-450
streamtube
Purpose Syntax
2streamtube
Creates a 3-D stream tube plot
streamtube(X,Y,Z,U,V,W,startx,starty,startz) streamtube(U,V,W,startx,starty,startz) streamtube(vertices,X,Y,Z,divergence) streamtube(vertices,divergence) streamtube(vertices,width) streamtube(vertices) streamtube(...,[scale n]) h = streamtube(...) streamtube(X,Y,Z,U,V,W,startx,starty,startz) draws stream tubes from vector volume data 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). startx, starty, and startz define the starting positions of the stream lines at the center of the tubes. The section "Starting Points for Stream Plots" in Visualization Techniques provides more information on defining starting points.
Description
The width of the tubes is proportional to the normalized divergence of the vector field. Generally, you should set the DataAspectRatio (daspect) before calling streamtube.
streamtube(U,V,W,startx,starty,startz) 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).
streamtube(vertices,X,Y,Z,divergence) assumes precomputed stream line vertices and divergence. vertices is a cell array of stream line vertices (as produced by stream3). X, Y, Z, and divergence are 3-D arrays. streamtube(vertices,divergence) assumes X, Y, and Z are determined by
the expression:
[X,Y,Z] = meshgrid(1:n,1:m,1:p)
2-451
streamtube
where [m,n,p] = size(divergence)
streamtube(vertices,width) specifies the width of the tubes in the cell array of vectors, width. The size of each corresponding element of vertices and width must be equal. width can also be a scalar, specifying a single value for
the width of all stream tubes.
streamtube(vertices) selects the width automatically. streamtube(...,[scale n]) scales the width of the tubes by scale. The default is scale = 1. When the stream tubes are created using start points or divergence, specifying scale = 0 suppresses automatic scaling. n is the number of points along the circumference of the tube. The default is n = 20. h = streamtube(...z) returns a vector of handles (one per start point) to surface objects used to draw the stream tubes.
Examples
This example uses stream tubes to indicate the flow in the wind data set. Inputs include the coordinates, vector field components, and starting location for the stream tubes.
load wind [sx sy sz] = meshgrid(80,20:10:50,0:5:15); daspect([1 1 1]) streamtube(x,y,z,u,v,w,sx,sy,sz); %-----Define viewing and lighting view(3) axis tight shading interp; camlight; lighting gouraud
2-452
streamtube
This example uses precalculated vertex data (stream3) and divergence (divergence).
load wind [sx sy sz] = meshgrid(80,20:10:50,0:5:15); daspect([1 1 1]) verts = stream3(x,y,z,u,v,w,sx,sy,sz); div = divergence(x,y,z,u,v,w); streamtube(verts,x,y,z,-div); %-----Define viewing and lighting view(3) axis tight shading interp camlight; lighting gouraud
2-453
streamtube
See also
divergence, streamribbon, streamline, stream3
"Volume Visualization" for related functions Displaying Divergence with Stream Tubes for another example Specifying Starting Points for Stream Plots for related information
2-454
strfind
Purpose Syntax Description
2strfind
Find one string within another
k = strfind(str,pattern) k = strfind(str,pattern) searches the string, str, for occurrences of a shorter string, pattern, returning the starting index of each such occurrence in the double array, k. If pattern is not found in str, or if pattern is longer than str, then strfind returns the empty array, [].
The search performed by strfind is case sensitive. Any leading and trailing blanks in either str or pattern are explicitly included in the comparison. Use the function findstr, if you are not certain which of the two input strings is the longer one.
Examples
s = 'Find the starting indices of the pattern string'; strfind(s,'in') ans = 2 15 19 45 strfind(s,'In') ans = [] strfind(s,' ') ans = 5 9
18
26
29
33
41
See Also
findstr, strmatch, strtok, strcmp, strncmp, strcmpi, strncmpi, regexp, regexpi, regexprep
2-455
strings
Purpose Syntax
2strings
MATLAB string handling
S = 'Any Characters' S = char(X) X = double(S) S = 'Any Characters' creates a character array, or string. The string is
Description
actually a vector whose components are the numeric codes for the characters (the first 127 codes are ASCII). The actual characters displayed depend on the character set encoding for a given font. The length of S is the number of characters. A quote within the string is indicated by two quotes.
S = [S1 S2 ...] concatenates character arrays S1, S2, etc. into a new character array, S. S = strcat(S1, S2, ...) concatenates S1, S2, etc., which can be character arrays or cell arrays of strings. When the inputs are all character arrays, the output is also a character array. When any of the inputs is a cell array of strings, strcat returns a cell array of strings.
Trailing spaces in strcat character array inputs are ignored and do not appear in the output. This is not true for strcat inputs that are cell arrays of strings. Use the S = [S1 S2 ...] concatenation syntax, shown above, to preserve trailing spaces.
S = char(X) can be used to convert an array that contains positive integers
representing numeric codes into a MATLAB character array.
X = double(S) converts the string to its equivalent double precision numeric
codes. A collection of strings can be created in either of the following two ways: As the rows of a character array via strvcat As a cell array of strings via the curly braces You can convert between character array and cell array of strings using char and cellstr. Most string functions support both types.
ischar(S) tells if S is a string variable. iscellstr(S) tells if S is a cell array of
strings.
2-456
strings
Examples
Create a simple string that includes a single quote.
msg = 'You''re right!' msg = You're right!
Create the string, name, using two methods of concatenation.
name = ['Thomas' ' R. ' 'Lee'] name = strcat('Thomas',' R.',' Lee')
Create a vertical array of strings.
C = strvcat('Hello','Yes','No','Goodbye') C = Hello Yes No Goodbye
Create a cell array of strings.
S = {'Hello' 'Yes' 'No' 'Goodbye'} S = 'Hello' 'Yes' 'No' 'Goodbye'
See Also
char, cellstr, ischar, iscellstr, strvcat, sprintf, sscanf, input
2-457
strjust
Purpose Syntax
2strjust
Justify a character array
T T T T = = = = strjust(S) strjust(S,'right') strjust(S,'left') strjust(S,'center')
Description
T = strjust(S) or T = strjust(S,'right') returns a right-justified version
of the character array S.
T = strjust(S,'left') returns a left-justified version of S. T = strjust(S,'center') returns a center-justified version of S.
See Also
deblank
2-458
strmatch
Purpose Syntax Description
2strmatch
Find possible matches for a string
x = strmatch('str',STRS) x = strmatch('str',STRS,'exact') x = strmatch('str',STRS) looks through the rows of the character array or cell array of strings STRS to find strings that begin with string str, returning the matching row indices. strmatch is fastest when STRS is a character array. x = strmatch('str',STRS,'exact') returns only the indices of the strings in STRS matching str exactly.
Examples
The statement
x = strmatch('max',strvcat('max','minimax','maximum'))
returns x = [1; 3] since rows 1 and 3 begin with 'max'. The statement
x = strmatch('max',strvcat('max','minimax','maximum'),'exact')
returns x = 1, since only row 1 matches 'max' exactly.
See Also
strcmp, strcmpi, strncmp, strncmpi, strfind, findstr, strvcat, regexp, regexpi, regexprep
2-459
strncmp
Purpose Syntax Description
2strncmp
Compare the first n characters of two strings
k = strncmp('str1','str2',n) TF = strncmp(S,T,n) k = strncmp('str1','str2',n) returns logical true (1) if the first n characters of the strings str1 and str2 are the same, and returns logical false (0) otherwise. Arguments str1 and str2 may also be cell arrays of strings. TF = strncmp(S,T,N) where either S or T is a cell array of strings, returns an array TF the same size as S and T containing 1 for those elements of S and T that match (up to n characters), and 0 otherwise. S and T must be the same size (or one can be a scalar cell). Either one can also be a character array with the right number of rows.
Remarks
The command strncmp is case sensitive. Any leading and trailing blanks in either of the strings are explicitly included in the comparison.
strncmp is intended for comparison of character data. When used to compare numeric data, strncmp returns 0.
See Also
strncmpi, strcmp, strcmpi, strmatch, strfind, findstr, regexp, regexpi, regexprep
2-460
strncmpi
Purpose Syntax Description
2strncmpi
Compare first n characters of strings ignoring case
strncmpi('str1','str2',n) TF = strncmpi(S,T,n) strncmpi('str1','str2',n) returns 1 if the first n characters of the strings str1 and str2 are the same except for case, and 0 otherwise. TF = strncmpi(S,T,n) when either S or T is a cell array of strings, returns an array the same size as S and T containing 1 for those elements of S and T that match except for case (up to n characters), and 0 otherwise. S and T must be the same size (or one can be a scalar cell). Either one can also be a character array with the right number of rows.
Remarks
strncmpi is intended for comparison of character data. When used to compare numeric data, strncmpi returns 0. strncmpi supports international character sets.
See Also
strncmp, strcmpi, strcmp, strmatch, strfind, findstr, regexp, regexpi, regexprep
2-461
strread
Purpose Syntax
2strread
Read formatted data from a string
A = strread('str') A = strread('str','',N) A = strread('str','',param,value,...) A = strread('str','',N,param,value,...) [A,B,C,...] = strread('str','format') [A,B,C,...] = strread('str','format',N) [A,B,C,...] = strread('str','format',param,value,...) [A,B,C,...] = strread('str','format',N,param,value,...)
Description
The first four syntaxes are used on strings containing only numeric data. If the input string, str, contains any text data, an error is generated.
A = strread('str') reads numeric data from the string, str, into the single
variable A.
A = strread('str','',N) reads N lines of numeric data, where N is an integer greater than zero. If N is -1, strread reads the entire string. A = strread('str','',param,value,...) customizes strread using param/value pairs, as listed in the table below. A = strread('str','',N,param,value,...) reads N lines and customizes the strread using param/value pairs.
The next four syntaxes can be used on numeric or nonnumeric data. In this case, strread reads data from the string, str, into the variables A, B, C, and so on, using the specified format. The type of each return argument is given by the format string. The number of return arguments must match the number of conversion specifiers in the format string. If there are fewer fields in the string than matching conversion specifiers in the format string, an error is generated. The format string determines the number and types of return arguments. The number of return arguments is the number of items in the format string. The format string supports a subset of the conversion specifiers and conventions of
2-462
strread
the C language fscanf routine. Values for the format string are listed in the table below. Whitespace characters in the format string are ignored.
[A,B,C,...] = strread('str','format') reads data from the string, str, into the variables A, B, C, and so on, using the specified format, until the entire
string is read.
format Action Output
Literals (ordinary characters)
Ignore the matching characters. For example, in a file that has Dept followed by a number (for department number), to skip the Dept and read only the number, use 'Dept' in the format string. Read a signed integer value. Read an integer value. Read a floating point value. Read a whitespace-separated string. Read a string, which could be in double quotes.
None
%d %u %f %s
Double array Double array Double array Cell array of strings Cell array of strings. Does not include the double quotes. Character array Cell array of strings
%q
%c
Read characters, including white space. Read the longest string containing characters specified in the brackets. Read the longest non-empty string containing characters that are not specified in the brackets.
%[...]
%[^...]
Cell array of strings
2-463
strread
format %*...
Action
Output
instead of %
%w...
Ignore the matching characters specified by *. Read field width specified by w. The %f format supports %w.pf, where w is the field width and p is the precision.
No output
instead of %
[A,B,C,...] = strread('str','format',N) reads the data, reusing the format string N times, where N is an integer greater than zero. If N is -1, strread reads the entire string. [A,B,C,...] = strread('str','format',param,value,...) customizes strread using param/value pairs, as listed in the table below. [A,B,C,...] = strread('str','format',N,param,value,...) reads the data, reusing the format string N times and customizes the strread using param/value pairs. param whitespace value \* where * can be: b f n r t \\ \'' or '' %% delimiter Action
Treats vector of characters, *, as whitespace. Default is \b\r\n\t. Backspace Form feed New line Carriage return Horizontal tab Backslash Single quotation mark Percent sign Specifies delimiter character. Default is none. Default is eEdD.
Delimiter character Exponent characters
expchars
2-464
strread
param bufsize
value
Action
positive integer positive integer
matlab shell c c++
Specifies the maximum string length, in bytes. Default is 4095. Ignores the specified number of lines at the beginning of the file. Ignores characters after % Ignores characters after #. Ignores characters between /* and */. Ignores characters after //.
headerlines
commentstyle commentstyle commentstyle commentstyle
Remarks
If your data uses a character other than a space as a delimiter, you must use the strread parameter 'delimiter' to specify the delimiter. For example, if the string, str, used a semicolon as a delimiter, you would use this command.
[names,types,x,y,answer] = strread(str,'%s %s %f ... %d %s','delimiter',';')
Examples
s = sprintf('a,1,2\nb,3,4\n'); [a,b,c] = strread(s,'%s%d%d','delimiter',',') a = 'a' 'b' b = 1 3 c = 2 4
See Also
textread, sscanf
2-465
strrep
Purpose Syntax Description
2strrep
String search and replace
str = strrep(str1,str2,str3) str = strrep(str1,str2,str3) replaces all occurrences of the string str2 within string str1 with the string str3. strrep(str1,str2,str3), when any of str1, str2, or str3 is a cell array of strings, returns a cell array the same size as str1, str2 and str3 obtained by performing a strrep using corresponding elements of the inputs. The inputs must all be the same size (or any can be a scalar cell). Any one of the strings can also be a character array with the right number of rows.
Examples
s1 = 'This is a good example.'; str = strrep(s1,'good','great') str = This is a great example. A = 'MATLAB' 'Toolboxes' B = 'Handle Graphics' 'Toolboxes' C = 'Signal Processing' 'MATLAB' strrep(A,B,C) ans = 'MATLAB' 'MATLAB' 'Image Processing' 'SIMULINK' 'Real Time Workshop' 'The MathWorks' 'SIMULINK' 'The MathWorks'
'SIMULINK' 'SIMULINK'
See Also
findstr
2-466
strtok
Purpose Syntax
2strtok
First token in string
token = strtok('str',delimiter) token = strtok('str') [token,rem] = strtok(...) token = strtok('str',delimiter) returns the first token in the text string str, that is, the first set of characters before a delimiter is encountered. The vector delimiter contains valid delimiter characters. Any leading delimiters
Description
are ignored.
token = strtok('str') uses the default delimiters, the white space
characters. These include tabs (ASCII 9), carriage returns (ASCII 13), and spaces (ASCII 32). Any leading white space characters are ignored.
[token,rem] = strtok(...) returns the remainder rem of the original string.
The remainder consists of all characters from the first delimiter on.
Examples
s = ' This is a good example.'; [token,rem] = strtok(s) token = This rem = is a good example. findstr, strmatch
See Also
2-467
struct
Purpose Syntax Description
2struct
Create structure array
s = struct('field1',{},'field2',{},...) s = struct('field1',values1,'field2',values2,...) s = struct('field1',{},'field2',{},...) creates an empty structure
with fields field1, field2, ...
s = struct('field1',values1,'field2',values2,...) creates a structure array with the specified fields and values. The value arrays values1, values2, etc. must be cell arrays of the same size or scalar cells. Corresponding elements of the value arrays are placed into corresponding structure array elements. The size of the resulting structure is the same size as the value cell arrays or 1-by-1 if none of the values is a cell.
Examples
The command
s = struct('type',{'big','little'},'color',{'red'},'x',{3 4})
produces a structure array s:
s = 1x2 struct array with fields: type color x
The value arrays have been distributed among the fields of s:
s(1) ans = type: 'big' color: 'red' x: 3 s(2) ans = type: 'little' color: 'red' x: 4
2-468
struct
Similarly, the command
a.b = struct('z',{});
produces an empty structure a.b with field z.
a.b ans = 0x0 struct array with fields: z
See Also
isstruct, fieldnames, isfield, orderfields, rmfield, deal, cell2struct, struct2cell
2-469
struct2cell
Purpose Syntax Description
2struct2cell
Structure to cell array conversion
c = struct2cell(s) c = struct2cell(s) converts the m-by-n structure s (with p fields) into a p-by-m-by-n cell array c.
If structure s is multidimensional, cell array c has size [p size(s)].
Examples
The commands
clear s, s.category = 'tree'; s.height = 37.4; s.name = 'birch';
create the structure
s = category: 'tree' height: 37.4000 name: 'birch'
Converting the structure to a cell array,
c = struct2cell(s) c = 'tree' [37.4000] 'birch'
See Also
cell2struct, fieldnames
2-470
strvcat
Purpose Syntax Description
2strvcat
Vertical concatenation of strings
S = strvcat(t1,t2,t3,...) S = strvcat(t1,t2,t3,...) forms the character array S containing the text strings (or string matrices) t1,t2,t3,... as rows. Spaces are appended to each
string as necessary to form a valid matrix. Empty arguments are ignored.
Remarks Examples
If each text parameter, ti, is itself a character array, strvcat appends them vertically to create arbitrarily large string matrices. The command strvcat('Hello','Yes') is the same as ['Hello';'Yes except that strvcat performs the padding automatically.
t1 = 'first';t2 = 'string';t3 = 'matrix';t4 = 'second'; S1 = strvcat(t1,t2,t3) S1 = first string matrix S3 = strvcat(S1,S2) S3 = first string matrix second string matrix S2 = strvcat(t4,t2,t3) S2 = second string matrix '],
See Also
cat, int2str, mat2str, num2str, strings
2-471
sub2ind
Purpose Syntax Description
2sub2ind
Single index from subscripts
IND = sub2ind(siz,I,J) IND = sub2ind(siz,I1,I2,...,In)
The sub2ind command determines the equivalent single index corresponding to a set of subscript values.
IND = sub2ind(siz,I,J) returns the linear index equivalent to the row and column subscripts I and J for a matrix of size siz. siz is a 2-element vector, where siz(1) is the number of rows and siz(2) is the number of columns. IND = sub2ind(siz,I1,I2,...,In) returns the linear index equivalent to the n subscripts I1,I2,...,In for an array of size siz. siz is an n-element vector that
specifies the size of each array dimension.
Examples
Create a 3-by-4-by-2 array, A.
A = [17 24 1 8; 2 22 7 14; 4 6 13 20]; A(:,:,2) = A - 10 A(:,:,1) = 17 2 4 24 22 6 1 7 13 8 14 20
A(:,:,2) = 7 -8 -6 14 12 -4 -9 -3 3 -2 4 10
The value at row 2, column 1, page 2 of the array is -8.
A(2,1,2) ans = -8
2-472
sub2ind
To convert A(2,1,2) into its equivalent single subscript, use sub2ind.
sub2ind(size(A),2,1,2) ans = 14
You can now access the same location in A using the single subscripting method.
A(14) ans = -8
See Also
ind2sub, find, size
2-473
subplot
Purpose Syntax
2subplot
Create and control multiple axes
subplot(m,n,p) subplot(m,n,p,'replace') subplot(h) subplot('Position',[left bottom width height]) h = subplot(...) subplot divides the current figure into rectangular panes that are numbered
Description
row-wise. Each pane contains an axes. Subsequent plots are output to the current pane.
subplot(m,n,p) creates an axes in the p-th pane of a figure divided into an m-by-n matrix of rectangular panes. The new axes becomes the current axes.
If p is a vector, it specifies an axes having a position that covers all the subplot positions listed in p.
subplot(m,n,p,'replace') If the specified axes already exists, delete it and
creat a new axes.
subplot(h) makes the axes with handle h current for subsequent plotting
commands.
subplot('Position',[left bottom width height]) creates an axes at the position specified by a four-element vector. left, bottom, width, and height are in normalized coordinates in the range from 0.0 to 1.0. h = subplot(...) returns the handle to the new axes.
Remarks
If a subplot specification causes a new axes to overlap any existing axes, then subplot deletes the existing axes and uicontrol objects. However, if the subplot specification exactly matches the position of an existing axes, then the matching axes is not deleted and it becomes the current axes.
subplot(1,1,1) or clf deletes all axes objects and returns to the default subplot(1,1,1) configuration.
You can omit the parentheses and specify subplot as.
subplot mnp
2-474
subplot
where m refers to the row, n refers to the column, and p specifies the pane.
Special Case subplot(111)
The command subplot(111) is not identical in behavior to subplot(1,1,1) and exists only for compatibility with previous releases. This syntax does not immediately create an axes, but instead sets up the figure so that the next graphics command executes a clf reset (deleting all figure children) and creates a new axes in the default position. This syntax does not return a handle, so it is an error to specify a return argument. (This behavior is implemented by setting the figure's NextPlot property to replace.)
Examples
To plot income in the top half of a figure and outgo in the bottom half,
income = [3.2 4.1 5.0 5.6]; outgo = [2.5 4.0 3.35 4.9]; subplot(2,1,1); plot(income) subplot(2,1,2); plot(outgo)
2-475
subsasgn
Purpose Syntax Description
2subsasgn
Overloaded method for A(I)=B, A{I}=B, and A.field=B
A = subsasgn(A,S,B) A = subsasgn(A,S,B) is called for the syntax A(i)=B, A{i}=B, or A.i=B when A is an object. S is a structure array with the fields:
type: A string containing '()', '{}', or '.', where '()' specifies integer subscripts; '{}' specifies cell array subscripts, and '.' specifies subscripted structure fields. subs: A cell array or string containing the actual subscripts.
Remarks
subsasgn is designed to be used by the MATLAB interpreter to handle indexed assignments to objects. Calling subsasgn directly as a function is not recommended. If you do use subsasgn in this way, it conforms to the formal
MATLAB dispatching rules and may yield unexpected results.
Examples
The syntax A(1:2,:)=B calls A=subsasgn(A,S,B) where S is a 1-by-1 structure with S.type='()' and S.subs = {1:2,':'}. A colon used as a subscript is passed as the string ':'. The syntax A{1:2}=B calls A=subsasgn(A,S,B) where S.type='{}'. The syntax A.field=B calls subsasgn(A,S,B) where S.type='.' and S.subs='field'. These simple calls are combined in a straightforward way for more complicated subscripting expressions. In such cases length(S) is the number of subscripting levels. For instance, A(1,2).name(3:5)=B calls A=subsasgn(A,S,B) where S is 3-by-1 structure array with the following values:
S(1).type='()' S(1).subs={1,2} S(2).type='.' S(2).subs='name' S(3).type='()' S(3).subs={3:5}
See Also
subsref
See "Handling Subscripted Assignment" for more information about overloaded methods and subsasgn.
2-476
subsindex
Purpose Syntax Description
2subsindex
Overloaded method for X(A)
ind = subsindex(A) ind = subsindex(A) is called for the syntax 'X(A)' when A is an object. subsindex must return the value of the object as a zero-based integer index. (ind must contain integer values in the range 0 to prod(size(X))-1). subsindex is called by the default subsref and subsasgn functions, and you
can call it if you overload these functions.
See Also
subsasgn, subsref
2-477
subsindex
The following illustration shows four subplot regions and indicates the command used to create each.
See Also
axes, cla, clf, figure, gca
"Basic Plots and Graphs" for more information
2-478
subspace
Purpose Syntax Description
2subspace
Angle between two subspaces
theta = subspace(A,B) theta = subspace(A,B) finds the angle between two subspaces specified by the columns of A and B. If A and B are column vectors of unit length, this is the same as acos(A'*B).
Remarks
If the angle between the two subspaces is small, the two spaces are nearly linearly dependent. In a physical experiment described by some observations A, and a second realization of the experiment described by B, subspace(A,B) gives a measure of the amount of new information afforded by the second experiment not associated with statistical errors of fluctuations. Consider two subspaces of a Hadamard matrix, whose columns are orthogonal.
H = hadamard(8); A = H(:,2:4); B = H(:,5:8);
Examples
Note that matrices A and B are different sizes-- A has three columns and B four. It is not necessary that two subspaces be the same size in order to find the angle between them. Geometrically, this is the angle between two hyperplanes embedded in a higher dimensional space.
theta = subspace(A,B) theta = 1.5708
That A and B are orthogonal is shown by the fact that theta is equal to / 2 .
theta - pi/2 ans = 0
2-479
subsref
Purpose Syntax Description
2subsref
Overloaded method for A(I), A{I} and A.field
B = subsref(A,S) B = subsref(A,S) is called for the syntax A(i), A{i}, or A.i when A is an object. S is a structure array with the fields:
type: A string containing '()', '{}', or '.', where '()' specifies integer subscripts; '{}' specifies cell array subscripts, and '.' specifies subscripted structure fields. subs: A cell array or string containing the actual subscripts.
Remarks
subsref is designed to be used by the MATLAB interpreter to handle indexed references to objects. Calling subsref directly as a function is not recommended. If you do use subsref in this way, it conforms to the formal
MATLAB dispatching rules and may yield unexpected results.
Examples
The syntax A(1:2,:) calls subsref(A,S) where S is a 1-by-1 structure with S.type='()' and S.subs={1:2,':'}. A colon used as a subscript is passed as the string ':'. The syntax A{1:2} calls subsref(A,S) where S.type='{}' and S.subs={1:2}. The syntax A.field calls subsref(A,S) where S.type='.' and S.subs='field'. These simple calls are combined in a straightforward way for more complicated subscripting expressions. In such cases length(S) is the number of subscripting levels. For instance, A(1,2).name(3:5) calls subsref(A,S) where S is 3-by-1 structure array with the following values:
S(1).type='()' S(1).subs={1,2} S(2).type='.' S(2).subs='name' S(3).type='()' S(3).subs={3:5}
See Also
subsasgn
See "Handling Subscripted Reference" for more information about overloaded methods and subsref.
2-480
substruct
Purpose Syntax Description
2substruct
Create structure argument for subsasgn or subsref
S = substruct(type1,subs1,type2,subs2,...) S = substruct(type1,subs1,type2,subs2,...) creates a structure with the fields required by an overloaded subsref or subsasgn method. Each type string must be one of '.', '()', or '{}'. The corresponding subs argument must be either a field name (for the '.' type) or a cell array containing the index vectors (for the '()' or '{}' types).
The output S is a structure array containing the fields: type one of '.', '()', or '{}' subs subscript values (field name or cell array of index vectors)
Examples
To call subsref with parameters equivalent to the syntax
B = A(3,5).field
you can use
S = substruct('()',{3,5},'.','field'); B = subsref(A,S);
The structure created by substruct in this example contains the following.
S(1) ans = type: '()' subs: {[3] S(2) ans = type: '.' subs: 'field'
[5]}
See Also
subsasgn, subsref
2-481
subvolume
Purpose Syntax
2subvolume
Extract subset of volume data set
[Nx,Ny,Nz,Nv] = subvolume(X,Y,Z,V,limits) [Nx,Ny,Nz,Nv] = subvolume(V,limits) Nv = subvolume(...) [Nx,Ny,Nz,Nv] = subvolume(X,Y,Z,V,limits) extracts a subset of the volume data set V using the specified axis-aligned limits. limits = [xmin,xmax,ymin, ymax,zmin,zmax] (Any NaNs in the limits indicate that the
Description
volume should not be cropped along that axis). The arrays X, Y, and Z define the coordinates for the volume V. The subvolume is returned in NV and the coordinates of the subvolume are given in NX, NY, and NZ.
[Nx,Ny,Nz,Nv] = subvolume(V,limits) assumes the arrays X, Y, and Z are defined as [X,Y,Z] = meshgrid(1:N,1:M,1:P) where [M,N,P] = size(V). Nv = subvolume(...) returns only the subvolume.
Examples
This example uses a data set that is a collection of MRI slices of a human skull. The data is processed in a variety of ways: The 4-D array is squeezed (squeeze) into three dimensions and then a subset of the data is extracted (subvolume). The outline of the skull is an isosurface generated as a patch (p1) whose vertex normals are recalculated to improve the appearance when lighting is applied (patch, isosurface, isonormals). A second patch (p2) with interpolated face color draws the end caps (FaceColor, isocaps). The view of the object is set (view, axis, daspect). A 100-element grayscale colormap provides coloring for the end caps (colormap). Adding lights to the right and left of the camera illuminates the object (camlight, lighting).
load mri D = squeeze(D); [x,y,z,D] = subvolume(D,[60,80,nan,80,nan,nan]);
2-482
subvolume
p1 = patch(isosurface(x,y,z,D, 5),... 'FaceColor','red','EdgeColor','none'); isonormals(x,y,z,D,p1); p2 = patch(isocaps(x,y,z,D, 5),... 'FaceColor','interp','EdgeColor','none'); view(3); axis tight; daspect([1,1,.4]) colormap(gray(100)) camlight right; camlight left; lighting gouraud
See Also
isocaps, isonormals, isosurface, reducepatch, reducevolume, smooth3
"Volume Visualization" for related functions
2-483
sum
Purpose Syntax Description
2sum
Sum of array elements
B = sum(A) B = sum(A,dim) B = sum(A) returns sums along different dimensions of an array.
If A is a vector, sum(A) returns the sum of the elements. If A is a matrix, sum(A) treats the columns of A as vectors, returning a row vector of the sums of each column. If A is a multidimensional array, sum(A) treats the values along the first non-singleton dimension as vectors, returning an array of row vectors.
B = sum(A,dim) sums along the dimension of A specified by scalar dim.
Remarks Examples
sum(diag(X)) is the trace of X.
The magic square of order 3 is
M = magic(3) M = 8 1 3 5 4 9
6 7 2
This is called a magic square because the sums of the elements in each column are the same.
sum(M) = 15 15 15
as are the sums of the elements in each row, obtained by transposing:
sum(M') = 15 15 15
See Also
cumsum, diff, prod, trace
2-484
superiorto
Purpose Syntax Description
2superiorto
Superior class relationship
superiorto('class1','class2',...)
The superiorto function establishes a hierarchy that determines the order in which MATLAB calls object methods.
superiorto('class1','class2',...) invoked within a class constructor method (say myclass.m) indicates that myclass's method should be invoked if a function is called with an object of class myclass and one or more objects of class class1, class2, and so on.
Remarks
Suppose A is of class 'class_a', B is of class 'class_b' and C is of class 'class_c'. Also suppose the constructor class_c.m contains the statement: superiorto('class_a'). Then e = fun(a,c) or e = fun(c,a) invokes class_c/fun. If a function is called with two objects having an unspecified relationship, the two objects are considered to have equal precedence, and the leftmost object's method is called. So, fun(b,c) calls class_b/fun, while fun(c,b) calls class_c/fun.
See Also
inferiorto
2-485
support
Purpose Syntax Description
2support
Open MathWorks Technical Support Web page
support support opens your web browser to The MathWorks Technical Support Web page at http://www.mathworks.com/support.
This page contains the following items: A Solution Search Engine The "Virtual Technical Support Engineer" that, through a series of questions, determines possible solutions to the problems you are experiencing Technical Notes Tutorials Bug fixes and patches
See Also
web
2-486
surf, surfc
Purpose Syntax
2surf, surfc
3-D shaded surface plot
surf(Z) surf(X,Y,Z) surf(X,Y,Z,C) surf(...,'PropertyName',PropertyValue) surfc(...) h = surf(...) h = surfc(...)
Description
Use surf and surfc to view mathematical functions over a rectangular region. surf and surfc create colored parametric surfaces specified by X, Y, and Z, with color specified by Z or C.
surf(Z) creates a a three-dimensional shaded surface from the z components in matrix Z, using x = 1:n and y = 1:m, where [m,n] = size(Z). The height, Z, is a single-valued function defined over a geometrically rectangular grid. Z
specifies the color data as well as surface height, so color is proportional to surface height.
surf(X,Y,Z) creates a shaded surface using Z for the color data as well as surface height. X and Y are vectors or matrices defining the x and y components of a surface. If X and Y are vectors, length(X) = n and length(Y) = m, where [m,n] = size(Z). In this case, the vertices of the surface faces are
( X ( j ), Y ( i ), Z ( i, j ) ) triples.
surf(X,Y,Z,C) creates a shaded surface, with color defined by C. MATLAB
performs a linear transformation on this data to obtain colors from the current colormap.
surf(...,'PropertyName',PropertyValue) specifies surface properties along
with the data.
surfc(...) draws a contour plot beneath the surface. h = surf(...) and h = surfc(...) return a handle to a surface graphics
object.
2-487
surf, surfc
Algorithm
Abstractly, a parametric surface is parametrized by two independent variables, i and j, which vary continuously over a rectangle; for example, 1 i m and 1 j n. The three functions, x(i,j), y(i,j), and z(i,j), specify the surface. When i and j are integer values, they define a rectangular grid with integer grid points. The functions x(i,j), y(i,j), and z(i,j) become three m-by-n matrices, X, Y and Z. surface color is a fourth function, c(i,j), denoted by matrix C. Each point in the rectangular grid can be thought of as connected to its four nearest neighbors.
i1,j | i,j1 i,j i,j+1 | i+1,j
This underlying rectangular grid induces four-sided patches on the surface. To express this another way, [X(:) Y(:) Z(:)] returns a list of triples specifying points in 3-space. Each interior point is connected to the four neighbors inherited from the matrix indexing. Points on the edge of the surface have three neighbors; the four points at the corners of the grid have only two neighbors. This defines a mesh of quadrilaterals or a quad-mesh. Surface color can be specified in two different ways at the vertices or at the centers of each patch. In this general setting, the surface need not be a single-valued function of x and y. Moreover, the four-sided surface patches need not be planar. For example, you can have surfaces defined in polar, cylindrical, and spherical coordinate systems. The shading function sets the shading. If the shading is interp, C must be the same size as X, Y, and Z; it specifies the colors at the vertices. The color within a surface patch is a bilinear function of the local coordinates. If the shading is faceted (the default) or flat, C(i,j) specifies the constant color in the surface patch:
(i,j) (i,j+1) | C(i,j) | (i+1,j) (i+1,j+1)
2-488
surf, surfc
In this case, C can be the same size as X, Y, and Z and its last row and column are ignored, Alternatively, its row and column dimensions can be one less than those of X, Y, and Z. The surf and surfc functions specify the view point using view(3). The range of X, Y, and Z, or the current setting of the axes XLimMode, YLimMode, and ZLimMode properties (also set by the axis function) determine the axis labels. The range of C, or the current setting of the axes CLim and ClimMode properties (also set by the caxis function) determine the color scaling. The scaled color values are used as indices into the current colormap.
Examples
Display a surface and contour plot of the peaks surface.
[X,Y,Z] = peaks(30); surfc(X,Y,Z) colormap hsv axis([-3 3 -3 3 -10 5])
5
0
-5
-10 3 2 1 0 -1 -2 -3 -3 -2 0 -1 1 2 3
Color a sphere with the pattern of +1s and -1s in a Hadamard matrix.
2-489
surf, surfc
k = 5; n = 2^k1; [x,y,z] = sphere(n); c = hadamard(2^k); surf(x,y,z,c); colormap([1 1 0; 0 axis equal
1
1])
1
0.5
0
-0.5
-1 1 0.5 0 -0.5 -1 -1 0 -0.5 0.5 1
See Also
axis, caxis, colormap, contour, delaunay, mesh, pcolor, shading, trisurf, view
Properties for surface graphics objects "Creating Surfaces and Meshes" for related functions Representing a Matrix as a Surface for more examples Coloring Mesh and Surface Plots for information about how to control the coloring of surfaces
2-490
surf2patch
Purpose Syntax
2surf2patch
Convert surface data to patch data
fvc = surf2patch(h) fvc = surf2patch(Z) fvc = surf2patch(Z,C) fvc = surf2patch(X,Y,Z) fvc = surf2patch(X,Y,Z,C) fvc = surf2patch(...,'triangles') [f,v,c] = surf2patch(...) fvc = surf2patch(h) converts the geometry and color data from the surface object identified by the handle h into patch format and returns the face, vertex, and color data in the struct fvc. You can pass this struct directly to the patch
Description
command.
fvc = surf2patch(Z) calculates the patch data from the surface's ZData matrix Z. fvc = surf2patch(Z,C) calculates the patch data from the surface's ZData and CData matrices Z and C. fvc = surf2patch(X,Y,Z) calculates the patch data from the surface's XData, YData, and ZData matrices X, Y, and Z. fvc = surf2patch(X,Y,Z,C) calculates the patch data from the surface's XData, YData, ZData, and CData matrices X, Y, Z, and C. fvc = surf2patch(...,'triangles') creates triangular faces instead of the
quadrilaterals that compose surfaces.
[f,v,c] = surf2patch(...) returns the face, vertex, and color data in the three arrays f, v, and c instead of a struct.
Examples
The first example uses the sphere command to generate the XData, YData, and ZData of a surface, which is then converted to a patch. Note that the ZData (z) is passed to surf2patch as both the third and fourth arguments the third argument is the ZData and the fourth argument is taken as the CData. This is because the patch command does not automatically use the z-coordinate data for the color data, as does the surface command.
2-491
surf2patch
Also, because patch is a low-level command, you must set the view to 3-D and shading to faceted to produce the same results produced by the surf command.
[x y z] = sphere; patch(surf2patch(x,y,z,z)); shading faceted; view(3)
In the second example surf2patch calculates face, vertex, and color data from a surface whose handle has been passed as an argument.
s = surf(peaks); pause patch(surf2patch(s)); delete(s) shading faceted; view(3)
See Also
patch, reducepatch, shrinkfaces, surface, surf
"Volume Visualization" for related functions
2-492
surface
Purpose Syntax
2surface
Create surface object
surface(Z) surface(Z,C) surface(X,Y,Z) surface(X,Y,Z,C) surface(...'PropertyName',PropertyValue,...) h = surface(...)
surface is the low-level function for creating surface graphics objects. surfaces
Description
are plots of matrix data created using the row and column indices of each element as the x- and y-coordinates and the value of each element as the z-coordinate.
surface(Z) plots the surface specified by the matrix Z. Here, Z is a
single-valued function, defined over a geometrically rectangular grid.
surface(Z,C) plots the surface specified by Z and colors it according to the data in C (see "Examples"). surface(X,Y,Z) uses C = Z, so color is proportional to surface height above the
x-y plane.
surface(X,Y,Z,C) plots the parametric surface specified by X, Y and Z, with
color specified by C.
surface(x,y,Z), surface(x,y,Z,C) replaces the first two matrix arguments with vectors and must have length(x) = n and length(y) = m where [m,n] = size(Z). In this case, the vertices of the surface facets are the triples (x(j),y(i),Z(i,j)). Note that x corresponds to the columns of Z and y corresponds to the rows of Z. For a complete discussion of parametric surfaces, see the surf function. surface(...'PropertyName',PropertyValue,...) follows the X, Y, Z, and C
arguments with property name/property value pairs to specify additional surface properties. These properties are described in the "Surface Properties" section.
h = surface(...) returns a handle to the created surface object.
2-493
surface
Remarks
Unlike high-level area creation functions, such as surf or mesh, surface does not respect the settings of the figure and axes NextPlot properties. It simply adds the surface object to the current axes. If you do not specify separate color data (C), MATLAB uses the matrix (Z) to determine the coloring of the surface. In this case, color is proportional to values of Z. You can specify a separate matrix to color the surface independently of the data defining the area of the surface. You can specify properties as property name/property value pairs, structure arrays, and cell arrays (see set and get for examples of how to specify these data types).
surface provides convenience forms that allow you to omit the property name for the XData, YData, ZData, and CData properties. For example,
surface('XData',X,'YData',Y,'ZData',Z,'CData',C)
is equivalent to:
surface(X,Y,Z,C)
When you specify only a single matrix input argument,
surface(Z)
MATLAB assigns the data properties as if you specified,
surface('XData',[1:size(Z,2)],... 'YData',[1:size(Z,1)],... 'ZData',Z,... 'CData',Z)
The axis, caxis, colormap, hold, shading, and view commands set graphics properties that affect surfaces. You can also set and query surface property values after creating them using the set and get commands.
Example
This example creates a surface using the peaks M-file to generate the data, and colors it using the clown image. The ZData is a 49-by-49 element matrix, while the CData is a 200-by-320 matrix. You must set the surface's FaceColor to texturemap to use ZData and CData of different dimensions.
load clown surface(peaks,flipud(X),...
2-494
surface
'FaceColor','texturemap',... 'EdgeColor','none',... 'CDataMapping','direct') colormap(map) view(-35,45)
Note the use of the surface(Z,C) convenience form combined with property name/property value pairs. Since the clown data (X) is typically viewed with the image command, which MATLAB normally displays with 'ij' axis numbering and direct CDataMapping, this example reverses the data in the vertical direction using flipud and sets the CDataMapping property to direct.
See Also
ColorSpec, mesh, patch, pcolor, surf
Properties for surface graphics objects "Creating Surfaces and Meshes" and "Object Creation Functions" for related functions
2-495
surface
Object Hierarchy
Root
Figure
Axes
Uicontrol
Uimenu
Uicontextmenu
Image
Light
Line
Patch
Rectangle
Surface
Text
Setting Default Properties
You can set default surface properties on the axes, figure, and root levels.
set(0,'DefaultSurfaceProperty',PropertyValue...) set(gcf,'DefaultSurfaceProperty',PropertyValue...) set(gca,'DefaultSurfaceProperty',PropertyValue...)
Where Property is the name of the surface property whose default value you want to set and PropertyValue is the value you are specifying. Use set and get to access the surface properties.
Property List
The following table lists all surface properties and provides a brief description of each. The property name links take you to an expanded description of the properties.
Property Description Property Value
Property Name Data Defining the Object XData
The x-coordinates of the vertices of the surface The y-coordinates of the vertices of the surface
Values: vector or matrix Values: vector or matrix
YData
2-496
surface
Property Name ZData
Property Description
Property Value
The z-coordinates of the vertices of the surface
Values: matrix
Specifying Color CData
Color data
Values: scalar, vector, or matrix Default: [] empty matrix Values: scaled, direct Default: scaled Values: ColorSpec, none, flat, interp Default: ColorSpec Values: ColorSpec, none, flat, interp Default: ColorSpec Values: ColorSpec, none,
auto
CDataMapping
Controls mapping of CData to colormap Color of face edges
EdgeColor
FaceColor
Color of face
MarkerEdgeColor
Color of marker or the edge color for filled markers Fill color for markers that are closed shapes
Default: auto
MarkerFaceColor
Values: ColorSpec, none,
auto
Default: none
Specifying Transparency AlphaData
The transparency data Transparency mapping method Transparency of the edges of patch faces
m-by-n matrix of double or
uint8 none, direct, scaled Default: scaled scalar, flat, interp Default: 1 (opaque)
AlphaDataMapping
EdgeAlpha
2-497
surface
Property Name FaceAlpha
Property Description
Property Value scalar, flat, interp, texture Default: 1 (opaque)
Transparency of the patch face
Controlling the Effects of Lights AmbientStrength
Intensity of the ambient light Controls lighting of faces pointing away from camera Intensity of diffuse light Method used to light edges
Values: scalar >=0 and <=1 Default: 0.3 Values: unlit, lit,
reverselit Default: reverselit
BackFaceLighting
DiffuseStrength
Values: scalar >=0 and <=1 Default: 0.6 Values: none, flat, gouraud,
phong
EdgeLighting
Default: none
FaceLighting
Method used to light edges
Values: none, flat, gouraud,
phong
Default: none
NormalMode
MATLAB-generated or user-specified Values: auto, manual normal vectors Default: auto Values: scalar 0 to 1 Default: 1 Values: scalar >= 1 Default: 10 Values: scalar >=0 and <=1 Default: 0.9 Values: matrix
SpecularColorReflectanc Composite color of specularly e reflected light SpecularExponent
Harshness of specular reflection Intensity of specular light Vertex normal vectors
SpecularStrength
VertexNormals
Defining Edges and Markers
2-498
surface
Property Name LineStyle
Property Description
Property Value
Linestyle of the edge. Select from five line styles. The width of the edge in points Marker symbol to plot at data points Size of marker in points
Values: -, --, :, -., none Default: - Values: scalar Default: 0.5 points Values: see Marker property Default: none Values: size in points Default: 6
LineWidth
Marker
MarkerSize
Controlling the Appearance Clipping
Clipping to axes rectangle Method of drawing and erasing the surface (useful for animation)
Values: on, off Default: on Values: normal, none, xor,
background Default: normal
EraseMode
MeshStyle
Specifies whether to draw all edge Values: both, row, column lines or just row or column edge lines Defaults: both Highlight surface when selected (Selected property set to on) Make the surface visible or invisible Values: on, off Default: on Values: on, off Default: on
SelectionHighlight
Visible
Controlling Access to Objects HandleVisibility
Determines if and when the surface's handle is visible to other functions Determines if the surface can become the current object (see the figure CurrentObject property)
Values: on, callback, off Default: on Values: on, off Default: on
HitTest
Properties Related to Callback Routine Execution
2-499
surface
Property Name BusyAction
Property Description
Property Value
Specifies how to handle callback routine interruption Defines a callback routine that executes when a mouse button is pressed on over the surface Defines a callback routine that executes when an surface is created Defines a callback routine that executes when the surface is deleted (via close or delete) Determines if callback routine can be interrupted Associates a context menu with the surface
Values: cancel, queue Default: queue Values: string or function handle Default: '' (empty string) Values: string or function handle Default: '' (empty string) Values: string or function handle Default: '' (empty string) Values: on, off Default: on (can be interrupted) Values: handle of a uicontextmenu
ButtonDownFcn
CreateFcn
DeleteFcn
Interruptible
UIContextMenu
General Information About the Surface Children Parent
Surface objects have no children The parent of a surface object is always an axes object Indicates whether the surface is in a "selected" state. User-specified label The type of graphics object (read only) User-specified data
Values: [] (empty matrix) Value: axes handle Values: on, off Default: on Value: any string Default: '' (empty string) Value: the string 'surface' Values: any matrix Default: [] (empty matrix)
Selected
Tag
Type
UserData
2-500
Surface Properties
Modifying Properties
2Surface 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.
Surface Property Descriptions
This section lists property names along with the types of values each accepts. Curly braces { } enclose default values.
AlphaData
m-by-n matrix of double or uint8
The transparency data. A matrix of non-NaN values specifying the transparency of each face or vertex of the object. The AlphaData can be of class double or uint8. MATLAB determines the transparency in one of three ways: Using the elements of AlphaData as transparency values (AlphaDataMapping set to none). Using the elements of AlphaData as indices into the current alphamap (AlphaDataMapping set to direct). Scaling the elements of AlphaData to range between the minimum and maximum values of the axes ALim property (AlphaDataMapping set to scaled, the default).
AlphaDataMapping none | direct | {scaled}
Transparency mapping method. This property determines how MATLAB interprets indexed alpha data. This property can be any of the following: none - The transparency values of AlphaData are between 0 and 1 or are clamped to this range (the default). scaled - Transform the AlphaData to span the portion of the alphamap indicated by the axes ALim property, linearly mapping data values to alpha values. direct - use the AlphaData as indices directly into the alphamap. When not scaled, the data are usually integer values ranging from 1 to length(alphamap). MATLAB maps values less than 1 to the first alpha value in the alphamap, and values greater than length(alphamap) to the
2-501
Surface Properties
last alpha value in the alphamap. Values with a decimal portion are fixed to the nearest, lower integer. If AlphaData is an array unit8 integers, then the indexing begins at 0 (i.e., MATLAB maps a value of 0 to the first alpha value in the alphamap).
AmbientStrength
scalar >= 0 and <= 1
Strength of ambient light. This property sets the strength of the ambient light, which is a nondirectional light source that illuminates the entire scene. You must have at least one visible light object in the axes for the ambient light to be visible. The axes AmbientLightColor property sets the color of the ambient light, which is therefore the same on all objects in the axes. You can also set the strength of the diffuse and specular contribution of light objects. See the surface DiffuseStrength and SpecularStrength properties.
BackFaceLighting
unlit | lit | reverselit
Face lighting control. This property determines how faces are lit when their vertex normals point away from the camera. unlit face is not lit lit face lit in normal way reverselit face is lit as if the vertex pointed towards the camera This property is useful for discriminating between the internal and external surfaces of an object. See Back Face Lighting for an example.
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.
2-502
Surface Properties
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 over the surface object. 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.
CData
matrix
Vertex colors. A matrix containing values that specify the color at every point in ZData. If you set the FaceColor property to texturemap, CData does not need to be the same size as ZData. In this case, MATLAB maps CData to conform to the surface defined by ZData. You can specify color as indexed values or true color. Indexed color data specifies a single value for each vertex. These values are either scaled to map linearly into the current colormap (see caxis) or interpreted directly as indices into the colormap, depending on the setting of the CDataMapping property. True color defines an RGB value for each vertex. If the coordinate data (XData for example) are contained in m-by-n matrices, then CData must be an m-by-n-3 array. The first page contains the red components, the second the green components, and the third the blue components of the colors. On computer displays that cannot display true color (e.g., 8-bit displays), MATLAB uses dithering to approximate the RGB triples using the colors in the figure's Colormap and Dithermap. By default, Dithermap uses the colorcube(64) colormap. You can also specify your own dithermap.
CDataMapping {scaled} | direct
Direct or scaled color mapping. This property determines how MATLAB interprets indexed color data used to color the surface. (If you use true color specification for CData, this property has no effect.) scaled transform the color data to span the portion of the colormap indicated by the axes CLim property, linearly mapping data values to colors. See the caxis reference page for more information on this mapping.
2-503
Surface Properties
direct use the color data as indices directly into the colormap. The color data should then be integer values ranging from 1 to length(colormap). MATLAB maps values less than 1 to the first color in the colormap, and values greater than length(colormap) to the last color in the colormap. Values with a decimal portion are fixed to the nearest, lower integer.
Children
matrix of handles
Always the empty matrix; surface objects have no children.
Clipping {on} | off
Clipping to axes rectangle. When Clipping is on, MATLAB does not display any portion of the surface that is outside the axes rectangle.
CreateFcn
string or function handle
Callback routine executed during object creation. This property defines a callback routine that executes when MATLAB creates a surface object. You must define this property as a default value for surfaces. For example, the statement,
set(0,'DefaultSurfaceCreateFcn',... 'set(gcf,''DitherMap'',my_dithermap)')
defines a default value on the root level that sets the figure DitherMap property whenever you create a surface object. MATLAB executes this routine after setting all surface properties. Setting this property on an existing surface object has no effect. The handle of the object whose CreateFcn is being executed is accessible only through the root CallbackObject property, which you can query using gcbo. See Function Handle Callbacks for information on how to use function handles to define the callback function.
DeleteFcn
string or function handle
Delete surface callback routine. A callback routine that executes when you delete the surface object (e.g., when you issue a delete command or clear the axes or figure). MATLAB executes the routine before destroying the object's properties so these values are available to the callback routine. The handle of the object whose DeleteFcn is being executed is accessible only through the root CallbackObject property, which you can query using gcbo.
2-504
Surface Properties
See Function Handle Callbacks for information on how to use function handles to define the callback function.
DiffuseStrength
scalar >= 0 and <= 1
Intensity of diffuse light. This property sets the intensity of the diffuse component of the light falling on the surface. Diffuse light comes from light objects in the axes. You can also set the intensity of the ambient and specular components of the light on the surface object. See the AmbientStrength and SpecularStrength properties.
EdgeAlpha {scalar = 1} | flat | interp
Transparency of the surface edges. This property can be any of the following: scalar - A single non-Nan scalar value between 0 and 1 that controls the transparency of all the edges of the object. 1 (the default) is fully opaque and 0 means completely transparent. flat - The alpha data (AlphaData) value for the first vertex of the face determines the transparency of the edges. interp - Linear interpolation of the alpha data (AlphaData) values at each vertex determine the transparency of the edge. Note that you must specify AlphaData as a matrix equal in size to ZData to use flat or interp EdgeAlpha.
EdgeColor {ColorSpec} | none | flat | interp
Color of the surface edge. This property determines how MATLAB colors the edges of the individual faces that make up the surface: ColorSpec -- A three-element RGB vector or one of the MATLAB predefined names, specifying a single color for edges. The default EdgeColor is black. See ColorSpec for more information on specifying color. none -- Edges are not drawn.
2-505
Surface Properties
flat -- The CData value of the first vertex for a face determines the color of each edge.
Direction of increasing y data
Vertex controlling the color of adjacent edges
Direction of increasing x data
interp -- Linear interpolation of the CData values at the face vertices determines the edge color.
EdgeLighting {none} | flat | gouraud | phong
Algorithm used for lighting calculations. This property selects the algorithm used to calculate the effect of light objects on surface edges. Choices are: none Lights do not affect the edges of this object. flat The effect of light objects is uniform across each edge of the surface. gouraud The effect of light objects is calculated at the vertices and then linearly interpolated across the edge lines. phong The effect of light objects is determined by interpolating the vertex normals across each edge line and calculating the reflectance at each pixel. Phong lighting generally produces better results than Gouraud lighting, but takes longer to render.
EraseMode {normal} | none | xor | background
Erase mode. This property controls the technique MATLAB uses to draw and erase surface objects. Alternative erase modes are useful for creating animated sequences, where control of the way individual objects redraw is necessary to improve performance and obtain the desired effect. normal -- Redraw the affected region of the display, performing the three-dimensional analysis necessary to ensure that all objects are rendered correctly. This mode produces the most accurate picture, but is the slowest. The other modes are faster, but do not perform a complete redraw and are therefore less accurate.
2-506
Surface Properties
none -- Do not erase the surface when it is moved or destroyed. While the object is still visible on the screen after erasing with EraseMode none, you cannot print it because MATLAB stores no information about its former location. xor -- Draw and erase the surface by performing an exclusive OR (XOR) with each pixel index of the screen behind it. Erasing the surface does not damage the color of the objects behind it. However, surface color depends on the color of the screen behind it and is correctly colored only when over the axes background Color, or the figure background Color if the axes Color is set to none. background -- Erase the surface by drawing it in the axes' background Color, or the figure background Color if the axes Color is set to none. This damages objects that are behind the erased object, but surface objects are always properly colored.
Printing with Non-normal Erase Modes. MATLAB always prints figures as if the EraseMode of all objects is normal. This means graphics objects created with EraseMode set to none, xor, or background can look different on screen than on
paper. On screen, MATLAB may mathematically combine layers of colors (e.g., XORing a pixel color with that of the pixel behind it) and ignore three-dimensional sorting to obtain greater rendering speed. However, these techniques are not applied to the printed output. You can use the MATLAB getframe command or other screen capture application to create an image of a figure containing non-normal mode objects.
FaceAlpha {scalar = 1} | flat | interp | texturemap
Transparency of the surface faces. This property can be any of the following: scalar - A single non-NaN scalar value between 0 and 1 that controls the transparency of all the faces of the object. 1 (the default) is fully opaque and 0 is completely transparent (invisible). flat - The values of the alpha data (AlphaData) determine the transparency for each face. The alpha data at the first vertex determines the transparency of the entire face. interp - Bilinear interpolation of the alpha data (AlphaData) at each vertex determine the transparency of each face. texturemap Use transparency for the texturemap.
2-507
Surface Properties
Note that you must specify AlphaData as a matrix equal in size to ZData to use flat or interp FaceAlpha.
FaceColor ColorSpec | none | {flat} | interp
Color of the surface face. This property can be any of the following: ColorSpec -- A three-element RGB vector or one of the MATLAB predefined names, specifying a single color for faces. See ColorSpec for more information on specifying color. none -- Do not draw faces. Note that edges are drawn independently of faces. flat -- The values of CData determine the color for each face of the surface. The color data at the first vertex determines the color of the entire face. interp -- Bilinear interpolation of the values at each vertex (the CData) determines the coloring of each face. texturemap -- Texture map the CData to the surface. MATLAB transforms the color data so that it conforms to the surface. (See the texture mapping example.)
FaceLighting {none} | flat | gouraud | phong
Algorithm used for lighting calculations. This property selects the algorithm used to calculate the effect of light objects on the surface. Choices are: none Lights do not affect the faces of this object. flat The effect of light objects is uniform across the faces of the surface. Select this choice to view faceted objects. gouraud The effect of light objects is calculated at the vertices and then linearly interpolated across the faces. Select this choice to view curved surfaces. phong The effect of light objects is determined by interpolating the vertex normals across each face and calculating the reflectance at each pixel. Select this choice to view curved surfaces. Phong lighting generally produces better results than Gouraud lighting, but takes longer to render.
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. This property is useful for preventing command-line users from
2-508
Surface Properties
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. 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 surface 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 surface. If HitTest is off, clicking on the surface selects the object below it (which maybe the axes containing it).
2-509
Surface Properties
Interruptible
{on} | off
Callback routine interruption mode. The Interruptible property controls whether a surface 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.
LineStyle {-} | -- | : | -. | none
Edge line type. This property determines the line style used to draw surface edges. The available line styles are shown in this table.
Symbol - Line Style
solid line (default) dashed line dotted line dash-dot line no line scalar
--
: -. none LineWidth
Edge line width. The width of the lines in points used to draw surface edges. The default width is 0.5 points (1 point = 1/72 inch).
Marker
marker symbol (see table)
Marker symbol. The Marker property specifies symbols that display at vertices. You can set values for the Marker property independently from the LineStyle property.
2-510
Surface Properties
You can specify these markers.
Marker Specifier + o * . x s d ^ v > < p h Description
plus sign circle asterisk point cross square diamond upward pointing triangle downward pointing triangle right pointing triangle left pointing triangle five-pointed star (pentagram) six-pointed star (hexagram) no marker (default)
none | {auto} | flat | ColorSpec
none
MarkerEdgeColor
Marker edge color. The color of the marker or the edge color for filled markers (circle, square, diamond, pentagram, hexagram, and the four triangles). none specifies no color, which makes nonfilled markers invisible. auto uses the same color as the EdgeColor property. flat uses the CData value of the vertex to determine the color of the maker edge. ColorSpec defines a single color to use for the edge (see ColorSpec for more information).
2-511
Surface Properties
MarkerFaceColor
{none} | auto | flat | ColorSpec
Marker face color. The fill color for markers that are closed shapes (circle, square, diamond, pentagram, hexagram, and the four triangles). none makes the interior of the marker transparent, allowing the background to show through. auto uses the axes Color for the marker face color. flat uses the CData value of the vertex to determine the color of the face. ColorSpec defines a single color to use for all marker on the surface (see ColorSpec for more information).
MarkerSize
size in points
Marker size. A scalar specifying the marker size, in points. The default value for MarkerSize is six points (1 point = 1/72 inch). Note that MATLAB draws the point marker at 1/3 the specified marker size.
MeshStyle {both} | row | column
Row and column lines. This property specifies whether to draw all edge lines or just row or column edge lines. both draws edges for both rows and columns. row draws row edges only. column draws column edges only.
NormalMode {auto} | manual
MATLAB -generated or user-specified normal vectors. When this property is auto, MATLAB calculates vertex normals based on the coordinate data. If you specify your own vertex normals, MATLAB sets this property to manual and does not generate its own data. See also the VertexNormals property.
Parent
handle
Surface's parent object. The parent of a surface object is the axes in which it is displayed. You can move a surface object to another axes by setting this property to the handle of the new parent.
Selected on | {off}
Is object selected? When this property is on, MATLAB displays a dashed bounding box around the surface if the SelectionHighlight property is also
2-512
Surface Properties
on. You can, for example, define the ButtonDownFcn to set this property,
allowing users to select the object with the mouse.
SelectionHighlight {on} | off
Objects highlight when selected. When the Selected property is on, MATLAB indicates the selected state by drawing a dashed bounding box around the surface. When SelectionHighlight is off, MATLAB does not draw the handles.
SpecularColorReflectancescalar in the range 0 to 1
Color of specularly reflected light. When this property is 0, the color of the specularly reflected light depends on both the color of the object from which it reflects and the color of the light source. When set to 1, the color of the specularly reflected light depends only on the color or the light source (i.e., the light object Color property). The proportions vary linearly for values in between.
SpecularExponent
scalar >= 1
Harshness of specular reflection. This property controls the size of the specular spot. Most materials have exponents in the range of 5 to 20.
SpecularStrength
scalar >= 0 and <= 1
Intensity of specular light. This property sets the intensity of the specular component of the light falling on the surface. Specular light comes from light objects in the axes. You can also set the intensity of the ambient and diffuse components of the light on the surface object. See the AmbientStrength and DiffuseStrength properties. Also see the material function.
Tag
string
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. You can define Tag as any string.
Type
string (read only)
Class of the graphics object. The class of the graphics object. For surface objects, Type is always the string 'surface'.
2-513
Surface Properties
UIContextMenu
handle of a uicontextmenu object
Associate a context menu with the surface. Assign this property the handle of a uicontextmenu object created in the same figure as the surface. Use the uicontextmenu function to create the context menu. MATLAB displays the context menu whenever you right-click over the surface.
UserData
matrix
User-specified data. Any matrix you want to associate with the surface object. MATLAB does not use this data, but you can access it using the set and get commands.
VertexNormals
vector or matrix
Surface normal vectors. This property contains the vertex normals for the surface. MATLAB generates this data to perform lighting calculations. You can supply your own vertex normal data, even if it does not match the coordinate data. This can be useful to produce interesting lighting effects.
Visible {on} | off
Surface object visibility. By default, all surfaces are visible. When set to off, the surface is not visible, but still exists and you can query and set its properties.
XData
vector or matrix
X-coordinates. The x-position of the surface points. If you specify a row vector, surface replicates the row internally until it has the same number of columns as ZData.
YData
vector or matrix
Y-coordinates. The y-position of the surface points. If you specify a row vector, surface replicates the row internally until it has the same number of rows as ZData.
ZData
matrix
Z-coordinates. Z-position of the surface points. See the Description section for more information.
2-514
surfl
Purpose Syntax
2surfl
Surface plot with colormap-based lighting
surfl(Z) surfl(X,Y,Z) surfl(...,'light') surfl(...,s) surfl(X,Y,Z,s,k) h = surfl(...)
Description
The surfl function displays a shaded surface based on a combination of ambient, diffuse, and specular lighting models.
surfl(Z) and surfl(X,Y,Z) create three-dimensional shaded surfaces using
the default direction for the light source and the default lighting coefficients for the shading model. X, Y, and Z are vectors or matrices that define the x, y, and z components of a surface.
surfl(...,'light') produces a colored, lighted surface using a MATLAB
light object. This produces results different from the default lighting method, surfl(...,'cdata'), which changes the color data for the surface to be the reflectance of the surface.
surfl(...,s) specifies the direction of the light source. s is a two- or
three-element vector that specifies the direction from a surface to a light source. s = [sx sy sz] or s = [azimuth elevation]. The default s is 45 counterclockwise from the current view direction.
surfl(X,Y,Z,s,k) specifies the reflectance constant. k is a four-element vector defining the relative contributions of ambient light, diffuse reflection, specular reflection, and the specular shine coefficient. k = [ka kd ks shine] and defaults to [.55,.6,.4,10]. h = surfl(...) returns a handle to a surface graphics object.
Remarks
For smoother color transitions, use colormaps that have linear intensity variations (e.g., gray, copper, bone, pink). The ordering of points in the X, Y, and Z matrices define the inside and outside of parametric surfaces. If you want the opposite side of the surface to reflect the
2-515
surfl
light source, use surfl(X',Y',Z'). Because of the way surface normal vectors are computed, surfl requires matrices that are at least 3-by-3.
Examples
View peaks using colormap-based lighting.
[x,y] = meshgrid(3:1/8:3); z = peaks(x,y); surfl(x,y,z); shading interp colormap(gray); axis([3 3 3 3 8 8])
To plot a lighted surface from a view direction other than the default.
view([10 10]) grid on hold on surfl(peaks) shading interp colormap copper
2-516
surfl
hold off
See Also
colormap, shading, light
"Creating Surfaces and Meshes" for functions related to surfaces "Lighting" for functions related to lighting
2-517
surfnorm
Purpose Syntax
2surfnorm
Compute and display 3-D surface normals
surfnorm(Z) surfnorm(X,Y,Z) [Nx,Ny,Nz] = surfnorm(...)
Description
The surfnorm function computes surface normals for the surface defined by X, Y, and Z. The surface normals are unnormalized and valid at each vertex. Normals are not shown for surface elements that face away from the viewer.
surfnorm(Z) and surfnorm(X,Y,Z) plot a surface and its surface normals. Z is a matrix that defines the z component of the surface. X and Y are vectors or
matrices that define the x and y components of the surface.
[Nx,Ny,Nz] = surfnorm(...) returns the components of the
three-dimensional surface normals for the surface.
Remarks
The direction of the normals is reversed by calling surfnorm with transposed arguments:
surfnorm(X',Y',Z') surfl uses surfnorm to compute surface normals when calculating the
reflectance of a surface.
Algorithm Examples
The surface normals are based on a bicubic fit of the data in X, Y, and Z. For each vertex, diagonal vectors are computed and crossed to form the normal. Plot the normal vectors for a truncated cone.
[x,y,z] = cylinder(1:10); surfnorm(x,y,z) axis([-12 12 -12 12 -0.1 1])
2-518
surfnorm
1 0.8 0.6 0.4 0.2 0 10 5 0 -5 -10 -10 -5 0 5 10
See Also
surf, quiver3
"Colormaps" for related functions
2-519
svd
Purpose Syntax
2svd
Singular value decomposition
s = svd(X) [U,S,V] = svd(X) [U,S,V] = svd(X,0)
Description
The svd command computes the matrix singular value decomposition.
s = svd(X) returns a vector of singular values. [U,S,V] = svd(X) produces a diagonal matrix S of the same dimension as X,
with nonnegative diagonal elements in decreasing order, and unitary matrices U and V so that X = U*S*V'.
[U,S,V] = svd(X,0) produces the "economy size" decomposition. If X is m-by-n with m > n, then svd computes only the first n columns of U and S is n-by-n.
Examples
For the matrix
X = 1 3 5 7 2 4 6 8
the statement
[U,S,V] = svd(X)
produces
U = -0.1525 -0.3499 -0.5474 -0.7448 S = 14.2691 0 0 0.6268 -0.8226 -0.4214 -0.0201 0.3812 -0.3945 0.2428 0.6979 -0.5462 -0.3800 0.8007 -0.4614 0.0407
2-520
svd
0 0 V = -0.6414 -0.7672
0 0
0.7672 -0.6414
The economy size decomposition generated by
[U,S,V] = svd(X,0)
produces
U = -0.1525 -0.3499 -0.5474 -0.7448 S = 14.2691 0 V = -0.6414 -0.7672 0.7672 -0.6414 0 0.6268 -0.8226 -0.4214 -0.0201 0.3812
Algorithm
svd uses LAPACK routines to compute the singular value decomposition.
Matrix
Routine DGESVD ZGESVD
Real Complex
Diagnostics
If the limit of 75 QR step iterations is exhausted while seeking a singular value, this message appears:
Solution will not converge.
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
2-521
svd
(http://www.netlib.org/lapack/lug/lapack_lug.html), Third Edition, SIAM, Philadelphia, 1999.
2-522
svds
Purpose Syntax
2svds
A few singular values
s = svds(A) s = svds(A,k) s = svds(A,k,0) [U,S,V] = svds(A,...) svds(A) computes the five largest singular values and associated singular vectors of the matrix A. svds(A,k) computes the k largest singular values and associated singular vectors of the matrix A. svds(A,k,0) computes the k smallest singular values and associated singular
Description
vectors. With one output argument, s is a vector of singular values. With three output arguments and if A is m-by-n: U is m-by-k with orthonormal columns S is k-by-k diagonal V is n-by-k with orthonormal columns U*S*V' is the closest rank k approximation to A
Algorithm
svds(A,k) uses eigs to find the k largest magnitude eigenvalues and corresponding eigenvectors of B = [0 A; A' 0]. svds(A,k,0) uses eigs to find the 2k smallest magnitude eigenvalues and corresponding eigenvectors of B = [0 A; A' 0], and then selects the k positive eigenvalues and their eigenvectors.
Example
west0479 is a real 479-by-479 sparse matrix. svd calculates all 479 singular values. svds picks out the largest and smallest singular values. load west0479 s = svd(full(west0479)) sl = svds(west0479,4) ss = svds(west0479,6,0)
2-523
svds
These plots show some of the singular values of west0479 as computed by svd and svds.
3.19 3.185 3.18 3.175 3.17 3.165
x 10
5
4 largest singular values of west0479 svds(A,4) svd(A)
1
2
3
4
6 5 4 3 2 1 0
x 10
-5
6 smallest singular values of west0479
svds(A,6,0) svd(A) 1 2 3 4 5 6
The largest singular value of west0479 can be computed a few different ways:
svds(west0479,1) = 3.189517598808622e+05 max(svd(full(west0479))) = 3.18951759880862e+05 norm(full(west0479)) = 3.189517598808623e+05
and estimated:
normest(west0479) = 3.189385666549991e+05
See Also
svd, eigs
2-524
switch
Purpose Syntax
2switch
Switch among several cases based on expression
switch switch_expr case case_expr statement,...,statement case {case_expr1,case_expr2,case_expr3,...} statement,...,statement ... otherwise statement,...,statement end
Discussion
The switch statement syntax is a means of conditionally executing code. In particular, switch executes one set of statements selected from an arbitrary number of alternatives. Each alternative is called a case, and consists of: The case statement One or more case expressions One or more statements In its basic syntax, switch executes the statements associated with the first case where switch_expr == case_expr. When the case expression is a cell array (as in the second case above), the case_expr matches if any of the elements of the cell array match the switch expression. If no case expression matches the switch expression, then control passes to the otherwise case (if it exists). After the case is executed, program execution resumes with the statement after the end. The switch_expr can be a scalar or a string. A scalar switch_expr matches a case_expr if switch_expr==case_expr. A string switch_expr matches a case_expr if strcmp(switch_expr,case_expr) returns 1 (true).
Note for C Programmers Unlike the C language switch construct, the MATLAB switch does not "fall through." That is, switch executes only the first matching case, subsequent matching cases do not execute. Therefore, break statements are not used.
2-525
switch
Examples
To execute a certain block of code based on what the string, method, is set to,
method = 'Bilinear'; switch lower(method) case {'linear','bilinear'} disp('Method is linear') case 'cubic' disp('Method is cubic') case 'nearest' disp('Method is nearest') otherwise disp('Unknown method.') end Method is linear
See Also
case, end, if, otherwise, while
2-526
symamd
Purpose Syntax
2symamd
Symmetric approximate minimum degree permutation
p = symamd(S) p = symamd(S,knobs) [p,stats] = symamd(S) [p,stats] = symamd(S,knobs) p = symamd(S) for a symmetric positive definite matrix S, returns the permutation vector p such that S(p,p) tends to have a sparser Cholesky factor than S. To find the ordering for S, symamd constructs a matrix M such that spones(M'*M) = spones (S), and then computes p = colamd(M). The symamd
Description
function may also work well for symmetric indefinite matrices.
S must be square; only the strictly lower triangular part is referenced. knobs is a scalar. If S is n-by-n, rows and columns with more than knobs*n
entries are removed prior to ordering, and ordered last in the output permutation p. If the knobs parameter is not present, then knobs = spparms('wh_frac').
stats is an optional vector that provides data about the ordering and the validity of the matrix S. stats(1) stats(2) stats(3)
Number of dense or empty rows ignored by symamd Number of dense or empty columns ignored by symamd Number of garbage collections performed on the internal data structure used by symamd (roughly of size 8.4*nnz(tril(S,-1)) + 9n integers)
0 if the matrix is valid, or 1 if invalid
stats(4) stats(5) stats(6) stats(7)
Rightmost column index that is unsorted or contains duplicate entries, or 0 if no such column exists 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 Number of duplicate and out-of-order row indices
2-527
symamd
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 symamd. For this reason, symamd verifies that S is valid: If a row index appears two or more times in the same column, symamd 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, symamd 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, symamd cannot continue. It prints an error message, and returns no output arguments (p or stats) . The ordering is followed by a symmetric elimination tree post-ordering.
Note symamd tends to be faster than symmmd and tends to return a better ordering.
See Also References
colamd, colmmd, colperm, spparms, symmmd, symrcm
The authors of the code for symamd are Stefan I. Larimore and Timothy A. Davis (davis@cise.ufl.edu), 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-528
symbfact
Purpose Syntax
2symbfact
Symbolic factorization analysis
count = symbfact(A) count = symbfact(A,'col') count = symbfact(A,'sym') [count,h,parent,post,R] = symbfact(...) count = symbfact(A) returns the vector of row counts for the upper
Description
triangular Cholesky factor of a symmetric matrix whose upper triangle is that of A, assuming no cancellation during the factorization. symbfact should be much faster than chol(A).
count = symbfact(A,'col') analyzes A' *A (without forming it explicitly). count = symbfact(A,'sym') is the same as count = symbfact(A). [count,h,parent,post,R] = symbfact(...) has several optional return
values.
h parent post R
Height of the elimination tree The elimination tree itself Postordering permutation of the elimination tree 0-1 matrix whose structure is that of chol(A)
See Also
chol, etree, treelayout
2-529
symmlq
Purpose Syntax
2symmlq
Symmetric LQ method
x = symmlq(A,b) symmlq(A,b,tol) symmlq(A,b,tol,maxit) symmlq(A,b,tol,maxit,M) symmlq(A,b,tol,maxit,M1,M2) symmlq(A,b,tol,maxit,M1,M2,x0) symmlq(afun,b,tol,maxit,m1fun,m2fun,x0,p1,p2,...) [x,flag] = symmlq(A,b,...) [x,flag,relres] = symmlq(A,b,...) [x,flag,relres,iter] = symmlq(A,b,...) [x,flag,relres,iter,resvec] = symmlq(A,b,...) [x,flag,relres,iter,resvec,resveccg] = symmlq(A,b,...) x = symmlq(A,b) attempts to solve the system of linear equations A*x=b for x. The n-by-n coefficient matrix A must be symmetric but need not be positive definite. It should also 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.
Description
If symmlq converges, a message to that effect is displayed. If symmlq 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.
symmlq(A,b,tol) specifies the tolerance of the method. If tol is [], then symmlq uses the default, 1e-6. symmlq(A,b,tol,maxit) specifies the maximum number of iterations. If maxit is [], then symmlq uses the default, min(n,20). symmlq(A,b,tol,maxit,M) and symmlq(A,b,tol,maxit,M1,M2) use the symmetric positive definite preconditioner M or M = M1*M2 and effectively solve the system inv(sqrt(M))*A*inv(sqrt(M))*y = inv(sqrt(M))*b for y and then return x = inv(sqrt(M))*y. If M is [] then symmlq applies no preconditioner. M can be a function that returns M\x.
2-530
symmlq
symmlq(A,b,tol,maxit,M1,M2,x0) specifies the initial guess. If x0 is [], then symmlq uses the default, an all-zero vector. symmlq(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] = symmlq(A,b,tol,maxit,M1,M2,x0,p1,p2,...) also returns a
convergence flag.
Flag 0
Convergence symmlq converged to the desired tolerance tol within maxit iterations. symmlq iterated maxit times but did not converge.
1 2 3
Preconditioner M was ill-conditioned.
symmlq stagnated. (Two consecutive iterates were the
same.)
4
One of the scalar quantities calculated during symmlq became too small or too large to continue computing. Preconditioner M was not symmetric positive definite.
5
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] = symmlq(A,b,tol,maxit,M1,M2,x0,p1,p2,...) also returns the relative residual norm(b-A*x)/norm(b). If flag is 0, relres <= tol. [x,flag,relres,iter] = symmlq(A,b,tol,maxit,M1,M2,x0,p1,p2,...) also returns the iteration number at which x was computed, where 0 <= iter <= maxit.
2-531
symmlq
[x,flag,relres,iter,resvec] = symmlq(A,b,tol,maxit,M1,M2,x0,p1,p2,...) also returns a vector of estimates of the symmlq residual norms at each iteration, including norm(b-A*x0). [x,flag,relres,iter,resvec,resveccg] = symmlq(A,b,tol,maxit,M1,M2,x0,p1,p2,...) also returns a vector of
estimates of the conjugate gradients residual norms at each iteration.
Examples
Example 1.
n = 100; on = ones(n,1); A = spdiags([-2*on 4*on -2*on],-1:1,n,n); b = sum(A,2); tol = 1e-10; maxit = 50; M1 = spdiags(4*on,0,n,n); x = symmlq(A,b,tol,maxit,M1,[],[]); symmlq converged at iteration 49 to a solution with relative residual 4.3e-015
Alternatively, use this matrix-vector product function
function y = afun(x,n) y = 4 * x; y(2:n) = y(2:n) - 2 * x(1:n-1); y(1:n-1) = y(1:n-1) - 2 * x(2:n);
as input to symmlq.
x1 = symmlq(@afun,b,tol,maxit,M1,[],[],n);
Example 2.
Use a symmetric indefinite matrix that fails with pcg.
A = diag([20:-1:1,-1:-1:-20]); b = sum(A,2); % The true solution is the vector of all ones. x = pcg(A,b); % Errors out at the first iteration. pcg stopped at iteration 1 without converging to the desired tolerance 1e-006 because a scalar quantity became too small or too large to continue computing.
2-532
symmlq
The iterate returned (number 0) has relative residual 1
However, symmlq can handle the indefinite matrix A.
x = symmlq(A,b,1e-6,40); symmlq converged at iteration 39 to a solution with relative residual 1.3e-007
See Also
bicg, bicgstab, cgs, lsqr, gmres, minres, pcg, qmr @ (function handle), / (slash)
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] Paige, C. C. and M. A. Saunders, "Solution of Sparse Indefinite Systems of Linear Equations." SIAM J. Numer. Anal., Vol.12, 1975, pp. 617-629.
2-533
symmmd
Purpose Syntax Description
2symmmd
Sparse symmetric minimum degree ordering
p = symmmd(S) p = symmmd(S) returns a symmetric minimum degree ordering of S. For a symmetric positive definite matrix S, this is a permutation p such that S(p,p) tends to have a sparser Cholesky factor than S. Sometimes symmmd works well for symmetric indefinite matrices too.
Remarks
The minimum degree ordering is automatically used by \ and / for the solution of symmetric, positive definite, sparse linear systems. Some options and parameters associated with heuristics in the algorithm can be changed with spparms.
Algorithm
The symmetric minimum degree algorithm is based on the column minimum degree algorithm. In fact, symmmd(A) just creates a nonzero structure K such that K'*K has the same nonzero structure as A and then calls the column minimum degree code for K. Here is a comparison of reverse Cuthill-McKee and minimum degree on the Bucky ball example mentioned in the symrcm reference page.
B = bucky+4*speye(60); r = symrcm(B); p = symmmd(B); R = B(r,r); S = B(p,p); subplot(2,2,1), spy(R), title('B(r,r)') subplot(2,2,2), spy(S), title('B(s,s)') subplot(2,2,3), spy(chol(R)), title('chol(B(r,r))') subplot(2,2,4), spy(chol(S)), title('chol(B(s,s))')
Examples
2-534
symmmd
B(r,r) 0 0
B(s,s)
20
20
40
40
60 0
20 40 nz = 240 chol(B(r,r))
60
60 0
20 40 nz = 240 chol(B(s,s))
60
0
0
20
20
40
40
60 0
20 40 nz = 514
60
60 0
20 40 nz = 360
60
Even though this is a very small problem, the behavior of both orderings is typical. RCM produces a matrix with a narrow bandwidth which fills in almost completely during the Cholesky factorization. Minimum degree produces a structure with large blocks of contiguous zeros which do not fill in during the factorization. Consequently, the minimum degree ordering requires less time and storage for the factorization.
See Also References
colamd, colmmd, colperm, symamd, symrcm
[1] 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-535
symrcm
Purpose Syntax Description
2symrcm
Sparse reverse Cuthill-McKee ordering
r = symrcm(S) r = symrcm(S) returns the symmetric reverse Cuthill-McKee ordering of S. This is a permutation r such that S(r,r) tends to have its nonzero elements
closer to the diagonal. This is a good preordering for LU or Cholesky factorization of matrices that come from long, skinny problems. The ordering works for both symmetric and nonsymmetric S. For a real, symmetric sparse matrix, S, the eigenvalues of S(r,r) are the same as those of S, but eig(S(r,r)) probably takes less time to compute than eig(S).
Algorithm
The algorithm first finds a pseudoperipheral vertex of the graph of the matrix. It then generates a level structure by breadth-first search and orders the vertices by decreasing distance from the pseudoperipheral vertex. The implementation is based closely on the SPARSPAK implementation described by George and Liu. The statement
B = bucky
Examples
uses an M-file in the demos toolbox to generate the adjacency graph of a truncated icosahedron. This is better known as a soccer ball, a Buckminster Fuller geodesic dome (hence the name bucky), or, more recently, as a 60-atom carbon molecule. There are 60 vertices. The vertices have been ordered by numbering half of them from one hemisphere, pentagon by pentagon; then reflecting into the other hemisphere and gluing the two halves together. With this numbering, the matrix does not have a particularly narrow bandwidth, as the first spy plot shows
subplot(1,2,1), spy(B), title('B')
The reverse Cuthill-McKee ordering is obtained with
p = symrcm(B); R = B(p,p);
2-536
symrcm
The spy plot shows a much narrower bandwidth.
subplot(1,2,2), spy(R), title('B(p,p)')
B 0 10 20 30 40 50 60 0 0 10 20 30 40 50 60 0 B(p,p)
20
40 nz = 180
60
20
40 nz = 180
60
This example is continued in the reference pages for symmmd. The bandwidth can also be computed with
[i,j] = find(B); bw = max(i-j) + 1
The bandwidths of B and R are 35 and 12, respectively.
See Also References
colamd, colmmd, colperm, symamd, symmmd
[1] George, Alan and Joseph Liu, Computer Solution of Large Sparse Positive Definite Systems, Prentice-Hall, 1981. [2] Gilbert, John R., Cleve Moler, and Robert Schreiber, "Sparse Matrices in MATLAB: Design and Implementation," to appear in SIAM Journal on Matrix Analysis, 1992. A slightly expanded version is also available as a technical report from the Xerox Palo Alto Research Center.
2-537
symvar
Purpose Syntax Description
2symvar
Determine the symbolic variables in an expression
symvar 'expr' s = symvar('expr') symvar 'expr' searches the expression, expr, for identifiers other than i, j, pi, inf, nan, eps, and common functions. symvar displays those variables that it finds or, if no such variable exists, displays an empty cell array, {}. s = symvar('expr') returns the variables in a cell array of strings, s. If no such variable exists, s is an empty cell array.
Examples
symvar finds variables beta1 and x, but skips pi and the cos function. symvar 'cos(pi*x - beta1)' ans = 'beta1' 'x'
See Also
findstr
2-538
startup
Purpose Description
2startup
MATLAB startup M-file for user-defined options
startup automatically executes the master M-file matlabrc.m and, if it exists, startup.m, when MATLAB starts. On multiuser or networked systems, matlabrc.m is reserved for use by the system manager. The file matlabrc.m invokes the file startup.m if it exists on the MATLAB search path.
You can create a startup.m file in your own MATLAB directory. The file can include physical constants, Handle Graphics defaults, engineering conversion factors, or anything else you want predefined in your workspace. There are other way to predefine aspects of MATLAB. See "Startup Options" and "Setting Preferences" in the MATLAB documentation.
Algorithm
Only matlabrc.m is actually invoked by MATLAB at startup. However, matlabrc.m contains the statements
if exist('startup')==2 startup end
that invoke startup.m. You can extend this process to create additional startup M-files, if required.
See Also
matlabrc, matlabroot, quit
2-539
system
Purpose Description
2system
Run operating system command and return result
system('command') calls upon the operating system to run command, for example dir or ls, and directs the output to MATLAB. If command runs successfully, ans is 0. If command fails or does not exist on your operating system, ans is a nonzero value and an explanatory message appears. [status, result] = system('command') calls upon the operating system to run command, and directs the output to MATLAB. If command runs successfully, status is 0 and result contains the output from command. If command fails or does not exist on your operating system, status is a nonzero value, result is an empty matrix, and an explanatory message appears.
Examples
Display the current directory by accessing the operating system.
system('pwd')
MATLAB displays the current directory and shows that the command executed correctly because ans is 0.
D:/mymfiles/ ans = 0
Similarly, run the operating system pwd command and assign the current directory to curr_dir.
[s, curr_dir] = system('pwd')
MATLAB displays
s = 0 curr_dir = D:/mymfiles/
See Also
! (exclamation point), dos, perl, unix
2-540
tan
Purpose Syntax Description
2tan
Tangent
Y = tan(X)
The tan function operates element-wise on arrays. The function's domains and ranges include complex values. All angles are in radians.
Y = tan(X) returns the circular tangent of each element of X.
Examples
Graph the tangent function over the domain / 2 < x < / 2 .
x = (-pi/2)+0.01:0.01:(pi/2)-0.01; plot(x,tan(x)), grid on
100 80 60 40 20 0 -20 -40 -60 -80 -100 -2 -1.5 -1 -0.5 0 0.5 1 1.5 2
The expression tan(pi/2) does not evaluate as infinite but as the reciprocal of the floating point accuracy eps since pi is only a floating-point approximation to the exact value of .
Definition
The tangent can be defined as sin ( z ) tan ( z ) = ---------------cos ( z )
2-541
tan
Algorithm
tan 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
atan, atan2, tanh
2-542
tanh
Purpose Syntax Description
2tanh
Hyperbolic tangent
Y = tanh(X)
The tanh function operates element-wise on arrays. The function's domains and ranges include complex values. All angles are in radians.
Y = tanh(X) returns the hyperbolic tangent of each element of X.
Examples
Graph the hyperbolic tangent function over the domain 5 x 5 .
x = -5:0.01:5; plot(x,tanh(x)), grid on
1 0.8 0.6 0.4 0.2 0 -0.2 -0.4 -0.6 -0.8 -1 -5 0 5
Definition
The hyperbolic tangent can be defined as sinh ( z ) tanh ( z ) = ------------------cosh ( z )
Algorithm
tanh 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-543
tanh
See Also
atan, atan2, tan
2-544
tempdir
Purpose Syntax Description
2tempdir
Return the name of the system's temporary directory
tmp_dir = tempdir tmp_dir = tempdir returns the name of the system's temporary directory, if
one exists. This function does not create a new directory. See Opening Temporary Files and Directories for more information.
See Also
tempname
2-545
tempname
Purpose Syntax Description
2tempname
Unique name for temporary file
tmp_nam = tempname tmp_nam = tempname returns a unique string, tmp_nam, suitable for use as a
temporary filename.
Note The filename that tempname generates is not guaranteed to be unique; however, it is likely to be so.
See Opening Temporary Files and Directories for more information.
See Also
tempdir
2-546
terminal
Purpose
2terminal
Set graphics terminal type
Note The terminal function will be removed in a future release.
Syntax Description
terminal terminal('type')
To add terminal-specific settings (e.g., escape characters, line length), edit the file terminal.m.
terminal displays a menu of graphics terminal types, prompts for a choice,
then configures MATLAB to run on the specified terminal.
terminal('type') accepts a terminal type string. Valid 'type' strings are
shown in the table.
Type tek401x tek4100 tek4105 retro sg100 sg200 vt240tek ergo graphon citoh xtermtek Description
Tektronix 4010/4014 Tektronix 4100 Tektronix 4105 Retrographics card Selanar Graphics 100 Selanar Graphics 200 VT240 & VT340 Tektronix mode Ergo terminal Graphon terminal C.Itoh terminal xterm, Tektronix graphics
2-547
terminal
Type wyse kermit hp2647 hds
Description (Continued)
Wyse WY-99GT MS-DOS Kermit 2.23 Hewlett-Packard 2647 Human Designed Systems
2-548
tetramesh
Purpose Syntax
2tetramesh
Tetrahedron mesh plot
tetramesh(T,X,c) tetramesh(T,X) h = tetramesh(...) tetramesh(...,'param','value','param','value'...) tetramesh(T,X,c) displays the tetrahedrons defined in the m-by-4 matrix T as mesh. T is usually the output of delaunayn. A row of T contains indices into X of the vertices of a tetrahedron. X is an n-by-3 matrix, representing n points in 3 dimension. The tetrahedron colors are defined by the vector C, which is used as indices into the current colormap.
Description
Note If T is the output of delaunay3, then X is the concatenation of the delaunay3 input arguments x, y, z interpreted as column vectors, i.e., X = [x(:) y(:) z(:)].
tetramesh(T,X) uses C = 1:m as the color for the m tetrahedrons. Each
tetrahedron has a different color (modulo the number of colors available in the current colormap).
h = tetramesh(...) returns a vector of tetrahedron handles. Each element of h is a handle to the set of patches forming one tetrahedron. You can use these handles to view a particular tetrahedron by turning the patch 'Visible' property 'on' or 'off'. tetramesh(...,'param','value','param','value'...) allows additional patch property name/property value pairs to be used when displaying the tetrahedrons. For example, the default transparency parameter is set to 0.9. You can overwrite this value by using the property name/property value pair ('FaceAlpha',value) where value is a number between 0 and 1. See Patch Properties for information about the available properties.
Examples
Generate a 3-dimensional Delaunay tesselation, then use tetramesh to visualize the tetrahedrons that form the corresponding simplex.
d = [-1 1];
2-549
tetramesh
[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 8 8 8 8
1 9 9 3 3 9 3 7 2 2 3 7
5 1 1 9 9 5 9 9 9 9 9 3
6 5 6 4 1 6 5 6 6 4 4 9
tetramesh(Tes,X);camorbit(20,0)
2-550
tetramesh
See Also
delaunayn, patch, Patch Properties, trimesh, trisurf
2-551
texlabel
Purpose Syntax Description
2texlabel
Produce TeX format from character string
texlabel(f) texlabel(f,'literal') texlabel(f) converts the MATLAB expression f into the TeX equivalent for
use in text strings. It processes Greek variable names (e.g., lambda, delta, etc.) into a string that displays as actual Greek letters.
texlabel(f,'literal') prints Greek variable names as literals.
If the string is too long to fit into a figure window, then the center of the expression is replaced with a tilde ellipsis (~~~).
Examples
You can use texlabel as an argument to the title, xlabel, ylabel, zlabel, and text commands. For example,
title(texlabel('sin(sqrt(x^2 + y^2))/sqrt(x^2 + y^2)'))
By default, texlabel translates Greek variable names to the equivalent Greek letter. You can select literal interpretation by including the literal argument. For example, compare these two commands.
text(.5,.5,... texlabel('lambda12^(3/2)/pi - pi*delta^(2/3)')) text(.25,.25,... texlabel('lambda12^(3/2)/pi - pi*delta^(2/3)','literal'))
2-552
texlabel
1
0.9
0.8
0.7
0.6
0.5
3/2 / 12
- 2/3
0.4
0.3
lambda12
0.2
3/2
/pi - pi delta
2/3
0.1
0
0
0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.8
0.9
1
See Also
text, title, xlabel, ylabel, zlabel, the text String property
"Annotating Plots" for related functions
2-553
text
Purpose Syntax
2text
Create text object in current axes
text(x,y,'string') text(x,y,z,'string') text(...'PropertyName',PropertyValue...) h = text(...) text is the low-level function for creating text graphics objects. Use text to
Description
place character strings at specified locations.
text(x,y,'string') adds the string in quotes to the location specified by the point (x,y). text(x,y,z,'string') adds the string in 3-D coordinates. text(x,y,z,'string','PropertyName',PropertyValue....) adds the string
in quotes to location defined by the coordinates and uses the values for the specified text properties. See the text property list section at the end of this page for a list of text properties.
text('PropertyName',PropertyValue....) omits the coordinates entirely
and specifies all properties using property name/property value pairs.
h = text(..) returns a column vector of handles to text objects, one handle per object. All forms of the text function optionally return this output
argument. See the String property for a list of symbols, including Greek letters.
Remarks
Specify the text location coordinates (the x, y, and z arguments) in the data units of the current axes (see "Examples"). The Extent, VerticalAlignment, and HorizontalAlignment properties control the positioning of the character string with regard to the text location point. If the coordinates are vectors, text writes the string at all locations defined by the list of points. If the character string is an array the same length as x, y, and z, text writes the corresponding row of the string array at each point specified. When specifying strings for multiple text objects, the string can be a cell array of strings
2-554
text
a padded string matrix a string vector using vertical slash characters (`|') as separators. Each element of the specified string array creates a different text object. When specifying the string for a single text object, cell arrays of strings and padded string matrices result in a text object with a multiline string, while vertical slash characters are not interpreted as separators and result in a single line string containing vertical slashes.
text is a low-level function that accepts property name/property value pairs as
input arguments, however; the convenience form,
text(x,y,z,'string')
is equivalent to:
text('XData',x,'YData',y,'ZData',z,'String','string')
You can specify other properties only as property name/property value pairs. See the text property list at the end of this page for a description of each property. You can specify properties as property name/property value pairs, structure arrays, and cell arrays (see the set and get reference pages for examples of how to specify these data types).
text does not respect the setting of the figure or axes NextPlot property. This allows you to add text objects to an existing axes without setting hold to on.
Examples
The statements,
plot(0:pi/20:2*pi,sin(0:pi/20:2*pi)) text(pi,0,' \leftarrow sin(\pi)','FontSize',18)
2-555
text
annotate the point at (pi,0) with the string sin().
1
0.8
0.6
0.4
0.2
0
sin()
-0.2
-0.4
-0.6
-0.8
-1
0
1
2
3
4
5
6
7
The statement,
text(x,y,'\ite^{i\omega\tau} = cos(\omega\tau) + i sin(\omega\tau)')
uses embedded TeX sequences to produce:
i e = cos() + i sin()
See Also
gtext, int2str, num2str, title, xlabel, ylabel, zlabel
The "Labeling Graphs" topic in the online Using MATLAB Graphics manual discusses positioning text.
2-556
text
Object Hierarchy
Root
Figure
Axes
Uicontrol
Uimenu
Uicontextmenu
Image
Light
Line
Patch
Rectangle
Surface
Text
Setting Default Properties
You can set default text properties on the axes, figure, and root levels.
set(0,'DefaulttextProperty',PropertyValue...) set(gcf,'DefaulttextProperty',PropertyValue...) set(gca,'DefaulttextProperty',PropertyValue...)
Where Property is the name of the text property and PropertyValue is the value you are specifying. Use set and get to access text properties.
Property List
The following table lists all text properties and provides a brief description of each. The property name links take you to an expanded description of the properties.
Property Description Property Value
Property Name
Defining the character string Editing
Enable or disable editing mode. Enable or disable TeX interpretation The character string (including list of TeX character sequences)
Values: on, off Default: off Values: tex, none Default: tex Value: character string
Interpreter
String
2-557
text
Property Name
Property Description
Property Value
Positioning the character string Extent
Position and size of text object Horizontal alignment of text string Position of text Extent rectangle Orientation of text object Units for Extent and Position properties
Values: [left, bottom, width, height] Values: left, center, right Default: left Values: [x, y, z] coordinates Default: [] empty matrix Values: scalar (degrees) Default: 0 Values: pixels, normalized, inches, centimeters, points, data Default: data Values: top, cap, middle, baseline, bottom Default: middle
HorizontalAlignment
Position
Rotation
Units
VerticalAlignment
Vertical alignment of text string
Text Bounding Box BackgroundColor
Color of text extent rectangle Color of edge drawn around text extent rectangle Width of the line (in points) use to draw the box drawn around text extent rectangle Style of the line use to draw the box drawn around text extent rectangle Distance in pixels from the text extent to the edge of the box enclosing the text.
Values: ColorSpec Default: none Values: ColorSpec Default: none Values: scalar (points) Default: 0.5 Values: -, --, :, -., none Default: - Values: scalar (pixels) Default: 2
EdgeColor
LineWidth
LineStyle
Margin
2-558
text
Property Name Specifying the Font FontAngle
Property Description
Property Value
Select italic-style font
Values: normal, italic, oblique Default: normal Values: a font supported by your system or the string
FixedWidth Default: Helvetica
FontName
Select font family
FontSize
Size of font Units for FontSize property
Values: size in FontUnits Default: 10 points Values: points, normalized, inches, centimeters, pixels Default: points Values: light, normal, demi,
bold
FontUnits
FontWeight
Weight of text characters
Default: normal
Controlling the Appearance Clipping
Clipping to axes rectangle Method of drawing and erasing the text (useful for animation) Highlight text when selected (Selected property set to on) Make the text visible or invisible Color of the text
Values: on, off Default: on Values: normal, none, xor,
background Default: normal
EraseMode
SelectionHighlight
Values: on, off Default: on Values: on, off Default: on
ColorSpec
Visible
Color
Controlling Access to Text Objects
2-559
text
Property Name HandleVisibility
Property Description
Property Value
Determines if and when the the text's handle is visible to other functions Determines if the text can become the current object (see the figure CurrentObject property)
Values: on, callback, off Default: on Values: on, off Default: on
HitTest
General Information About Text Objects Children Parent
Text objects have no children The parent of a text object is always an axes object Indicate whether the text is in a "selected" state. User-specified label The type of graphics object (read only) User-specified data
Values: [] (empty matrix) Value: axes handle Values: on, off Default: off Value: any string Default: '' (empty string) Value: the string 'text' Values: any matrix Default: [] (empty matrix)
Selected
Tag
Type
UserData
Controlling Callback Routine Execution BusyAction
Specifies how to handle callback routine interruption Defines a callback routine that executes when a mouse button is pressed on over the text Defines a callback routine that executes when an text is created
Values: cancel, queue Default: queue Values: string or function handle Default: '' (empty string) Values: string or function handle Default: '' (empty string)
ButtonDownFcn
CreateFcn
2-560
text
Property Name DeleteFcn
Property Description
Property Value
Defines a callback routine that executes when the text is deleted (via close or delete) Determines if callback routine can be interrupted Associates a context menu with the text
Values: string or function handle Default: '' (empty string) Values: on, off Default: on (can be interrupted) Values: handle of a uicontextmenu
Interruptible
UIContextMenu
2-561
Text Properties
Modifying Properties
2Text Properties
You can set and query graphics object properties using the property editor or the set and get commands. 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.
Text Property Descriptions
This section lists property names along with the types of values each accepts. Curly braces { } enclose default values.
BackgroundColor ColorSpec | {none}
Color of text extent rectangle. This property enables you define a color for the rectangle that encloses the text Extent. For example, the following code creates a text object that labels a plot and sets the background color to light green.
text(3*pi/4,sin(3*pi/4),... ['sin(3*pi/4) = ',num2str(sin(3*pi/4))],... 'HorizontalAlignment','center',... 'BackgroundColor',[.7 .9 .7]);
1 0.8 0.6 0.4 0.2 0 -0.2 -0.4 -0.6 -0.8 -1 0 1 2 3 4 5 6 7 sin(3*pi/4) = 0.70711
For additional features, see the following properties: EdgeColor -- Color of the rectangle's edge (none by default). LineStyle -- Style of the rectangle's edge line (first set EdgeColor).
2-562
Text Properties
LineWidth -- Width of the rectangle's edge line (first set EdgeColor) Margin -- Increase the size of the rectangle by adding a margin to the existing text extent rectangle. See also "Drawing Text in a Box" in the MATLAB Graphics documentation for an example using background color with contour labels.
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 set to 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 over the text object. 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.
Children
matrix (read only)
The empty matrix; text objects have no children.
Clipping on | {off}
Clipping mode. When Clipping is on, MATLAB does not display any portion of the text that is outside the axes.
2-563
Text Properties
Color
ColorSpec
Text color. A three-element RGB vector or one of the predefined names, specifying the text color. The default value for Color is white. See ColorSpec for more information on specifying color.
CreateFcn
string or function handle
Callback routine executed during object creation. This property defines a callback routine that executes when MATLAB creates a text object. You must define this property as a default value for text. For example, the statement,
set(0,'DefaultTextCreateFcn',... 'set(gcf,''Pointer'',''crosshair'')')
defines a default value on the root level that sets the figure Pointer property to a crosshair whenever you create a text object. MATLAB executes this routine after setting all text properties. Setting this property on an existing text object has no effect. The handle of the object whose CreateFcn is being executed is accessible only through the root CallbackObject property, which you can query using gcbo. See Function Handle Callbacks for information on how to use function handles to define the callback function.
DeleteFcn
string or function handle
Delete text callback routine. A callback routine that executes when you delete the text object (e.g., when you issue a delete command or clear the axes or figure). MATLAB executes the routine before destroying the object's properties so these values are available to the callback routine. The handle of the object whose DeleteFcn is being executed is accessible only through the root CallbackObject property, which you can query using gcbo. See Function Handle Callbacks for information on how to use function handles to define the callback function.
EdgeColor ColorSpec | {none}
Color of edge drawn around text extent rectangle. This property enables you to specify the color of a box drawn around the text Extent. For example, the following code draws a red rectangle around text that labels a plot.
text(3*pi/4,sin(3*pi/4),...
2-564
Text Properties
'\leftarrowsin(t) = .707',... 'EdgeColor','red');
1 0.8 0.6 0.4 0.2 0 -0.2 -0.4 -0.6 -0.8 -1 0 1 2 3 4 5 6 7 sin(t) = .707
For additional features, see the following properties: BackgroundColor -- Color of the rectangle's interior (none by default). LineStyle -- Style of the rectangle's edge line (first set EdgeColor). LineWidth -- Width of the rectangle's edge line (first set EdgeColor) Margin -- Increase the size of the rectangle by adding a margin to the existing text extent rectangle.
Editing on | {off}
Enable or disable editing mode. When this property is set to the default off, you cannot edit the text string interactively (i.e., you must change the String property to change the text). When this property is set to on, MATLAB places an insert cursor at the beginning of the text string and enables editing. To apply the new text string
1 Press the ESC key. 2 Clicking in any figure window (including the current figure). 3 Reset the Editing property to off.
MATLAB then updates the String property to contain the new text and resets the Editing property to off. You must reset the Editing property to on to resume editing.
2-565
Text Properties
EraseMode
{normal} | none | xor | background
Erase mode. This property controls the technique MATLAB uses to draw and erase text objects. Alternative erase modes are useful for creating animated sequences where controlling the way individual objects redraw is necessary to improve performance and obtain the desired effect. normal -- Redraw the affected region of the display, performing the three-dimensional analysis necessary to ensure that all objects are rendered correctly. This mode produces the most accurate picture, but is the slowest. The other modes are faster, but do not perform a complete redraw and are therefore, less accurate. none -- Do not erase the text when it is moved or destroyed. While the object is still visible on the screen after erasing with EraseMode none, you cannot print it because MATLAB stores no information about its former location. xor -- Draw and erase the text by performing an exclusive OR (XOR) with each pixel index of the screen beneath it. When the text is erased, it does not damage the objects beneath it. However, when text is drawn in xor mode, its color depends on the color of the screen beneath it. It is correctly colored only when over axes background Color, or the figure background Color if the axes Color is set to none. background -- Erase the text by drawing it in the axes background Color, or the figure background Color if the axes Color is set to none. This damages objects that are behind the erased text, but text is always properly colored.
Printing with Nonnormal Erase Modes. MATLAB always prints figures as if the EraseMode of all objects is set to normal. This means graphics objects created with EraseMode set to none, xor, or background can look differently on screen
than on paper. On screen, MATLAB may mathematically combine layers of colors (e.g., XORing a pixel color with that of the pixel behind it) and ignore three-dimensional sorting to obtain greater rendering speed. However, these techniques are not applied to the printed output. You can use the MATLAB getframe command or other screen capture application to create an image of a figure containing nonnormal mode objects.
Extent
position rectangle (read only)
Position and size of text. A four-element read-only vector that defines the size and position of the text string
2-566
Text Properties
[left,bottom,width,height]
If the Units property is set to data (the default), left and bottom are the x and y coordinates of the lower left corner of the text Extent. For all other values of Units, left and bottom are the distance from the lower left corner of the axes position rectangle to the lower left corner of the text Extent. width and height are the dimensions of the Extent rectangle. All measurements are in units specified by the Units property.
FontAngle {normal} | italic | oblique
Character slant. MATLAB uses this property to select a font from those available on your particular system. Generally, setting this property to italic or oblique selects a slanted font.
FontName
A name, such as Courier, or the string FixedWidth
Font family. A string specifying the name of the font to use for the text object. To display and print properly, this must be a font that your system supports. The default font is Helvetica.
Specifying a Fixed-Width Font
If you want text to use a fixed-width font that looks good in any locale, you should set FontName to the string FixedWidth:
set(text_handle,'FontName','FixedWidth')
This eliminates the need to hard code 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.
2-567
Text Properties
FontSize
size in FontUnits
Font size. An integer specifying the font size to use for text in units determined by the FontUnits property. The default point size is 10 (1 point = 1/72 inch).
FontWeight light | {normal} | demi | bold
Weight of text characters. MATLAB uses this property to select a font from those available on your particular system. Generally, setting this property to bold or demi causes MATLAB to use a bold font.
FontUnits {points} | normalized | inches | centimeters | pixels
Font size units. MATLAB uses this property to determine the units used by the FontSize property. Normalized units interpret FontSize as a fraction of the height of the parent axes. When you resize the axes, MATLAB modifies the screen FontSize accordingly. pixels, inches, centimeters, and points are absolute units (1 point = 1/72 inch).
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 set to 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-568
Text 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. 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 text 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 text. If HitTest is set to off, clicking on the text selects the object below it (which is usually the axes containing it). For example, suppose you define the button down function of an image (see the
ButtonDownFcn property) to display text at the location you click on with the
mouse. First define the callback routine.
function bd_function pt = get(gca,'CurrentPoint'); text(pt(1,1),pt(1,2),pt(1,3),... '{\fontsize{20}\oplus} The spot to label',... 'HitTest','off')
Now display an image, setting its ButtonDownFcn property to the callback routine.
load earth image(X,'ButtonDownFcn','bd_function'); colormap(map)
When you click on the image, MATLAB displays the text string at that location. With HitTest set to off, existing text cannot intercept any subsequent button
2-569
Text Properties
down events that occur over the text. This enables the image's button down function to execute.
HorizontalAlignment{left} | center | right
Horizontal alignment of text. This property specifies the horizontal justification of the text string. It determines where MATLAB places the string with regard to the point specified by the Position property. The following picture illustrates the alignment options.
HorizontalAlignment viewed with the VerticalAlignment set to middle
(the default).
Left
Center
Right
See the Extent property for related information.
Interpreter {tex} | none
Interpret Tex instructions. This property controls whether MATLAB interprets certain characters in the String property as Tex instructions (default) or displays all characters literally. See the String property for a list of supported Tex instructions.
Interruptible {on} | off
Callback routine interruption mode. The Interruptible property controls whether a text callback routine can be interrupted by subsequently invoked callback routines. Text objects have three properties that define callback routines: ButtonDownFcn, CreateFcn, and DeleteFcn. See the BusyAction property for information on how MATLAB executes callback routines.
LineStyle {-} | -- | : | -. | none
Edge line type. This property determines the line style used to draw the edges of the text Extent. The available line styles are shown in the following table.
Symbol - Line Style
solid line (default) dashed line
--
2-570
Text Properties
Symbol : -. none
Line Style
dotted line dash-dot line no line
For example, the following code draws a red rectangle wth a dotted line style around text that labels a plot.
text(3*pi/4,sin(3*pi/4),... '\leftarrowsin(t) = .707',... 'EdgeColor','red',... 'LineWidth',2,... 'LineStyle',':');
1 0.8 0.6 0.4 0.2 0 -0.2 -0.4 -0.6 -0.8 -1 0 1 2 3 4 5 6 7 sin(t) = .707
For additional features, see the following properties: BackgroundColor -- Color of the rectangle's interior (none by default) EdgeColor -- Color of the rectangle's edge (none by default) LineWidth -- Width of the rectangle's edge line (first set EdgeColor) Margin -- Increase the size of the rectangle by adding a margin to the existing text extent rectangle
2-571
Text Properties
LineWidth
scalar (points)
Width of line used to draw text extent rectangle. When you set the text EdgeColor property to a color (the default is none), MATLAB displays a rectangle around the text Extent. Use the LineWidth property to specify the width of the rectangle edge. For example, the following code draws a red rectangle around text that labels a plot and specifies a line width of 3 points:
text(3*pi/4,sin(3*pi/4),... '\leftarrowsin(t) = .707',... 'EdgeColor','red',... 'LineWidth',3);
1 0.8 0.6 0.4 0.2 0 -0.2 -0.4 -0.6 -0.8 -1 0 1 2 3 4 5 6 7 sin(t) = .707
For additional features, see the following properties: BackgroundColor -- Color of the rectangle's interior (none by default) EdgeColor -- Color of the rectangle's edge (none by default) LineStyle -- style of the rectangle's edge line (first set EdgeColor) Margin -- increase the size of the rectangle by adding a margin to the exsiting text extent rectangle
Margin
scalar (pixels)
Distance between the text extent and the rectangle edge. When you specify a color for the BackgroundColor or EdgeColor text properties, MATLAB draws a rectangle around the area defined by the text Extent plus the value specified
2-572
Text Properties
by the Margin. For example, the following code displays a light green rectangle with a 10-pixel margin.
text(5*pi/4,sin(5*pi/4),... ['sin(5*pi/4) = ',num2str(sin(5*pi/4))],... 'HorizontalAlignment','center',... 'BackgroundColor',[.7 .9 .7],... 'Margin',10);
1 0.8 0.6 0.4 0.2 0 -0.2 -0.4 -0.6 -0.8 -1 0 1 sin(5*pi/4) = -0.70711 2 3 4 5 6 7
For additional features, see the following properties: BackgroundColor -- Color of the rectangle's interior (none by default) EdgeColor -- Color of the rectangle's edge (none by default) LineStyle -- Style of the rectangle's edge line (first set EdgeColor) LineWidth -- Width of the rectangle's edge line (first set EdgeColor)
Parent
handle
Text object's parent. The handle of the text object's parent object. The parent of a text object is the axes in which it is displayed. You can move a text object to another axes by setting this property to the handle of the new parent.
Position [x,y,[z]]
Location of text. A two- or three-element vector, [x y [z]], that specifies the location of the text in three dimensions. If you omit the z value, it defaults to 0. All measurements are in units specified by the Units property. Initial value is [0 0 0].
2-573
Text Properties
Rotation
scalar (default = 0)
Text orientation. This property determines the orientation of the text string. Specify values of rotation in degrees (positive angles cause counterclockwise rotation).
Selected on | {off}
Is object selected? When this property is set to on, MATLAB displays selection handles if the SelectionHighlight property is also set to on. You can, for example, define the ButtonDownFcn to set this property, allowing users to select the object with the mouse.
SelectionHighlight {on} | off
Objects highlight when selected. When the Selected property is set to on, MATLAB indicates the selected state by drawing four edge handles and four corner handles. When SelectionHighlight is set to off, MATLAB does not draw the handles.
String
string
The text string. Specify this property as a quoted string for single-line strings, or as a cell array of strings, or a padded string matrix for multiline strings. MATLAB displays this string at the specified location. Vertical slash characters are not interpreted as linebreaks in text strings, and are drawn as part of the text string. See Mathematical Symbols, Greek Letters, and TeX Characters for an example. When the text Interpreter property is set to Tex (the default), you can use a subset of TeX commands embedded in the string to produce special characters such as Greek letters and mathematical symbols. The following table lists these characters and the character sequences used to define them.
Character Sequence \alpha \beta \gamma \delta Symbol Character Sequence \upsilon \phi \chi \psi Symbol Character Sequence \sim \leq \infty \clubsuit Symbol
2-574
Text Properties
Character Sequence \epsilon \zeta \eta \theta \vartheta \iota \kappa \lambda \mu \nu \xi \pi \rho \sigma \varsigma \tau \equiv \Im \otimes \cap \supset \int
Symbol
Character Sequence \omega \Gamma \Delta \Theta \Lambda \Xi \Pi \Sigma \Upsilon \Phi \Psi \Omega \forall \exists \ni \cong \approx \Re \oplus \cup \subseteq \in
Symbol
Character Sequence \diamondsuit \heartsuit \spadesuit \leftrightarrow \leftarrow \uparrow \rightarrow \downarrow \circ \pm \geq \propto \partial \bullet \div \neq \aleph \wp \oslash \supseteq \subset \o
Symbol
2-575
Text Properties
Character Sequence \rfloor
Symbol
Character Sequence \lceil
Symbol
Character Sequence \nabla
Symbol
... |
\lfloor
\perp
\cdot \neg \times \surd \varpi \rangle
\ldots \prime \0 \mid \copyright
\wedge \rceil \vee \langle
You can also specify stream modifiers that control the font used. The first four modifiers are mutually exclusive. However, you can use \fontname in combination with one of the other modifiers: \bf -- bold font \it -- italics font \sl -- oblique font (rarely available) \rm -- normal font \fontname{fontname} -- specify the name of the font family to use. \fontsize{fontsize} -- specify the font size in FontUnits. Stream modifiers remain in effect until the end of the string or only within the context defined by braces { }.
Specifying Subscript and Superscript Characters
The subscript character "_" and the superscript character "^" modify the character or substring defined in braces immediately following. To print the special characters used to define the Tex strings when Interpreter is Tex, prefix them with the backslash "\" character: \\, \{, \} \_, \^. See the example in the text reference page for more information.
2-576
Text Properties
When Interpreter is set to none, no characters in the String are interpreted, and all are displayed when the text is drawn.
Tag
string
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. You can define Tag as any string.
Type
string (read only)
Class of graphics object. For text objects, Type is always the string 'text'.
Units pixels | normalized | inches | centimeters | points | {data}
Units of measurement. This property specifies the units MATLAB uses to interpret the Extent and Position properties. All units are measured from the lower left corner of the axes plotbox. Normalized units map the lower left corner of the rectangle defined by the axes to (0,0) and the upper right corner to (1.0,1.0). pixels, inches, centimeters, and points are absolute units (1 point = 1/72 inch). data refers to the data units of the parent axes. If you change the value of Units, it is good practice to return it to its default value after completing your computation so as not to affect other functions that assume Units is set to the default value.
UserData
matrix
User-specified data. Any data you want to associate with the text object. MATLAB does not use this data, but you can access it using set and get.
UIContextMenu
handle of a uicontextmenu object
Associate a context menu with the text. Assign this property the handle of a uicontextmenu object created in the same figure as the text. Use the uicontextmenu function to create the context menu. MATLAB displays the context menu whenever you right-click over the text.
2-577
Text Properties
VerticalAlignment top | cap | {middle} | baseline | bottom
Vertical alignment of text. This property specifies the vertical justification of the text string. It determines where MATLAB places the string with regard to the value of the Position property. The possible values mean top -- Place the top of the string's Extent rectangle at the specified y-position. cap -- Place the string so that the top of a capital letter is at the specified y-position. middle -- Place the middle of the string at specified y-position. baseline -- Place font baseline at the specified y-position. bottom -- Place the bottom of the string's Extent rectangle at the specified y-position. The following picture illustrates the alignment options. Text VerticalAlignment property viewed with the HorizontalAlignment property set to left (the default).
Middle Baseline
Visible
Top Bottom
{on} | off
Cap
Text visibility. By default, all text is visible. When set to off, the text is not visible, but still exists and you can query and set its properties.
2-578
textread
Purpose Graphical Interface Syntax
2textread
Read formatted data from text file As an alternative to textread, use the Import Wizard. To activate the Import Wizard, select Import Data from the File menu.
[A,B,C,...] = textread('filename','format') [A,B,C,...] = textread('filename','format',N) [...] = textread(...,'param','value',...) [A,B,C,...] = textread('filename','format') reads data from the file 'filename' into the variables A,B,C, and so on, using the specified format, until the entire file is read. textread is useful for reading text files with a
Description
known format. Both fixed and free format files can be handled.
textread matches and converts groups of characters from the input. Each
input field is defined as a string of non-whitespace characters that extends to the next whitespace or delimiter character, or to the maximum field width. Repeated delimiter characters are significant, while repeated whitespace characters are treated as one. The format string determines the number and types of return arguments. The number of return arguments is the number of items in the format string. The format string supports a subset of the conversion specifiers and conventions of the C language fscanf routine. Values for the format string are listed in the table below. Whitespace characters in the format string are ignored.
format Action Output
Literals (ordinary characters)
Ignore the matching characters. For example, in a file that has Dept followed by a number (for department number), to skip the Dept and read only the number, use 'Dept' in the format string. Read a signed integer value. Read an integer value. Read a floating point value.
None
%d %u %f
Double array Double array Double array
2-579
textread
format %s
Action
Output
Read a whitespace or delimiterseparated string. Read a string, which could be in double quotes.
Cell array of strings Cell array of strings. Does not include the double quotes. Character array Cell array of strings
%q
%c
Read characters, including white space. Read the longest string containing characters specified in the brackets. Read the longest non-empty string containing characters that are not specified in the brackets. Ignore the matching characters specified by *. Read field width specified by w. The %f format supports %w.pf, where w is the field width and p is the precision.
%[...]
%[^...]
Cell array of strings
%*...
No output
instead of %
%w...
instead of %
[A,B,C,...] = textread('filename','format',N) reads the data, reusing the format string N times, where N is an integer greater than zero. If N is smaller than zero, textread reads the entire file.
2-580
textread
[...] = textread(...,'param','value',...) customizes textread using param/value pairs, as listed in the table below. param whitespace value Any from the list below: ' ' \b \n \r \t delimiter Action
Treats vector of characters as whitespace. Default is ' \b\t'. Space Backspace New line Carriage return Horizontal tab Specifies delimiter character. Default is none. Default is eEdD. Specifies the maximum string length, in bytes. Default is 4095. Ignores the specified number of lines at the beginning of the file. Ignores characters after % Ignores characters after #. Ignores characters between /* and */. Ignores characters after //.
Delimiter character Exponent characters positive integer positive integer
matlab shell c c++
expchars
bufsize
headerlines
commentstyle commentstyle commentstyle commentstyle
Note When textread reads a consecutive series of whitespace values, it treats them as one whitespace. When it reads a consecutive series of delimiter values, it treats each as a separate delimiter.
2-581
textread
Examples Example 1 Read All Fields in Free Format File Using %
The first line of mydata.dat is
Sally Type1 12.34 45 Yes
Read the first line of the file as a free format file using the % format.
[names,types,x,y,answer] = textread('mydata.dat','%s %s %f ... %d %s',1)
returns
names = 'Sally' types = 'Type1' x = 12.34000000000000 y = 45 answer = 'Yes'
Example 2 Read as Fixed Format File, Ignoring the Floating Point Value
The first line of mydata.dat is
Sally Type1 12.34 45 Yes
Read the first line of the file as a fixed format file, ignoring the floating point value.
[names,types,y,answer] = textread('mydata.dat','%9c %5s %*f ... %2d %3s',1)
returns
names = Sally types = 'Type1' y = 45 answer =
2-582
textread
'Yes' %*f in the format string causes textread to ignore the floating point value, in this case, 12.34.
Example 3 Read Using Literal to Ignore Matching Characters
The first line of mydata.dat is
Sally Type1 12.34 45 Yes
Read the first line of the file, ignoring the characters Type in the second field.
[names,typenum,x,y,answer] = textread('mydata.dat','%s Type%d %f %d %s',1)
returns
names = 'Sally' typenum = 1 x = 12.34000000000000 y = 45 answer = 'Yes' Type%d in the format string causes the characters Type in the second field to be
ignored, while the rest of the second field is read as a signed integer, in this case, 1.
Example 4 Read M-file into a Cell Array of Strings
Read the file fft.m into cell array of strings.
file = textread('fft.m','%s','delimiter','\n','whitespace','');
See Also
dlmread, csvread, fscanf
ts and you can query and set its properties.
2-583
textwrap
Purpose Syntax Description
2textwrap
Return wrapped string matrix for given uicontrol
outstring = textwrap(h,instring) [outstring,position] = textwrap(h,instring) outstring = textwrap(h,instring) returns a wrapped string cell array, outstring, that fits inside the uicontrol with handle h. instring is a cell array, with each cell containing a single line of text. outstring is the wrapped string
matrix in cell array format. Each cell of the input string is considered a paragraph.
[outstring,position]=textwrap(h,instring) returns the recommended position of the uicontrol in the units of the uicontrol. position considers the
extent of the multiline text in the x and y directions.
Example
Place a textwrapped string in a uicontrol:
pos = [10 10 100 10]; h = uicontrol('Style','Text','Position',pos); string = {'This is a string for the uicontrol.', 'It should be correctly wrapped inside.'}; [outstring,newpos] = textwrap(h,string); pos(4) = newpos(4);
set(h,'String',outstring,'Position',[pos(1),pos(2),pos(3)+10,pos(4)])
See Also
uicontrol
2-584
tic, toc
Purpose Syntax
2tic, toc
Stopwatch timer
tic any statements toc t = toc
Description
tic starts a stopwatch timer. toc prints the elapsed time since tic was used. t = toc returns the elapsed time in t.
Examples
This example measures how the time required to solve a linear system varies with the order of a matrix.
for n = 1:100 A = rand(n,n); b = rand(n,1); tic x = A\b; t(n) = toc; end plot(t)
See Also
clock, cputime, etime, profile
2-585
timer
Purpose Syntax
2timer
Construct timer object
T = timer T = timer(`PropertyName1', PropertyValue1, 'PropertyName2', PropertyValue2,...) T = timer constructs a timer object with default attributes. T = timer('PropertyName1', PropertyValue1, 'PropertyName2', PropertyValue2,...) constructs a timer object in which the given Property
Description
name/value pairs are set on the object. See Timer Object Properties for a list of all the properties supported by the timer object. Note that the property name/property value pairs can be in any format supported by the set function, i.e., property/value string pairs, structures, and property/value cell array pairs.
Example
This example constructs a timer object with a timer callback function handle, mycallback, and a 10 second interval.
t = timer('TimerFcn',@mycallback, 'Period', 10.0);
See Also Timer Object Properties
delete, disp, get, isvalid, set, start, startat, stop, timerfind, wait
The timer object supports the following properties that control its attributes. The table includes information about the data type of each property and its default value.
2-586
timer
To view the value of the properties of a particular timer object, use the get function. To set the value of the properties of a timer object, use the set function.
Property Name AveragePeriod Property Description Datatypes, Values, and Defaults
The average time between TimerFcn executions since the timer started. Note: Value is NaN until timer executes two timer callbacks. Action taken when a timer has to execute TimerFcn before the completion of previous execution of TimerFcn. 'drop'--Do not execute the function. 'error'--Generate an error. 'queue'--Execute function at next opportunity.
Datatype: double Default: NaN Readonly: Always Datatype: Enumerated string Values: 'drop'
'queue' 'error' Default: 'drop'
BusyMode
Readonly: Only when Running='on'
ErrorFcn
Function that the timer executes when an error occurs. This function executes before the StopFcn. See Creating Timer Callback Functions for more information. Determines how the timer object schedules timer events. See Timer Execution Modes for more information.
Datatype: Text string, function handle, or cell array. Default: Readonly: Never Datatype: Enumerated string Values: 'singleShot'
'fixedSpacing' 'fixedDelay' 'fixedRate' Default: 'singleShot' Readonly: When Running='on'
ExecutionMode
InstantPeriod
The time between the last two executions of TimerFcn.
Datatype: double Default: NaN Readonly: Always
2-587
timer
Property Name Name
Property Description
Datatypes, Values, and Defaults
User-supplied name
Datatype: Text string Default: 'timer-i', where i is a number indicating the ith timer object created this session. Note: If you issue the clear classes command, the timer object resets i to 1. Readonly: Never Datatype: double Value: Any number <0.001 Default: 1.0 Readonly: When Running='on' Datatype: Enumerated string: Values: 'off' Default: Readonly: Always
'on' 'off'
Period
Specifies the delay, in seconds, between executions of TimerFcn.
Running
Indicates whether the timer is currently executing.
StartDelay
Specifies the delay, in seconds, between the start of the timer and the first execution of the function specified in TimerFcn. Function the timer calls when it starts. See Creating Timer Callback Functions for more information.
Datatype: double Value: Any number <=0 Default: 0 Readonly: When Running='on' Datatype: Text string, function handle, or cell array Default: Readonly: Never
StartFcn
2-588
timer
Property Name StopFcn
Property Description
Datatypes, Values, and Defaults
Function the timer calls when it stops. The timer stops when: You call the timer stop function When the timer finishes executing TimerFcn, i.e., the value of TasksExecuted reaches the limit set by the TasksToExecute. An error occurs (The ErrorFcn is called first, followed by the StopFcn.) See Creating Timer Callback Functions for more information.
Datatype: Text string, function handle, or cell array. Default: Readonly: Never
Tag
User supplied label Specifies the number of times the timer should execute the function specified in the TimerFcn property. The number of times the timer has executed TimerFcn since the timer was started Timer callback function. See Creating Timer Callback Functions for more information.
Datatype: Text string Default: ''(empty string) Datatype: double Value: Any number <0 Default: 1 Readonly: Never Datatype: double Value: Any number <=0 Default: 0 Readonly: Always Datatype: Text string, function handle, or cell array. Default: Readonly: Never
TasksToExecute
TasksExecuted
TimerFcn
2-589
timer
Property Name Type
Property Description
Datatypes, Values, and Defaults
Identifies the object type
Datatype: Text string Value: 'timer' Readonly: Always Datatype: User-defined Default: [] Readonly: Never
UserData
User-supplied data
2-590
timerfind
Purpose Syntax
2timerfind
Find timer objects
out out out out = = = = timerfind timerfind('P1', V1, 'P2', V2,...) timerfind(S) timerfind(obj, 'P1', V1, 'P2', V2,...)
Description
out = timerfind returns an array, out, of all the timer objects that exist in
memory.
out = timerfind('P1', V1, 'P2', V2,...) returns an array, out, of timer objects whose property values match those passed as param-value pairs, P1, V1, P2, V2. Param-value pairs may be specified as a cell array. out = timerfind(S) returns an array, out, of timer objects whose property values match those defined in the structure, S. The field names of S are timer
object property names and the field values are the corresponding property values.
out = timerfind(obj, 'P1', V1, 'P2', V2,...) restricts the search for matching parameter/value pairs to the timer objects listed in obj. obj can be an array of timer objects.
Note Param-value string pairs, structures, and param-value cell array pairs may be used in the same call to timerfind.
Note that, for most properties, timerfind performs case-sensitive searches of property values. For example, if the value of an object's Name property is 'MyObject', timerfind will not find a match if you specify 'myobject'. Use the get function to determine the exact format of a property value. However, properties which have an enumerated list of possible values, are not case-sensitive. For example, timerfind will find an object with an ExecutionMode property value of 'singleShot' or 'singleshot'.
Example
This example uses timerfind to find timer objects with the specified property values.
2-591
timerfind
t1 = t2 = out1 out2
timer('Tag', 'broadcastProgress', 'Period', 5); timer('Tag', 'displayProgress'); = timerfind('Tag', 'displayProgress') = timerfind({'Period', 'Tag'}, {5, 'broadcastProgress'})
See Also
timer, get
2-592
title
Purpose Syntax
2title
Add title to current axes
title('string') title(fname) title(...,'PropertyName',PropertyValue,...) h = title(...)
Description
Each axes graphics object can have one title. The title is located at the top and in the center of the axes.
title('string') outputs the string at the top and in the center of the current
axes.
title(fname) evaluates the function that returns a string and displays the
string at the top and in the center of the current axes.
title(...,'PropertyName',PropertyValue,...) specifies property name and property value pairs for the text graphics object that title creates. h = title(...) returns the handle to the text object used as the title.
Examples
Display today's date in the current axes:
title(date)
Include a variable's value in a title:
f = 70; c = (f--32)/1.8; title(['Temperature is ',num2str(c),'C'])
Include a variable's value in a title and set the color of the title to yellow:
n = 3; title(['Case number #',int2str(n)],'Color','y')
Include Greek symbols in a title:
title('\ite^{\omega\tau} = cos(\omega\tau) + isin(\omega\tau)')
Include a superscript character in a title:
title('\alpha^2')
2-593
title
Include a subscript character in a title:
title('X_1')
The text object String property lists the available symbols.
Remarks See Also
title sets the Title property of the current axes graphics object to a new text graphics object. See the text String property for more information. gtext, int2str, num2str, text, xlabel, ylabel, zlabel
"Annotating Plots" for related functions Adding Titles to Graphs for more information on ways to add titles.
2-594
toeplitz
Purpose Syntax Description
2toeplitz
Toeplitz matrix
T = toeplitz(c,r) T = toeplitz(r)
A Toeplitz matrix is defined by one row and one column. A symmetric Toeplitz matrix is defined by just one row. toeplitz generates Toeplitz matrices given just the row or row and column description.
T = toeplitz(c,r) returns a nonsymmetric Toeplitz matrix T having c as its first column and r as its first row. If the first elements of c and r are different, a message is printed and the column element is used. T = toeplitz(r) returns the symmetric or Hermitian Toeplitz matrix formed from vector r, where r defines the first row of the matrix.
Examples
A Toeplitz matrix with diagonal disagreement is
c = [1 2 3 4 5]; r = [1.5 2.5 3.5 4.5 5.5]; toeplitz(c,r) Column wins diagonal conflict: ans = 1.000 2.500 3.500 2.000 1.000 2.500 3.000 2.000 1.000 4.000 3.000 2.000 5.000 4.000 3.000
4.500 3.500 2.500 1.000 2.000
5.500 4.500 3.500 2.500 1.000
See Also
hankel
2-595
trace
Purpose Syntax Description Algorithm
2trace
Sum of diagonal elements
b = trace(A) b = trace(A) is the sum of the diagonal elements of the matrix A. trace is a single-statement M-file. t = sum(diag(A));
See Also
det, eig
2-596
trapz
Purpose Syntax
2trapz
Trapezoidal numerical integration
Z = trapz(Y) Z = trapz(X,Y) Z = trapz(...,dim) Z = trapz(Y) computes an approximation of the integral of Y via the
Description
trapezoidal method (with unit spacing). To compute the integral for spacing other than one, multiply Z by the spacing increment. If Y is a vector, trapz(Y) is the integral of Y. If Y is a matrix,trapz(Y) is a row vector with the integral over each column. If Y is a multidimensional array, trapz(Y) works across the first nonsingleton dimension.
Z = trapz(X,Y) computes the integral of Y with respect to X using trapezoidal
integration. If X is a column vector and Y an array whose first nonsingleton dimension is length(X), trapz(X,Y) operates across this dimension.
Z = trapz(...,dim) integrates across the dimension of Y specified by scalar dim. The length of X, if given, must be the same as size(Y,dim).
Examples
The exact value of
0 sin ( x ) dx
is 2.
To approximate this numerically on a uniformly spaced grid, use
X = 0:pi/100:pi; Y = sin(x);
Then both
Z = trapz(X,Y)
and
Z = pi/100*trapz(Y)
produce
2-597
trapz
Z = 1.9998
A nonuniformly spaced example is generated by
X = sort(rand(1,101)*pi); Y = sin(X); Z = trapz(X,Y);
The result is not as accurate as the uniformly spaced grid. One random sample produced
Z = 1.9984
See Also
cumsum, cumtrapz
2-598
treelayout
Purpose Syntax Description
2treelayout
Lay out tree or forest
[x,y] = treelayout(parent,post) [x,y,h,s] = treelayout(parent,post) [x,y] = treelayout(parent,post) lays out a tree or a forest. parent is the vector of parent pointers, with 0 for a root. post is an optional postorder permutation on the tree nodes. If you omit post, treelayout computes it. x and y are vectors of coordinates in the unit square at which to lay out the nodes of
the tree to make a nice picture.
[x,y,h,s] = treelayout(parent,post) also returns the height of the tree h and the number of vertices s in the top-level separator.
See Also
etree, treeplot, etreeplot, symbfact
2-599
treeplot
Purpose Syntax Description
2treeplot
Plot picture of tree
treeplot(p) treeplot(p,nodeSpec,edgeSpec) treeplot(p) plots a picture of a tree given a vector of parent pointers, with p(i) = 0 for a root. treeplot(p,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
etree, etreeplot, treelayout
2-600
tril
Purpose Syntax Description
2tril
Lower triangular part of a matrix
L = tril(X) L = tril(X,k) L = tril(X) returns the lower triangular part of X. L = tril(X,k) returns the elements on and below the kth diagonal of X. k = 0 is the main diagonal, k > 0 is above the main diagonal, and k < 0 is below the
main diagonal.
k = 0 k < 0 k > 0
Examples
tril(ones(4,4),-1) ans = 0 1 1 1 0 0 1 1 0 0 0 1 0 0 0 0
See Also
diag, triu
2-601
trimesh
Purpose Syntax
2trimesh
Triangular mesh plot
trimesh(Tri,X,Y,Z) trimesh(Tri,X,Y,Z,C) trimesh(...'PropertyName',PropertyValue...) h = trimesh(...) trimesh(Tri,X,Y,Z) displays triangles defined in the m-by-3 face matrix Tri as a mesh. Each row of Tri defines a single triangular face by indexing into the vectors or matrices that contain the X, Y, and Z vertices. trimesh(Tri,X,Y,Z,C) specifies color defined by C in the same manner as the surf function. MATLAB performs a linear transformation on this data to
Description
obtain colors from the current colormap.
trimesh(...'PropertyName',PropertyValue...) specifies additional patch property names and values for the patch graphics object created by the function. h = trimesh(...) returns a handle to a patch graphics object.
Example
Create vertex vectors and a face matrix, then create a triangular mesh plot.
x = rand(1,50); y = rand(1,50); z = peaks(6*x3,6*x3); tri = delaunay(x,y); trimesh(tri,x,y,z)
See Also
patch, tetramesh, triplot, trisurf, delaunay
"Creating Surfaces and Meshes" for related functions
2-602
triplequad
Purpose Syntax
2triplequad
Numerically evaluate triple integral
triplequad(fun,xmin,xmax,ymin,ymax,zmin,zmax) triplequad(fun,xmin,xmax,ymin,ymax,zmin,zmax,tol) triplequad(fun,xmin,xmax,ymin,ymax,zmin,zmax,tol,method) triplequad(fun,xmin,xmax,ymin,ymax,zmin,zmax,tol,method,p1,p2,...) triplequad(fun,xmin,xmax,ymin,ymax,zmin,zmax) evaluates the triple integral fun(x,y,z) over the three dimensional rectangular region xmin <= x <= xmax, ymin <= y <= ymax, zmin <= z <= zmax. The function fun(x,y,z) must accept a vector x and scalars y and z, and return a vector of values of the integrand. triplequad(fun,xmin,xmax,ymin,ymax,zmin,zmax,tol) uses a tolerance tol instead of the default, which is 1.0e-6. triplequad(fun,xmin,xmax,ymin,ymax,zmin,zmax,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. triplequad(fun,xmin,xmax,ymin,ymax,zmin,zmax,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. triplequad(fun,xmin,xmax,ymin,ymax,zmin,zmax,[],[],p1,p2,...) is the
Description
same as
triplequad(fun,xmin,xmax,ymin,ymax,zmin,zmax,1e-6,@quad,p1,p2,...)
Examples
fun can be an inline object Q = triplequad(inline('y*sin(x)+z*cos(x)'),0,pi,0,1,-1,1)
or a function handle
Q = triplequad(@integrnd,0,pi,0,1,-1,1)
where integrnd.m is the M-file
function f = integrnd(x,y,z) f = y*sin(x)+z*cos(x);
2-603
triplequad
This example integrates y*sin(x)+z*cos(x) over the region 0 <= x <= pi, 0 <= y <= 1, -1 <= z <= 1. Note that the integrand can be evaluated with a vector x and scalars y and z.
See Also
dblquad, inline, quad, quadl, @ (function handle)
2-604
triplot
Purpose Syntax
2 triplot
2-D triangular plot
triplot(TRI,x,y) triplot(TRI,x,y,color) h = triplot(...) triplot(...,'param','value','param','value'...) triplot(TRI,x,y) displays the triangles defined in the m-by-3 matrix TRI. A row of TRI contains indices into the vectors x and y that define a single triangle.
Description
The default line color is blue.
triplot(TRI,x,y,color) uses the string color as the line color. color can also be a line specification. See ColorSpec for a list of valid color strings. See LineSpec for information about line specifications. h = triplot(...) returns a vector of handles to the displayed triangles. triplot(...,'param','value','param','value'...) allows additional line property name/property value pairs to be used when creating the plot. See Line Properties for information about the available properties.
Examples
This code plots the Delaunay triangulation for 10 randomly generated points.
rand('state',7); x = rand(1,10); y = rand(1,10); TRI = delaunay(x,y); triplot(TRI,x,y,'red')
2-605
triplot
1
0.9
0.8
0.7
0.6
0.5
0.4
0.3
0.2
0.1
0
0
0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.8
0.9
1
See Also
ColorSpec, delaunay, line, Line Properties, LineSpec, plot, trimesh, trisurf
2-606
trisurf
Purpose Syntax
2trisurf
Triangular surface plot
trisurf(Tri,X,Y,Z) trisurf(Tri,X,Y,Z,C) trisurf(...'PropertyName',PropertyValue...) h = trisurf(...) trisurf(Tri,X,Y,Z) displays triangles defined in the m-by-3 face matrix Tri as a surface. Each row of Tri defines a single triangular face by indexing into the vectors or matrices that contain the X, Y, and Z vertices. trisurf(Tri,X,Y,Z,C) specifies color defined by C in the same manner as the surf function. MATLAB performs a linear transformation on this data to
Description
obtain colors from the current colormap.
trisurf(...'PropertyName',PropertyValue...) specifies additional patch property names and values for the patch graphics object created by the function. h = trisurf(...) returns a patch handle.
Example
Create vertex vectors and a face matrix, then create a triangular surface plot.
x = rand(1,50); y = rand(1,50); z = peaks(6*x3,6*x3); tri = delaunay(x,y); trisurf(tri,x,y,z)
See Also
patch, surf, tetramesh, trimesh, triplot, delaunay
"Creating Surfaces and Meshes" for related functions
2-607
triu
Purpose Syntax Description
2triu
Upper triangular part of a matrix
U = triu(X) U = triu(X,k) U = triu(X) returns the upper triangular part of X. U = triu(X,k) returns the element on and above the kth diagonal of X. k = 0 is the main diagonal, k > 0 is above the main diagonal, and k < 0 is below the
main diagonal.
k = 0 k < 0 k > 0
Examples
triu(ones(4,4),-1) ans = 1 1 0 0 1 1 1 0 1 1 1 1 1 1 1 1
See Also
diag, tril
2-608
true
Purpose Syntax
2true
True array
true true(n) true(m,n) true(m,n,p,...) true(size(A)) true is shorthand for logical(1). true(n) is an n-by-n matrix of logical ones. true(m,n) or true([m,n]) is an m-by-n matrix of logical ones. true(m,n,p,...) or true([m n p ...]) is an m-by-n-by-p-by-... array of
Description
logical ones.
true(size(A)) is an array of logical ones that is the same size as array A.
Remarks See Also
true(n) is much faster and more memory efficient than logical(ones(n)). false, logical
2-609
try
Purpose Description
2try
Begin try block The general form of a try statement is:
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
catch, end, eval, evalin
2-610
tsearch
Purpose Syntax Description
2tsearch
Search for enclosing Delaunay triangle
T = tsearch(x,y,TRI,xi,yi) T = tsearch(x,y,TRI,xi,yi) returns an index into the rows of TRI for each point in xi, yi. The tsearch command returns NaN for all points outside the convex hull. Requires a triangulation TRI of the points x,y obtained from delaunay. delaunay, delaunayn, dsearch, tsearchn
See Also
2-611
tsearchn
Purpose Syntax Description
2tsearchn
n-D closest simplex search
t = tsearchn(X,TES,XI) [t,P] = tsearchn(X,TES,XI) t = tsearchn(X,TES,XI) returns the indices t of the enclosing simplex of the Delaunay tessellation TES 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. tsearchn returns NaN for all points outside the convex hull of X. tsearchn requires a tessellation TES of the points X obtained from delaunayn. [t,P] = tsearchn(X,TES,XI) also returns the barycentric coordinate P of XI in the simplex TES. P is a p-by-n+1 matrix. Each row of P is the Barencentric coordinate of the corresponding point in XI. It is useful for interpolation.
See Also
delaunayn, griddatan, tsearch
2-612
type
Purpose Syntax Description
2type
List file
type ('filename') type filename type('filename') displays the contents of the specified file in the MATLAB Command Window. Use the full path for filename, or use a MATLAB relative
partial pathname. If you do not specify a filename extension and there is no filename file without an extension, the type function adds the .m extension by default. The type function checks the directories specified in the MATLAB search path, which makes it convenient for listing the contents of M-files on the screen. Use type with more on to see the listing one screenful at a time.
type filename is the unquoted form of the syntax.
Examples
type('foo.bar') lists the contents of the file foo.bar. type foo lists the contents of the file foo. If foo does not exist, type foo lists the contents of the file foo.m.
See Also
cd, dbtype, delete, dir, more, partialpath, path, what, who
2-613
uicontextmenu
Purpose Syntax Description
2uicontextmenu
Create a context menu
handle = uicontextmenu('PropertyName',PropertyValue,...); uicontextmenu creates a context menu, which is a menu that appears when the
user right-clicks on a graphics object. You create context menu items using the uimenu function. Menu items appear in the order the uimenu statements appear. You associate a context menu with an object using the UIContextMenu property for the object and specifying the context menu's handle as the property value.
Properties
This table lists the properties that are useful to uicontextmenu objects, grouping them by function. Each property name acts as a link to a description of the property.
Property Description Property Value
Property Name
Controlling Style and Appearance Visible
Uicontextmenu visibility Location of uicontextmenu when Visible is set to on
Value: on, off Default: off Value: two-element vector Default: [0 0]
Position
General Information About the Object Children
The uimenus defined for the uicontextmenu Uicontextmenu object's parent User-specified object identifier Class of graphics object User-specified data
Value: matrix Value: scalar figure handle Value: string Value: string (read-only) Default: uicontrol Value: matrix
Parent Tag Type
UserData
Controlling Callback Routine Execution
2-614
uicontextmenu
Property Name BusyAction
Property Description
Property Value
Callback routine interruption Control action Callback routine executed during object creation Callback routine executed during object deletion Callback routine interruption mode
Value: cancel, queue Default: queue Value: string Value: string Value: string Value: on, off Default: on
Callback CreateFcn
DeleteFcn
Interruptible
Controlling Access to Objects HandleVisibility
Whether handle is accessible from command line and GUIs
Value: on, callback, off Default: on
Example
These statements define a context menu associated with a line. When the user extend-clicks anywhere on the line, the menu appears. Menu items enable the user to change the line style.
% Define the context menu cmenu = uicontextmenu; % Define the line and associate it with the context menu hline = plot(1:10, 'UIContextMenu', cmenu); % Define callbacks for context menu items cb1 = ['set(hline, ''LineStyle'', ''--'')']; cb2 = ['set(hline, ''LineStyle'', '':'')']; cb3 = ['set(hline, ''LineStyle'', ''-'')']; % Define the context menu items item1 = uimenu(cmenu, 'Label', 'dashed', 'Callback', cb1); item2 = uimenu(cmenu, 'Label', 'dotted', 'Callback', cb2); item3 = uimenu(cmenu, 'Label', 'solid', 'Callback', cb3);
2-615
uicontextmenu
When the user extend-clicks on the line, the context menu appears, as shown in this figure:
Object Hierarchy
Root
Figure
Axes
Uicontrol
Uimenu
Uicontextmenu
Uimenu
Uimenu
See Also
uicontrol, uimenu
2-616
uicontextmenu Properties
Modifying Properties
2uicontextmenu 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.
Uicontextmenu Property Descriptions
BusyAction
cancel | {queue}
Callback routine interruption. The BusyAction property enables you to control how MATLAB handles events that potentially interrupt executing callback routines. If a callback routine is 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 whose callback is executing 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
This property has no effect on uicontextmenu objects.
Callback
string
Control action. A routine that executes whenever you right-click on an object for which a context menu is defined. The routine executes immediately before the context menu is posted. 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.
Children
matrix
The uimenus defined for the uicontextmenu.
2-617
uicontextmenu Properties
Clipping
{on} | off
This property has no effect on uicontextmenu objects.
CreateFcn
string
Callback routine executed during object creation. This property defines a callback routine that executes when MATLAB creates a uicontextmenu object. You must define this property as a default value for uicontextmenus. For example, this statement:
set(0,'DefaultUicontextmenuCreateFcn',... 'set(gcf,''IntegerHandle'',''off'')')
defines a default value on the root level that sets the figure IntegerHandle property to off whenever you create a uicontextmenu object. MATLAB executes this routine after setting all property values for the uicontextmenu. Setting this property on an existing uicontextmenu 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.
DeleteFcn
string
Delete uicontextmenu callback routine. A callback routine that executes when you delete the uicontextmenu object (e.g., when you issue a delete command or clear the figure containing the uicontextmenu). MATLAB executes the routine before destroying the object's properties so these values are available to the callback routine. The handle of the object whose DeleteFcn is being executed is accessible only through the root CallbackObject property, which you can query using gcbo.
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
2-618
uicontextmenu Properties
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. 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
This property has no effect on uicontextmenu objects.
Interruptible {on} | off
Callback routine interruption mode. The Interruptible property controls whether a uicontextmenu callback routine can be interrupted by subsequently invoked callback routines. By default (on), execution of a callback routine can be interrupted. Only callback routines defined for the ButtonDownFcn and Callback properties are affected by the Interruptible property. MATLAB checks for events that can interrupt a callback routine only when it encounters a drawnow, figure, getframe, pause, or waitfor command in the routine.
2-619
uicontextmenu Properties
Parent
handle
Uicontextmenu's parent. The handle of the uicontextmenu's parent object. The parent of a uicontextmenu object is the figure in which it appears. You can move a uicontextmenu object to another figure by setting this property to the handle of the new parent.
Position
vector
Uicontextmenu's position. A two-element vector that defines the location of a context menu posted by setting the Visible property value to on. Specify Position as
[left bottom]
where vector elements represent the distance in pixels from the bottom left corner of the figure window to the top left corner of the context menu.
Selected on | {off}
This property has no effect on uicontextmenu objects.
SelectionHighlight {on} | off
This property has no effect on uicontextmenu objects.
Tag
string
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. You can define Tag as any string.
Type
string
Class of graphics object. For uicontextmenu objects, Type is always the string 'uicontextmenu'.
UIContextMenu
handle
This property has no effect on uicontextmenus.
UserData
matrix
User-specified data. Any data you want to associate with the uicontextmenu object. MATLAB does not use this data, but you can access it using set and get.
2-620
uicontextmenu Properties
Visible
on | {off}
Uicontextmenu visibility. The Visible property can be used in two ways: Its value indicates whether the context menu is currently posted. While the context menu is posted, the property value is on; when the context menu is not posted, its value is off. Its value can be set to on to force the posting of the context menu. Similarly, setting the value to off forces the context menu to be removed. When used in this way, the Position property determines the location of the posted context menu.
2-621
uicontrol
Purpose Syntax Description
2uicontrol
Create user interface control object
handle = uicontrol(parent) handle = uicontrol(...,'PropertyName',PropertyValue,...) uicontrol creates uicontrol graphics objects (user interface controls). You
implement graphical user interfaces using uicontrols. When selected, most uicontrol objects perform a predefined action. MATLAB supports numerous styles of uicontrols, each suited for a different purpose: Check boxes Editable text fields Frames List boxes Pop-up menus Push buttons Radio buttons Sliders Static text labels Toggle buttons See User Interface Controls for information on using these uicontrols within GUIDE, the MATLAB GUI development environment.
Specifying the Uicontrol Style
To create a specific type of uicontrol, set the Style property as one of the following strings: 'checkbox' Check boxes generate an action when clicked on. These devices are useful when providing the user with a number of independent choices. To activate a check box, click the mouse button on the object. The state of the device is indicated on the display. 'edit' Editable text fields enable users to enter or modify text values. Use editable text when you want text as input. On Microsoft Windows systems, if an editable text box has focus, clicking on the menu bar does not cause the editable text callback routine to execute.
2-622
uicontrol
However, it does cause execution on UNIX systems. Therefore, after clicking on the menu bar, the statement
get(edit_handle,'String')
does not return the current contents of the edit box on Microsoft Windows systems because MATLAB must execute the callback routine to update the String property (even though the text string has changed on the screen). This behavior is consistent with the respective platform conventions. 'frame' Frames are rectangles that provide a visual enclosure for regions of a figure window. Frames can make a user interface easier to understand by grouping related controls. Frames have no callback routines associated with them. Only other uicontrols can appear within frames. Frames are opaque, not transparent, so the order you define uicontrols is important in determining whether uicontrols within a frame are covered by the frame or are visible. Stacking order determines the order objects are drawn: objects defined first are drawn first; objects defined later are drawn over existing objects. If you use a frame to enclose objects, you must define the frame before you define the objects. 'listbox' List boxes display a list of items (defined using the String property) and enable users to select one or more items. The Min and Max properties control the selection mode: If Max-Min>1, then multiple selection is allowed. If Max-Min<=1, then only single selection is allowed. The Value property indicates selected entries and contains the indices into the list of strings; a vector value indicates multiple selections. MATLAB evaluates the list box's callback routine after any mouse button up event that changes the Value property. Therefore, you may need to add a "Done" button to delay action caused by multiple clicks on list items. List boxes differentiate between single and double clicks and set the figure SelectionType property to normal or open accordingly before evaluating the list box's Callback property. 'popupmenu' Popup menus open to display a list of choices (defined using the String property) when pressed. When not open, a pop-up menu indicates the current choice. Pop-up menus are useful when you want to provide users with a number of mutually exclusive choices, but do not want to take up the
2-623
uicontrol
amount of space that a series of radio buttons requires. You must specify a value for the String property. 'pushbutton' Push buttons generate an action when pressed. To activate a push button, click the mouse button on the push button. 'radiobutton' Radio buttons are similar to check boxes, but are intended to be mutually exclusive within a group of related radio buttons (i.e., only one is in a pressed state at any given time). To activate a radio button, click the mouse button on the object. The state of the device is indicated on the display. Note that your code can implement the mutually exclusive behavior of radio buttons. 'slider' Sliders accept numeric input within a specific range by enabling the user to move a sliding bar. Users move the bar by pressing the mouse button and dragging the pointer over the bar, or by clicking in the trough or on an arrow. The location of the bar indicates a numeric value, which is selected by releasing the mouse button. You can set the minimum, maximum, and current values of the slider. 'text' Static text boxes display lines of text. Static text is typically used to label other controls, provide directions to the user, or indicate values associated with a slider. Users cannot change static text interactively and there is no way to invoke the callback routine associated with it. 'toggle' Toggle buttons are controls that execute callbacks when clicked on and indicate their state, either on or off. Toggle buttons are useful for building toolbars.
Remarks
The uicontrol function accepts property name/property value pairs, structures, and cell arrays as input arguments and optionally returns the handle of the created object. You can also set and query property values after creating the object using the set and get functions. Uicontrol objects are children of figures and therefore do not require an axes to exist when placed in a figure window.
2-624
uicontrol
Properties
This table lists all properties useful for uicontrol objects, grouping them by function. Each property name acts as a link to a description of the property.
Property Description Property Value
Property Name
Controlling Style and Appearance BackgroundColor
Object background color Truecolor image displayed on the control Color of text Object highlighted when selected Uicontrol label, also list box and pop-up menu items Uicontrol visibility
Value: ColorSpec Default: system dependent Value: matrix Value: ColorSpec Default: [0 0 0] Value: on, off Default: on Value: string Value: on, off Default: on
CData
ForegroundColor
SelectionHighlight
String
Visible
General Information About the Object Children Enable
Uicontrol objects have no children Enable or disable the uicontrol Uicontrol object's parent Whether object is selected Slider step size Value: on, inactive, off Default: on Value: scalar figure handle Value: on, off Default: off Value: two-element vector Default: [0.01 0.1]
Parent Selected
SliderStep
2-625
uicontrol
Property Name Style
Property Description
Property Value
Type of uicontrol object
Value: pushbutton, togglebutton, radiobutton, checkbox, edit, text, slider, frame, listbox, popupmenu Default: pushbutton Value: string Value: string Value: string (read-only) Default: uicontrol Value: matrix
Tag TooltipString Type
User-specified object identifier Content of object's tooltip Class of graphics object User-specified data
UserData
Controlling the Object Position Position
Size and location of uicontrol object Units to interpret position vector
Value: position rectangle Default: [20 20 60 20] Value: pixels, normalized, inches, centimeters, points, characters Default: pixels
Units
Controlling Fonts and Labels FontAngle
Character slant
Value: normal, italic, oblique Default: normal Value: string Default: system dependent Value: size in FontUnits Default: system dependent
FontName
Font family Font size
FontSize
2-626
uicontrol
Property Name FontUnits
Property Description
Property Value
Font size units
Value: points, normalized, inches, centimeters, pixels Default: points Value: light, normal, demi,
bold
FontWeight
Weight of text characters
Default: normal
HorizontalAlignment
Alignment of label string
Value: left, center, right Default: depends on uicontrol object Value: string
String
Uicontrol object label, also list box and pop-up menu items
Controlling Callback Routine Execution BusyAction
Callback routine interruption Button press callback routine Control action Callback routine executed during object creation Callback routine executed during object deletion Callback routine interruption mode Uicontextmenu object associated with the uicontrol
Value: cancel, queue Default: queue Value: string Value: string Value: string Value: string Value: on, off Default: on Value: handle
ButtonDownFcn Callback CreateFcn
DeleteFcn
Interruptible
UIContextMenu
Information About the Current State ListboxTop
Index of top-most string displayed in list box
Value: scalar Default: [1]
2-627
uicontrol
Property Name Max
Property Description
Property Value
Maximum value (depends on uicontrol object) Minimum value (depends on uicontrol object) Current value of uicontrol object
Value: scalar Default: object dependent Value: scalar Default: object dependent Value: scalar or vector Default: object dependent
Min
Value
Controlling Access to Objects HandleVisibility
Whether handle is accessible from command line and GUIs Whether selectable by mouse click
Value: on, callback, off Default: on Value: on, off Default: on
HitTest
Examples
The following statement creates a push button that clears the current axes when pressed:
h = uicontrol('Style', 'pushbutton', 'String', 'Clear',... 'Position', [20 150 100 70], 'Callback', 'cla');
You can create a uicontrol object that changes figure colormaps by specifying a pop-up menu and supplying an M-file name as the object's Callback:
hpop = uicontrol('Style', 'popup',... 'String', 'hsv|hot|cool|gray',... 'Position', [20 320 100 50],... 'Callback', 'setmap');
The above call to uicontrol defines four individual choices in the menu: hsv, hot, cool, and gray. You specify these choices with the String property, separating the choices with the "|" character. The Callback, in this case setmap, is the name of an M-file that defines a more complicated set of instructions than a single MATLAB command. setmap contains these statements:
val = get(hpop,'Value'); if val == 1
2-628
uicontrol
colormap(hsv) elseif val == 2 colormap(hot) elseif val == 3 colormap(cool) elseif val == 4 colormap(gray) end
The Value property contains a number that indicates the selected choice. The choices are numbered sequentially from one to four. The setmap M-file can get and then test the contents of the Value property to determine what action to take.
Object Hierarchy
Root
Figure
Axes
Uicontrol
Uimenu
Uicontextmenu
Uimenu
Uimenu
See Also
textwrap, uimenu
2-629
Uicontrol Properties
Modifying Properties
2Uicontrol 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.
Uicontrol Property Descriptions
You can set default uicontrol properties on the root and figure levels:
set(0,'DefaultUicontrolProperty',PropertyValue...) set(gcf,'DefaultUicontrolProperty',PropertyValue...)
where Property is the name of the uicontrol property whose default value you want to set and PropertyValue is the value you are specifying. Use set and get to access uicontrol properties. Curly braces { } enclose the default value.
BackgroundColor ColorSpec
Object background color. The color used to fill the uicontrol rectangle. Specify a color using a three-element RGB vector or one of the MATLAB predefined names. The default color is determined by system settings. See ColorSpec for more information on specifying color.
BusyAction cancel | {queue}
Callback routine interruption. If a callback is executing and the user triggers an event (such as a mouse click) on an object for which a callback is defined, that callback attempts to interrupt the first callback. The first callback can be interrupted only at a drawnow, figure, getframe, pause, or waitfor command; if the callback does not contain any of these commands, it cannot be interrupted. If the Interruptible property of the object whose callback is executing is off (the default value is on), the callback cannot be interrupted (except by certain callbacks; see the note below). The BusyAction property of the object whose callback is waiting to execute determines what happens to the callback: If the value is queue, the callback is added to the event queue and executes after the first callback finishes execution.
2-630
Uicontrol Properties
If the value is cancel, the event is discarded and the callback is not executed.
Note If the interrupting callback is a DeleteFcn or CreateFcn callback or a figure's CloseRequest or ResizeFcn callback, it interrupts an executing callback regardless of the value of that object's Interruptible property. The interrupting callback starts execution at the next drawnow, figure, getframe, pause, or waitfor statement.
ButtonDownFcn
string
Button press callback routine. A callback routine that executes whenever you press a mouse button while the pointer is in a five-pixel wide border around the uicontrol. When the uicontrol's Enable property is set to inactive or off, the ButtonDownFcn executes when you click the mouse in the five-pixel border or on the control itself. This is useful for implementing actions to interactively modify control object properties, such as size and position, when they are clicked on (using selectmoveresize, for example). 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. The Callback property defines the callback routine that executes when you activate the enabled uicontrol (e.g., click on a push button).
Callback
string (GUIDE sets this property)
Control action. A routine that executes whenever you activate the uicontrol object (e.g., when you click on a push button or move a slider). 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. To execute the callback routine for an editable text control, type in the desired text, then either: Move the focus off the object (click the mouse someplace else in the GUI), For a single line editable text box, press Return, or For a multiline editable text box, press Ctl-Return. Callback routines defined for frames and static text do not execute because no action is associated with these objects.
2-631
Uicontrol Properties
CData
matrix
Truecolor image displayed on control. A three-dimensional matrix of RGB values that defines a truecolor image displayed on either a push button or toggle button. Each value must be between 0.0 and 1.0.
Children
matrix
...

**Find millions of documents on Course Hero - Study Guides, Lecture Notes, Reference Materials, Practice Exams and more. Course Hero has millions of course specific materials providing students with the best way to expand their education.**

Below is a small sample set of documents:

USC - ENGR - 483

MATLABThe Language of Technical ComputingComputation Visualization ProgrammingUsing MATLABVersion 6How to Contact The MathWorks:www.mathworks.com comp.soft-sys.matlab support@mathworks.com suggest@mathworks.com bugs@mathworks.com doc@mathw

Washington University in St. Louis - MEXMRS - 0120

=Upfront Notes= This "aareadme.txt" file contains the description of the naming convention that will be used for all MEX kernels. One part of them will be directly produced by an automated system located at ESTEC,PST. Consequently, we c

Washington University in St. Louis - MEXMRS - 0120

$MEX LIGHT TIME FILE 1*LITIME 2*PREP JPL Mars Express Navigation Team 3*TITLE

Washington University in St. Louis - MEXMRS - 0120

$MEX ORBIT PROPAGATION AND TIMING GEOMETRY FILE v002* OPTG optg.out* TITLE 2004 Mars Express Mapping: OPTG File* CREATION JPL 04-JUN-30/08:28:01* BEGIN SCE 04-JUN-30/00:00:00.000* CUTOFF SCE 04-AUG-17/00:00:00.000*

Washington University in St. Louis - MEXMRS - 0120

=MEX CK Files= Last update: 10 NOV 2004 This "aareadme.txt" file describes the contents of the KERNELS/CK directory of the MEX SPICE data server. It also provides the file naming conventions used for the MEX CK kernels, and it provi

Washington University in St. Louis - MEXMRS - 0120

=MEX FK Files= Last Update: 27 JUL 2005 This "aareadme.txt" file describes the contents of the KERNELS/FK directory of the MEX SPICE data server. It also provides the file naming conventions used for the MEX FK kernels, and it provides id

Washington University in St. Louis - MEXMRS - 0120

=MEX SPK Files= Last update: 27 JUL 2005 This "aareadme.txt" file describes the contents of the KERNELS/SPK directory of the MEX SPICE data server. It also provides the file naming conventions used for the MEX SPK kernels, and it pr

Washington University in St. Louis - MEXMRS - 0120

=MEX PCK Files= Last Update: 10 NOV 2004 This "aareadme.txt" file describes the contents of the KERNELS/PCK directory of the MEX SPICE data server. It also provides the file naming conventions used for the MEX PCK kernels, and it provides

Washington University in St. Louis - MEXMRS - 0120

=MEX LSK Files= Last update: 08 AUG 2005 This "aareadme.txt" file describes the contents of the KERNELS/LSK directory. It also provides the file naming conventions used for the MEX LSK kernels, and it provides identification of the m

Washington University in St. Louis - MEXMRS - 0120

=MEX SCLK Files= Last update: 22 MAR 2004 This "aareadme.txt" file describes the contents of the KERNELS/SCLK directory of the MEX SPICE data server. It also provides the file naming conventions used for the MEX SCLK kernels, and it

Washington University in St. Louis - MEXMRS - 0120

=MEX Orbit Number Files= Last update: 22 MAR 2004 This "aareadme.txt" file describes the contents of the KERNELS/ORBNUM directory of the MEX SPICE data server. It also provides the file naming conventions used for the MEX Orbit Numb

Washington University in St. Louis - MEXMRS - 0448

=Upfront Notes= This "aareadme.txt" file contains the description of the naming convention that will be used for all MEX kernels. One part of them will be directly produced by an automated system located at ESTEC,PST. Consequently, we c

Washington University in St. Louis - MEXMRS - 0448

=MEX FK Files= Last Update: 12 MAY 2006 This "aareadme.txt" file describes the contents of the KERNELS/FK directory of the MEX SPICE data server. It also provides the file naming conventions used for the MEX FK kernels, and it provides id

Washington University in St. Louis - MEXMRS - 0448

=MEX CK Files= Last update: 22 NOV 2005 This "aareadme.txt" file describes the contents of the KERNELS/CK directory of the MEX SPICE data server. It also provides the file naming conventions used for the MEX CK files, and it provide

Washington University in St. Louis - MEXMRS - 0448

=MEX SPK Files= Last update: 30 MAY 2006 This "aareadme.txt" file describes the contents of the KERNELS/SPK directory of the MEX SPICE data server. It also provides the file naming conventions used for the MEX SPK kernels, and it pr

Washington University in St. Louis - MEXMRS - 0448

=MEX PCK Files= Last Update: 12 MAY 2006 This "aareadme.txt" file describes the contents of the KERNELS/PCK directory of the MEX SPICE data server. It also provides the file naming conventions used for the MEX PCK kernels, and it provides

Rensselaer Polytechnic Institute - DARPAREV - 033105

Washington University in St. Louis - MEXMRS - 0448

=MEX LSK Files= Last update: 08 AUG 2005 This "aareadme.txt" file describes the contents of the KERNELS/LSK directory. It also provides the file naming conventions used for the MEX LSK kernels, and it provides identification of t

Washington University in St. Louis - MEXMRS - 0448

=MEX SCLK Files= Last update: 22 MAR 2004 This "aareadme.txt" file describes the contents of the KERNELS/SCLK directory of the MEX SPICE data server. It also provides the file naming conventions used for the MEX SCLK kernels, and it

Washington University in St. Louis - MEXMRS - 0448

=MEX Orbit Number Files= Last update: 11 MAY 2006 This "aareadme.txt" file describes the contents of the KERNELS/ORBNUM directory of the MEX SPICE data server. It also provides the file naming conventions used for the MEX Orbit Numbe

Rensselaer Polytechnic Institute - AFRLUPDATE - 0205

Rensselaer Polytechnic Institute - SUNYB - 020905

UMBC - CMSC - 681

2002-06-04IEEE C802.16-02/05Project Title Date Submitted Source(s)IEEE 802.16 Broadband Wireless Access Working Group <http:/ieee802.org/16> IEEE Standard 802.16: A Technical Overview of the WirelessMANTM Air Interface for Broadband Wireless Ac

UMBC - CMSC - 681

SelfHealing GroupWise Key Distribution Schemes with TimeLimited Node Revocation for Wireless Sensor NetworksMinghui Shi, Xuemin Shen, Yixin Jiang, Chuang Lin CMSC 681 Fall 2007 Advanced Computer Networks Isaac Mativo Sensor NodeTypical s

Rensselaer Polytechnic Institute - MESA - 0205

Rensselaer Polytechnic Institute - NIMDPIMEET - 1104

UCLA - ESS - 136

Thursday, May 21, 2009EXPLORATION GEOPHYSICS - MINERAL METHODS ESS 136B SPRING 2003 Professor R.L. McPherron RESISTIVITY SOUNDING - OUTLINE OF LECTURE 10 Wednesday April 23, 20031.0 STANDARD RESISTIVITY ARRAYS 1.1 WENNER ARRAY The Wenner array sk

San Diego State - ART - 496

PACMAN Do Candyland: Painting orange spots to disguise himself as a lollipop, PACMAN strolls around Candyland to munch on anything he can crunch. Getting tired of all the plain food he has been eating, no one can stop him once he arrives to this bonu

San Diego State - ART - 496

P ACMANDo CandylandPainting orange spots to disguise himself as a lollipop, PACMAN strolls around Candyland to munch on anything he can crunch. Getting tired of all the plain food he has been eating, no one can stop him once he arrives to this bonu

San Diego State - ART - 496

P ACMANDo CandylandPainting orange spots to disguise himself as a lollipop, PACMAN strolls around Candyland to munch on anything he can crunch. Getting tired of all the plain food he has been eating, no one can stop him once he arrives to this bonu

San Diego State - ART - 496

P ACMANDoes CandylandPainting orange spots to disguise himself as a lollipop, PACMAN strolls around Candyland to munch on anything he can crunch. Getting tired of all the plain food he has been eating, no one can stop him once he arrives to this bo

Colorado College - FACULTY - 121

Human Domination of Earths EcosystemsPeter M. Vitousek, Harold A. Mooney, Jane Lubchenco, Jerry M. MelilloHuman alteration of Earth is substantial and growing. Between one-third and one-half of the land surface has been transformed by human action;

Colorado College - FACULTY - 121

Arithmetic, Population, and EnergyDr. Albert BartlettDepartment of Physics, University of Colorado at Boulder, 80309-0390 Office, (303) 492-7016: Department (303) 492 6652: Home: (303) 443 0595 albert.bartlett@colorado.edu Dr. Bartlett is a retired

NYU - PYH - 207

Network Object in C+Final Project of HonorOS Professor David MazierePo-yen Huang (Dennis) Dong-rong Wen May 9, 2003Table of ContentAbstract ..3 Introduction .3 Architecture ..3 The idea ..3 More details helper classes .4 Dialogue between proxy

Midwestern State University - MATH - 201

Midwestern State University - MATH - 201

Berkeley - E - 1071

Support Vector MachinesThe Interface to libsvm in package e1071 by David Meyer Technische Universitt Wien, Austria a David.Meyer@ci.tuwien.ac.at January 6, 2009"Hype or Hallelujah?" is the provocative title used by Bennett & Campbell (2000) in a

Dallas - CS - 3345

VI TutorialVI is a very powerful text editor that is found on almost all UNIX platforms. It is available on all the UNIX machines that you may encounter in the School of Engineering network. Since vi is so ubiquitous, you will complete a short tu

Dallas - CS - 3345

#include <iostream>using namespace std;int main(){int x, y;x = 5;y = x + +x;cout < " x is " < x < " y is " < y < endl;x = 5;y = +x + x;cout < " x is " < x < " y is " < y < endl;x = 5;y = x+ + x;cout < " x is " < x < "

Dallas - CS - 3345

Object-Oriented Programming Using C+CLASS 21ObjectivesDeclare, initialize and use a pointer and an array of pointers Create a string Use built-in string functions2int main() { int a; / a is an integer int *aPtr; / aPtr is a pointer to an i

Dallas - CS - 3335

Course Professor Term MeetingsCS3335C/C+ KamranZ.Khan Spring2009 MW7:008:15PMECSS2.305ProfessorsContactInformation OfficePhone (214)2807124 OfficeLocation ECSS 3.411 EmailAddress kkhan@utdallas.edu OfficeHours MW6:007:00PM OtherInformation ClassW

Allan Hancock College - MECH - 2700

An Open Source ProjectNumerical PythonDavid Ascher Paul F. Dubois Konrad Hinsen Jim Hugunin Travis Oliphantwith contributions from the Numerical Python community.September 7, 2001Lawrence Livermore National Laboratory, Livermore, CA 94566 UCRL

Washington - ECON - 482

CHAPTER 6SOLUTIONS TO PROBLEMS 6.1 The generality is not necessary. The t statistic on roe2 is only about .30, which shows that roe2 is very statistically insignificant. Plus, having the squared term has only a minor effect on the slope even for lar

Virginia Tech - CS - 2604

Big-O AnalysisAsymptotics1Big-O ExampleTake the function obtained in the algorithm analysis example earlier:Asymptotics2Order of magnitude analysis requires a number of mathematical definitions and theorems. The most basic concept is com

Syracuse - CIS - 758

Network toolbox netwox - | KNOWN PROBLEMS | -This file describes known problems (incompatibilities, unsupportedfeatures, errors, etc.).If you seek help (u

Syracuse - CIS - 758

Network toolbox netwox - | KNOWN PROBLEMS | -This file describes known problems (incompatibilities, unsupportedfeatures, errors, etc.).If you seek help (u

Laurentian - ANTH - 3500

Lecture 1 is not available

Laurentian - ANTH - 3500

Lecture 2 is not available

Evansville - PS - 4802

JOURNAL OF BACTERIOLOGY, Aug. 2001, p. 45624570 0021-9193/01/$04.00 0 DOI: 10.1128/JB.183.15.45624570.2001 Copyright 2001, American Society for Microbiology. All Rights Reserved.Vol. 183, No. 15DNA Microarray-Mediated Transcriptional Profiling o

Evansville - PS - 4802

Proc. Natl. Acad. Sci. USA Vol. 96, pp. 67456750, June 1999 Cell BiologyBroad patterns of gene expression revealed by clustering analysis of tumor and normal colon tissues probed by oligonucleotide arraysU. A LON*, N. BARKAI*, D. A. NOTTERMAN*, K.

IUPUI - N - 361

Chapter 1: Introduction to Project ManagementInformation Technology Project Management, Fourth EditionLearning Objectives Understand the growing need for better project management, especially for information technology projects. Explain what a

IUPUI - N - 361

Chapter 2: The Project Management and Information Technology ContextInformation Technology Project Management, Fourth EditionLearning Objectives Describe the systems view of project management and how it applies to information technology proj

Washington University in St. Louis - MEXMRS - 0026

PDS_VERSION_ID = PDS3 RECORD_TYPE = STREAM OBJECT = TEXT PUBLICATION_DATE = 2005-07-26 NOTE

Washington University in St. Louis - MEXMRS - 0026

=Upfront Notes= This "aareadme.txt" file contains the description of the naming convention that will be used for all MEX kernels. One part of them will be directly produced by an automated system located at ESTEC,PST. Consequently, we c

Washington University in St. Louis - MEXMRS - 0026

$MEX ORBIT PROPAGATION AND TIMING GEOMETRY FILE v002* OPTG optg.out* TITLE 2004 Mars Express Mapping: OPTG File* CREATION JPL 04-MAR-19/10:10:04* BEGIN SCE 04-MAR-18/00:00:00.000* CUTOFF SCE 04-APR-21/00:00:00.000*

Washington University in St. Louis - MEXMRS - 0026

=MEX FK Files= Last Update: 10 NOV 2004 This "aareadme.txt" file describes the contents of the KERNELS/FK directory of the MEX SPICE data server. It also provides the file naming conventions used for the MEX FK kernels, and it provides id

Washington University in St. Louis - MEXMRS - 0026

=MEX CK Files= Last update: 10 NOV 2004 This "aareadme.txt" file describes the contents of the KERNELS/CK directory of the MEX SPICE data server. It also provides the file naming conventions used for the MEX CK kernels, and it provi

Washington University in St. Louis - MEXMRS - 0026

=MEX SPK Files= Last update: 10 NOV 2004 This "aareadme.txt" file describes the contents of the KERNELS/SPK directory of the MEX SPICE data server. It also provides the file naming conventions used for the MEX SPK kernels, and it pr

Washington University in St. Louis - MEXMRS - 0026

=MEX LSK Files= Last update: 22 MAR 2004 This "aareadme.txt" file describes the contents of the KERNELS/LSK directory. It also provides the file naming conventions used for the MEX LSK kernels, and it provides identification of the

Washington University in St. Louis - MEXMRS - 0026

=MEX SCLK Files= Last update: 22 MAR 2004 This "aareadme.txt" file describes the contents of the KERNELS/SCLK directory of the MEX SPICE data server. It also provides the file naming conventions used for the MEX SCLK kernels, and it

Washington University in St. Louis - MEXMRS - 0026

=MEX Orbit Number Files= Last update: 22 MAR 2004 This "aareadme.txt" file describes the contents of the KERNELS/ORBNUM directory of the MEX SPICE data server. It also provides the file naming conventions used for the MEX Orbit Numb