Documents Found!
As seen in
Less Work, Better Grades
Join
Course Hero
Access
best resources
Ace
your classes
Ace your courses with Course Hero!
|
|
|
Study Smarter, Score Higher
Here are the top 5 related documents
...CSS 465
Global Positioning System
Importance of Location
Maps Navigation Resource inventory Tracking vehicles
Location
First Coordinate
46 02 04 N 46 02 03.925 N
Second Coordinate
76 08 05 W 76 08 05.969W
2199606.518 2199572.459 16727330.06 1...
...CSS 465 _ Global Positioning Systems Spring 2006
Name
Due: Due at the beginning of next lab Lab Assignment #2: GPS Mapping / GIS Integration
Objectives: # Collect GPS data for Alumni Field # Process data in a GIS GPS DATA COLLECTION AND DOWNLOADIN...
...CSS 465 _ Global Positioning Systems Fall 2004
Name
Due: at the beginning of next lab Lab Assignment #4: Creating a final map
Objectives: # Update almanac. # Practice mission planning. # Complete final map from week 2 (1) Next week we will be perf...
...Lectures 5 - 7 Building Model Parameters
CSS 620 Spatial Modeling and Analysis
Review Project Proposals
Things we did this week
Anaglyph images of photos Ponds Kriging Updating DEM data
Arthur J. Lembo, Jr. Cornell University
Things to discu...
Document Content (unformatted)
Course Hero has millions of student submitted documents similar to the one
below including study guides, homework solutions, papers, exam answer keys and textbook solutions.
The MATLAB Language of Technical Computing Computation Visualization Programming MATLAB Function Reference Volume 1: A - E Version 6 How to Contact The MathWorks: www.mathworks.com comp.soft-sys.matlab 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 1: A - E COPYRIGHT 1984 - 2001 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 Target Language Compiler 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 First printing June 1997 Revised for 5.1 October 1997 Revised for 5.2 January 1999 Revised for Release 11 June 1999 Printed for Release 11 March 2000 Beta June 2001 Revised for 6.1 (for MATLAB 5) (online version) (online version) (online version) (online only) (online version) 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-3 1-3 1-3 1-4 1-4 1-5 1-6 1-6 Mathematics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-7 Arrays and Matrices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-8 Linear Algebra . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-10 Elementary Math . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-12 Data Analysis and Fourier Transforms . . . . . . . . . . . . . . . . . . 1-14 Polynomials . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-15 Interpolation and Computational Geometry . . . . . . . . . . . . . . 1-16 Coordinate System Conversion . . . . . . . . . . . . . . . . . . . . . . . . . 1-17 Nonlinear Numerical Methods . . . . . . . . . . . . . . . . . . . . . . . . . 1-17 Specialized Math . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-18 Sparse Matrices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-19 Math Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-21 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 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Spreadsheets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-22 1-22 1-26 1-27 1-30 1-34 1-34 1-34 1-35 1-35 1-35 i Scientific Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-36 Audio and Audio/Video . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-36 Images . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-37 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 and Identifying Objects . . . . . . . . . . . . . . . . . . . . . . . . GUI Utility Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Controlling Program Execution . . . . . . . . . . . . . . . . . . . . . . . . . 1-38 1-38 1-38 1-39 1-41 1-41 1-41 1-43 1-43 1-44 1-45 1-46 1-46 1-47 1-47 1-48 1-48 1-48 1-48 1-48 1-49 Alphabetical List of Functions 2 ii Contents 1 Functions By Category 1 Functions By Category The MATLAB Function Reference contains descriptions of all MATLAB commands and functions. If you know the name of a function, use the Alphabetical List of Functions to find the reference page. If you do not know the name of a function, select a category from the following table to see a list of related functions. You can also browse these tables to see what functionality MATLAB provides. Category Description Development Environment Mathematics Programming and Data Types 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 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, ActiveX, Serial Port functions. File I/O Graphics 3-D Visualization Creating Graphical User Interface External Interfaces See Simulink, Stateflow, Real-Time Workshop, and the individual toolboxes for lists of their functions 1-2 Development Environment Development Environment General functions for working in MATLAB, including functions for startup, Command Window, help, and editing and debugging. Category Description 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 Methods for finding information File, search path, variable management Editing and debugging, source control, profiling Identifying current computer, license, or product version Improving and assessing performance, e.g., 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 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 1-3 1 Functions By Category notebook unix Open M-book in Microsoft Word (Windows only) Execute UNIX command and return result Getting Help doc docopt help helpbrowser helpwin info lookfor support web whatsnew Display online documentation in MATLAB 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 filebrowser lookfor Change working directory Copy file Delete files or graphics objects Display directory listing Check if a variable or file exists Display Current Directory browser, a tool for viewing files Search for specified keyword in all help entries 1-4 Development Environment ls matlabroot mkdir pwd rehash type what which List directory on UNIX Return root directory of MATLAB installation Make new directory Display current directory Refresh function and file system caches 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 pathtool rmpath Add directories to MATLAB search path Generate path string Partial pathname View or change the MATLAB directory search path Open Set Path dialog box to view and change MATLAB path Remove directories from MATLAB search path Programming Tools Editing and Debugging Source Control Profiling 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-5 1 Functions By Category 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 Profiling profile profreport Optimize performance of M-file code Generate profile report System computer javachk license 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 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-6 Mathematics Mathematics Functions for working with arrays and matrices, linear algebra, data analysis, and other areas of mathematics. Category Description 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, nite differences, correlation, ltering and convolution, fourier transforms Multiplication, division, evaluation, roots, derivatives, integration, eigenvalue problem, curve tting, 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 Math Data Analysis and Fourier Transforms Polynomials Interpolation and Computational Geometry Coordinate System Conversion Nonlinear Numerical Methods Specialized Math 1-7 1 Functions By Category Category Description Sparse Matrices Elementary sparse matrices, operations, reordering algorithms, linear algebra, iterative methods, tree operations Pi, imaginary unit, in nity, Not-a-Number, largest and smallest positive oating point numbers, oating point relative accuracy Math Constants 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 1-8 Mathematics / ' .' .* .^ .\ ./ 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 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 Index into array, rearrange array Block diagonal concatenation 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 1-9 1 Functions By Category 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 meshgrid ndgrid ones rand randn repmat zeros 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 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 1-10 Mathematics Matrix Analysis cond condeig det norm normest null orth rank rcond rref subspace trace 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 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 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 1-11 1 Functions By Category schur svd svds 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 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 from QR factorization Insert column in 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 Inverse cosine and inverse hyperbolic cosine Inverse cotangent and inverse hyperbolic cotangent Inverse cosecant and inverse hyperbolic cosecant Inverse secant and inverse hyperbolic secant Inverse sine and inverse hyperbolic sine 1-12 Mathematics atan, atanh atan2 cos, cosh cot, coth csc, csch sec, sech sin, sinh tan, tanh Inverse tangent and inverse hyperbolic tangent Four-quadrant inverse tangent Cosine and hyperbolic cosine Cotangent and hyperbolic cotangent Cosecant and hyperbolic cosecant Secant and hyperbolic secant Sine and hyperbolic sine Tangent and hyperbolic tangent Exponential exp log log2 log10 nextpow2 pow2 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 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 (signed remainder after division) Remainder after division Signum 1-13 1 Functions By Category 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-14 Mathematics 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 fast Fourier transform Two-dimensional fast Fourier transform N-dimensional discrete Fourier Transform Shift DC component of fast Fourier transform to center of spectrum Inverse one-dimensional fast Fourier transform Inverse two-dimensional fast Fourier transform Inverse multidimensional fast 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 roots 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 coefficients Polynomial roots 1-15 1 Functions By Category 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 tetramesh trimesh triplot trisurf tsearch tsearchn Delaunay triangulation Three-dimensional Delaunay tessellation Multidimensional Delaunay tessellation Search for nearest point Multidimensional closest point search Tetrahedron mesh plot Triangular mesh plot Two-dimensional triangular plot Triangular surface plot Search for enclosing Delaunay triangle Multidimensional closest simplex search 1-16 Mathematics 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) Boundary Value Problems Partial Differential Equations Optimization Numerical Integration (Quadrature) Ordinary Differential Equations (IVP) deval ode113 ode15s Evaluate solution of differential equation problem Solve non-stiff differential equations, variable order method Solve stiff ODEs and DAEs Index 1, variable order method 1-17 1 Functions By Category ode23 ode23s ode23t ode23tb ode45 odeget odeset 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 Boundary Value Problems bvp4c bvpset bvpget deval Solve two-point boundary value problems for ODEs by collocation Create/alter BVP options structure Get BVP options parameters 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 optimset optimget 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 Create or alter optimization options structure Get optimization parameters from options structure Numerical Integration (Quadrature) quad quadl dblquad Numerically evaluate integral, adaptive Simpson quadrature (low order) Numerically evaluate integral, adaptive Lobatto quadrature (high order) Numerically evaluate double integral Specialized Math airy besselh besseli besselj besselk bessely beta 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 1-18 Mathematics betainc betaln ellipj ellipke erf erfc erfcinv erfcx erfinv expint gamma gammainc gammaln legendre 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 Sparse Matrices Elementary Sparse Matrices Full to Sparse Conversion Working with Sparse Matrices 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 1-19 1 Functions By Category 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 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 1-20 Mathematics 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-21 1 Functions By Category 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. Category Description 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 Numeric [ ] cat class find ipermute isa isequal isnumeric isreal Array constructor Concatenate arrays Return object s class name (e.g., numeric) Find indices and values of nonzero array elements Inverse permute dimensions of multidimensional array Detect object of given class (e.g., numeric) Determine if arrays are numerically equal Determine if item is numeric array Determine if all array elements are real numbers 1-22 Programming and Data Types permute reshape squeeze zeros Rearrange dimensions of multidimensional array 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 strcmp strcmpi strfind strmatch strncmp strncmpi strtok 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 Compare strings Compare strings, ignoring case Find one string within another Find possible matches for string Compare first n characters of strings Compare first n characters of strings, ignoring case First token in string 1-23 1 Functions By Category 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 getfield isa isequal isfield isstruct rmfield setfield struct struct2cell Cell array to structure array conversion Return object s class name (e.g., struct) Deal inputs to outputs Field names of structure Get field of structure array 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 Remove structure fields Set field of structure array Create structure array Structure to cell array conversion Cell Arrays { } cell cellfun cellstr cell2struct celldisp cellplot class deal isa iscell iscellstr isequal num2cell struct2cell Construct cell array Construct cell array Apply function to each element in cell array Create cell array of strings from character array 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 Convert numeric array into cell array Structure to cell array conversion Data Type Conversion Numeric double Convert to double-precision 1-24 Programming and Data Types int8 int16 int32 single uint8 uint16 uint32 String to Numeric base2dec bin2dec hex2dec hex2num str2double str2num Numeric to String char dec2base dec2bin dec2hex int2str mat2str num2str Other Conversions cell2struct datestr func2str logical num2cell str2func struct2cell Convert to signed 8-bit integer Convert to signed 16-bit integer Convert to signed 32-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 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 to structure array Convert serial date number to string Convert function handle to function name string Convert numeric to logical array Convert a numeric array to cell array Convert function name string to function handle Convert structure to cell array Determine Data Type is* isa iscell iscellstr ischar isfield 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 1-25 1 Functions By Category isjava islogical isnumeric isobject isstruct 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 isempty isequal isnumeric islogical length ndims numel size Display text or array Overloaded method to display text or array Determine if array is empty Determine if arrays are numerically equal 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 1-26 Programming and Data Types Array Manipulation : blkdiag cat 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 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 Operators and Operations Special Characters Arithmetic Operations Bit-wise Operations Relational Operations 1-27 1 Functions By Category 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 Bit-wise Operations bitand bitcmp bitor bitmax bitset bitshift bitget 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 1-28 Programming and Data Types bitxor 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 find is* isa iskeyword isvarname logical xor Logical AND Logical OR Logical NOT Test to determine if all elements are nonzero Test for any nonzero elements 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 Logical EXCLUSIVE OR Set Operations intersect ismember setdiff setxor union unique Set intersection of two vectors Detect members of set Return set difference of two vectors 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 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 1-29 1 Functions By Category etime now tic, toc weekday 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 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 inputname mfilename nargin nargout nargchk nargoutchk pcode script varargin varargout 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 Input argument name Name of currently running M-file Number of function input arguments Number of function output arguments Check number of input arguments Validate number of output arguments Create preparsed pseudocode file (P-file) Describes script M-file Accept variable number of arguments Return variable number of arguments Evaluation of Expressions and Functions builtin cellfun eval Execute builtin function from overloaded method Apply function to each element in cell array Interpret strings containing MATLAB expressions 1-30 Programming and Data Types evalc evalin feval iskeyword isvarname pause run script symvar tic, toc 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 Variables and Functions in Memory assignin global inmem isglobal mislocked mlock munlock pack persistent rehash Assign value to workspace variable Define global variables Return names of functions in memory Determine if item is global variable True if M-file cannot be cleared Prevent clearing M-file from memory Allow clearing M-file from memory Consolidate workspace memory Define persistent variable 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) 1-31 1 Functions By Category 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 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 import inmem isa isjava javaArray javaMethod javaObject methods 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, 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 1-32 Programming and Data Types methodsview which Display information on all methods implemented by class Display package and class name for method Error Handling catch error ferror lasterr lastwarn try warning Begin catch block of try/catch statement Display error message Query MATLAB about errors in file input or output Return last error message generated by MATLAB Return last warning message issued by MATLAB 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. Category Description Filename Construction Opening, Loading, Saving Files Low-Level File I/O Text Files Spreadsheets Scienti c Data Audio and Audio/Video Images Get path, directory, lename information; construct lenames Open les; transfer data between les and MATLAB workspace Low-level operations that use a le identi er (e.g., fopen, fseek, fread) Delimited or formatted I/O to text les 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 Load data from various types of files Load all or specific data from MAT or ASCII file 1-34 File I/O open save Open files of various types using appropriate editor or program Save all or specific data to MAT or ASCII file 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 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 SPARCstation-Specific Sound Functions Microsoft WAVE Sound Functions Audio Video Interleaved (AVI) Functions Microsoft Excel Functions Lotus123 Functions 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 1-36 File I/O 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 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 imfinfo imread imwrite 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. Category Description 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 le, convert to movie frames Printing and exporting gures to standard formats Creating graphics objects, setting properties, nding handles Basic Plots and Graphs box errorbar hold 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 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 Add contour labels to contour plot Date formatted tick labels 1-38 Graphics gtext legend texlabel title xlabel ylabel zlabel Place text on 2-D graph using mouse Graph legend for lines and patches Produce the TeX format from character string 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 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 contourc contourf ezcontour ezcontourf Contour (level curves) 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 Bit-Mapped Images frame2im image imagesc imfinfo im2frame imread imwrite ind2rgb Convert movie frame to indexed image Display image object Scale data and display image object Information about graphics file Convert image to movie frame Read image from graphics file Write image to graphics file Convert indexed image to RGB image Printing orient pagesetupdlg print printdlg printopt printpreview saveas 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 Handle Graphics Finding and Identifying Graphics Objects Object Creation Functions Figure Windows Axes Operations Finding and Identifying Graphics Objects allchild copyobj Find all children of specified objects Make copy of graphics object and its children 1-41 1 Functions By Category delete findall findobj gca gcbo gcbf gco get ishandle rotate set Delete files or graphics objects Find all graphics objects (including hidden handles) 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 Rotate objects about specified origin and direction 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) surface Create surface (quadrilaterals) text Create text object (character strings) uicontextmenu Create context menu (popup associated with object) Figure Windows capture clc clf close closereq drawnow gcf newplot refresh saveas Screen capture of the current figure Clear figure window Clear figure Close specified window Default close request function Complete any pending drawing Get current figure handle Graphics M-file preamble for NextPlot property Refresh figure Save figure or model to desired output format Axes Operations axis cla gca grid Plot axis scaling and appearance Clear Axes Get current Axes handle Grid lines for 2-D and 3-D plots 1-42 3-D Visualization 3-D Visualization Create and manipulate graphics that display 2-D matrix and 3-D volume data, controlling the view, lighting and transparency. Category Description 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 1-43 1 Functions By Category Domain Generation griddata meshgrid Data gridding and surface fitting Generation of X and Y arrays for 3-D plots Color Operations brighten caxis colorbar colordef colormap graymon hsv2rgb rgb2hsv rgbplot shading spinmap surfnorm whitebg Brighten or darken color map Pseudocolor axis scaling Display color bar (color scale) Set up color defaults Set the color look-up table (list of colormaps) Graphics figure defaults set for grayscale monitor Hue-saturation-value to red-green-blue conversion RGB to HSVconversion Plot color map Color shading mode Spin the colormap 3-D surface normals 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 1-44 3-D Visualization Selecting Region of Interest 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 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-45 1 Functions By Category 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-46 Creating Graphical User Interfaces Creating Graphical User Interfaces Predefined dialog boxes and functions to control GUI programs. Category Description Predefined Dialog Boxes Deploying User Interfaces Developing User Interfaces User Interface Objects Finding and Identifying Objects 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 callbacks Moving objects, text wrapping Wait and resume based on user input Predefined Dialog Boxes dialog errordlg helpdlg inputdlg listdlg msgbox pagedlg printdlg questdlg 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 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-47 1 Functions By Category 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 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 and Identifying Objects findall findfigs gcbf gcbo Find all graphics objects Display off-screen visible figure windows 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 objects textwrap Return wrapped string matrix for given uicontrol 1-48 Creating Graphical User Interfaces Controlling Program Execution uiresume uiwait Resumes program execution halted with uiwait Halts program execution, restart with uiresume 1-49 1 Functions By Category 1-50 2 Alphabetical List of Functions 2 Alphabetical List of Functions Arithmetic Operators + - * / \ ^ ' . . . . . . . . . . . . . . . . . . . . . . . Relational Operators < > <= >= == ~= . . . . . . . . . . . . . . Logical Operators & | ~ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Special Characters [ ] ( ) {} = ' . ... , ; % ! . . . . . . . . . . . . . . . . . . Colon : . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . abs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . acos, acosh . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . acot, acoth . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . acsc, acsch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . actxcontrol . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . actxserver . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . addframe . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . addpath . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . airy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . alim . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . all . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . allchild . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . alpha . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . alphamap . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ans . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . any . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . area . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . asec, asech . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . asin, asinh . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . assignin . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . atan, atanh . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . atan2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . audioplayer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . audiorecorder . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . auread . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . auwrite . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . avifile . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . aviinfo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . aviread . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . axes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Axes Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-10 2-18 2-20 2-22 2-25 2-27 2-28 2-30 2-32 2-34 2-37 2-38 2-40 2-42 2-44 2-45 2-47 2-48 2-51 2-53 2-54 2-55 2-57 2-59 2-61 2-63 2-65 2-67 2-69 2-72 2-76 2-77 2-78 2-81 2-83 2-84 2-96 2-2 axis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . balance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . bar, barh . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . bar3, bar3h . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . base2dec . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . beep . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . besselh . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . besseli, besselk . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . besselj, bessely . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . beta, betainc, betaln . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . bicg . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . bicgstab . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . bin2dec . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . bitand . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . bitcmp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . bitget . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . bitmax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . bitor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . bitset . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . bitshift . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . bitxor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . blanks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . blkdiag . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . box . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . break . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . brighten . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . builtin . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . bvp4c . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . bvpget . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . bvpinit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . bvpset . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . bvpval . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . calendar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . camdolly . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . camlight . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . camlookat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . camorbit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-117 2-123 2-126 2-130 2-134 2-135 2-136 2-138 2-141 2-144 2-146 2-154 2-159 2-160 2-161 2-162 2-163 2-164 2-165 2-166 2-167 2-168 2-169 2-170 2-171 2-172 2-173 2-174 2-181 2-182 2-184 2-186 2-187 2-188 2-190 2-192 2-194 2-3 2 Alphabetical List of Functions campan . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . campos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . camproj . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . camroll . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . camtarget . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . camup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . camva . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . camzoom . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . capture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . cart2pol . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . cart2sph . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . case . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . cat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . catch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . caxis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . cd . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . cdf2rdf . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . cdfinfo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . cdfread . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ceil . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . cell . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . cell2struct . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . celldisp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . cellfun . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . cellplot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . cellstr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . cgs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . char . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . checkin . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . checkout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . chol . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . cholinc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . cholupdate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . cla . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . clabel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . clc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-196 2-197 2-199 2-200 2-201 2-203 2-205 2-207 2-208 2-209 2-210 2-211 2-212 2-213 2-214 2-218 2-219 2-221 2-224 2-226 2-227 2-229 2-230 2-231 2-233 2-234 2-235 2-239 2-241 2-243 2-246 2-248 2-255 2-258 2-259 2-261 2-263 2-4 clear . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . clear (serial) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . clf . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . clipboard . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . clock . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . close . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . close (avifile) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . closereq . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . cmopts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . colamd . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . colmmd . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . colorbar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . colordef . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . colormap . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ColorSpec . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . colperm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . comet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . comet3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . compan . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . compass . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . complex . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . computer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . cond . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . condeig . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . condest . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . coneplot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . conj . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . continue . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . contour . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . contour3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . contourc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . contourf . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . contourslice . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . contrast . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . conv . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . conv2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . convhull . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-264 2-268 2-269 2-270 2-271 2-272 2-274 2-275 2-276 2-277 2-279 2-282 2-284 2-285 2-289 2-291 2-292 2-293 2-294 2-295 2-297 2-299 2-301 2-302 2-303 2-304 2-309 2-310 2-311 2-315 2-317 2-319 2-321 2-324 2-325 2-326 2-331 2-5 2 Alphabetical List of Functions convhulln . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . convn . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . copyfile . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . copyobj . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . corrcoef . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . cos, cosh . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . cot, coth . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . cov . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . cplxpair . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . cputime . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . cross . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . csc, csch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . csvread . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . csvwrite . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . cumprod . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . cumsum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . cumtrapz . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . curl . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . customverctrl . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . cylinder . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . daspect . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . date . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . datenum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . datestr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . datetick . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . datevec . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . dbclear . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . dbcont . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . dbdown . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . dblquad . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . dbmex . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . dbquit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . dbstack . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . dbstatus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . dbstep . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . dbstop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . dbtype . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-333 2-335 2-336 2-337 2-339 2-340 2-342 2-344 2-345 2-346 2-347 2-348 2-350 2-352 2-353 2-354 2-355 2-357 2-360 2-361 2-364 2-367 2-368 2-370 2-373 2-376 2-378 2-380 2-381 2-382 2-384 2-385 2-386 2-387 2-388 2-389 2-393 2-6 dbup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ddeadv . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ddeexec . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ddeinit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ddepoke . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ddereq . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ddeterm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ddeunadv . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . deal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . deblank . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . dec2base . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . dec2bin . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . dec2hex . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . deconv . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . default4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . del2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . delaunay . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . delaunay3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . delaunayn . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . delete . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . delete (activex) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . delete (serial) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . depdir . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . depfun . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . det . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . detrend . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . deval . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . diag . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . dialog . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . diary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . diff . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . dir . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . disp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . disp (serial) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . display . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . divergence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . dlmread . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-394 2-395 2-397 2-398 2-399 2-401 2-403 2-404 2-405 2-407 2-408 2-409 2-410 2-411 2-412 2-413 2-416 2-421 2-424 2-427 2-428 2-429 2-430 2-431 2-435 2-436 2-438 2-439 2-441 2-442 2-443 2-445 2-447 2-448 2-449 2-451 2-453 2-7 2 Alphabetical List of Functions dlmwrite . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . dmperm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . doc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . docopt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . dos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . dot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . double . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . dragrect . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . drawnow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . dsearch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . dsearchn . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . echo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . edit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . eig . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . eigs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ellipj . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ellipke . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ellipsoid . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . else . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . elseif . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . end . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . eomday . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . eps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . erf, erfc, erfcx, erfinv, erfcinv . . . . . . . . . . . . . . . . . . . . . . . . . error . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . errorbar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . errordlg . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . etime . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . etree . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . etreeplot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . eval . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . evalc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . evalin . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . exist . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . exit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . exp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . expint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-454 2-455 2-456 2-457 2-458 2-460 2-461 2-462 2-463 2-464 2-465 2-466 2-467 2-469 2-473 2-481 2-483 2-485 2-486 2-487 2-489 2-491 2-492 2-493 2-495 2-496 2-498 2-500 2-501 2-502 2-503 2-505 2-506 2-508 2-511 2-512 2-513 2-8 expm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . eye . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ezcontour . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ezcontourf . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ezmesh . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ezmeshc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ezplot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ezplot3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ezpolar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ezsurf . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ezsurfc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-514 2-516 2-517 2-520 2-523 2-525 2-527 2-529 2-531 2-532 2-535 2-9 Arithmetic Operators + - * / \ ^ ' Purpose Syntax 2Arithmetic Operators + - * / \ ^ ' Matrix and array arithmetic A+B A B A B A/B A\B A^B A' A. B A./B A.\B A.^B A.' Description MATLAB has two different types of arithmetic operations. Matrix arithmetic operations are defined by the rules of linear algebra. Array arithmetic operations are carried out element-by-element. The period character (.) distinguishes the array operations from the matrix operations. However, since the matrix and array operations are the same for addition and subtraction, the character pairs .+ and . are not used. + Addition or unary plus. A+B adds A and B. A and B must have the same size, unless one is a scalar. A scalar can be added to a matrix of any size. Subtraction or unary minus. A B subtracts B from A. A and B must have the same size, unless one is a scalar. A scalar can be subtracted from a matrix of any size. Matrix multiplication. C = A B is the linear algebraic product of the matrices A and B. More precisely, C ( i, j ) = * k=1 n A ( i, k )B ( k, j ) For nonscalar A and B, the number of columns of A must equal the number of rows of B. A scalar can multiply a matrix of any size. . Array multiplication. A. B is the element-by-element product of the arrays A and B. A and B must have the same size, unless one of them is a scalar. Slash or matrix right division. B/A is roughly the same as B inv(A). More precisely, B/A = (A'\B')'. See \. / 2-10 Arithmetic Operators + - * / \ ^ ' ./ \ Array right division. A./B is the matrix with elements A(i,j)/B(i,j). A and B must have the same size, unless one of them is a scalar. Backslash or matrix left division. If A is a square matrix, A\B is roughly the same as inv(A) B, except it is computed in a different way. If A is an n-by-n matrix and B is a column vector with n components, or a matrix with several such columns, then X = A\B is the solution to the equation AX = B computed by Gaussian elimination (see Algorithm for details). A warning message prints if A is badly scaled or nearly singular. If A is an m-by-n matrix with m ~= n and B is a column vector with m components, or a matrix with several such columns, then X = A\B is the solution in the least squares sense to the under- or overdetermined system of equations AX = B. The effective rank, k, of A, is determined from the QR decomposition with pivoting (see Algorithm for details). A solution X is computed which has at most k nonzero components per column. If k < n, this is usually not the same solution as pinv(A) B, which is the least squares solution with the smallest norm, ||X||. .\ ^ Array left division. A.\B is the matrix with elements B(i,j)/A(i,j). A and B must have the same size, unless one of them is a scalar. Matrix power. X^p is X to the power p, if p is a scalar. If p is an integer, the power is computed by repeated squaring. If the integer is negative, X is inverted rst. For other values of p, the calculation involves eigenvalues and eigenvectors, such that if [V,D] = eig(X), then X^p = V D.^p/V. If x is a scalar and P is a matrix, x^P is x raised to the matrix power P using eigenvalues and eigenvectors. X^P, where X and P are both matrices, is an error. .^ ' .' Array power. A.^B is the matrix with elements A(i,j) to the B(i,j) power. A and B must have the same size, unless one of them is a scalar. Matrix transpose. A' is the linear algebraic transpose of A. For complex matrices, this is the complex conjugate transpose. Array transpose. A.' is the array transpose of A. For complex matrices, this does not involve conjugation. 2-11 Arithmetic Operators + - * / \ ^ ' Remarks The arithmetic operators have M-file function equivalents, as shown: Binary addition Unary plus Binary subtraction Unary minus Matrix multiplication Array-wise multiplication Matrix right division Array-wise right division Matrix left division Array-wise left division Matrix power Array-wise power Complex transpose Matrix transpose A+B +A A B A A*B A.*B A/B A./B A\B A.\B A^B A.^B A' A.' plus(A,B) uplus(A) minus(A,B) uminus(A) mtimes(A,B) times(A,B) mrdivide(A,B) rdivide(A,B) mldivide(A,B) ldivide(A,B) mpower(A,B) power(A,B) ctranspose(A) transpose(A) Examples Here are two vectors, and the results of various matrix and array operations on them, printed with format rat. Matrix Operations x 1 2 3 1 5 7 9 2 3 Array Operations y 4 5 6 4 3 3 3 5 6 x' x+y y' x y 2-12 Arithmetic Operators + - * / \ ^ ' Matrix Operations x + 2 3 4 5 Error Array Operations x 2 1 0 1 4 10 18 Error Error x y x. y x' y x y' 32 4 8 12 2 4 6 16/7 5 10 15 6 12 18 x'. y x. y' x 2 x. 2 2 4 6 4 5/2 2 2 1 2/3 1/4 2/5 1/2 1/2 1 3/2 1 32 729 1 4 9 x\y x.\y 2\x 1/2 1 3/2 0 0 0 1/2 1 3/2 Error 0 0 0 1/6 1/3 1/2 2./x x/y x./y x/2 x./2 x^y x.^y x^2 Error x.^2 2-13 Arithmetic Operators + - * / \ ^ ' Matrix Operations 2^x Error Array Operations 2.^x 2 4 8 (x+i y)' (x+i y).' 1 4i 1 + 4i 2 5i 2 + 5i 3 6i 3 + 6i Algorithm The specific algorithm used for solving the simultaneous linear equations denoted by X = A\B and X = B/A depends upon the structure of the coefficient matrix A. If A is a triangular matrix, or a permutation of a triangular matrix, then X can be computed quickly by a permuted backsubstitution algorithm. The check for triangularity is done for full matrices by testing for zero elements and for sparse matrices by accessing the sparse data structure. Most nontriangular matrices are detected almost immediately, so this check requires a negligible amount of time. If A is symmetric, or Hermitian, and has positive diagonal elements, then a Cholesky factorization is attempted (see chol). If A is found to be positive definite, the Cholesky factorization attempt is successful and requires less than half the time of a general factorization. Nonpositive definite matrices are usually detected almost immediately, so this check also requires little time. If successful, the Cholesky factorization is A = R' R where R is upper triangular. The solution X is computed by solving two triangular systems, X = R\(R'\B) If A is sparse, a symmetric minimum degree preordering is applied (see symmmd and spparms). The algorithm is: perm = symmmd(A); R = chol(A(perm,perm)); y = R'\B(perm); X(perm,:) = R\y; % % % % Symmetric minimum degree reordering Cholesky factorization Lower triangular solve Upper triangular solve 2-14 Arithmetic Operators + - * / \ ^ ' If A is Hessenberg, it is reduced to an upper triangular matrix and that system is solved via substitution. If A is square, but not a permutation of a triangular matrix, or is not Hermitian with positive elements, or the Cholesky factorization fails, then a general triangular factorization is computed by Gaussian elimination with partial pivoting (see lu). This results in A = L U where L is a permutation of a lower triangular matrix and U is an upper triangular matrix. Then X is computed by solving two permuted triangular systems. X = U\(L\B) If A is sparse, a nonsymmetric minimum degree preordering is applied (see colmmd and spparms). The algorithm is perm = colmmd(A); [L,U,P] = lu(A(:,perm)); Y = L\(P*B); X(perm,:) = U\Y; % % % % Column minimum degree ordering Cholesky factorization Lower triangular solve Upper triangular solve If A is not square and is full, then Householder reflections are used to compute an orthogonal-triangular factorization. A P = Q R where P is a permutation, Q is orthogonal and R is upper triangular (see qr). The least squares solution X is computed with X = P (R\(Q' B) If A is not square and is sparse, then MATLAB computes a least squares solution using the sparse qr factorization of A. Note Backslash is not implemented for matrices A that are not square, and are also sparse and complex. 2-15 Arithmetic Operators + - * / \ ^ ' MATLAB uses LAPACK routines to compute the various full matrix factorizations: Matrix Real DLANGE, DPOTRF, DPOTRS, DPOCON DLANGE, DGESV, DGECON DGEQPF, DORMQR, DTRTRS Complex ZLANGE, ZPOTRF, ZPOTRS ZPOCON ZLANGE, ZGESV, ZGECON ZGEQPF, ZORMQR, ZTRTRS Full square, symmetric (Hermitian) positive de nite Full square, general case Full non-square For other cases (triangular and Hessenberg) MATLAB does not use LAPACK. Diagnostics From matrix division, if a square A is singular: Warning: Matrix is singular to working precision. From element-wise division, if the divisor has zero elements: Warning: Divide by zero. The matrix division returns a matrix with each element set to Inf; the element-wise division produces NaNs or Infs where appropriate. If the inverse was found, but is not reliable: Warning: Matrix is close to singular or badly scaled. Results may be inaccurate. RCOND = xxx From matrix division, if a nonsquare A is rank deficient: Warning: Rank deficient, rank = xxx tol = xxx See Also References det, inv, lu, orth, permute, ipermute, qr, rref [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, 2-16 Arithmetic Operators + - * / \ ^ ' LAPACK User s Guide (http://www.netlib.org/lapack/lug/ lapack_lug.html), Third Edition, SIAM, Philadelphia, 1999. 2-17 Relational Operators < Purpose Syntax > <= >= == ~= 2Relational Operators < Relational operations A A A A A A < B > B <= B >= B == B ~= B > <= >= == ~= Description The relational operators are <, , >, , ==, and ~=. Relational operators perform element-by-element comparisons between two arrays. They return an array of the same size, with elements set to logical true (1) where the relation is true, and elements set to logical false (0) where it is not. The operators <, , >, and use only the real part of their operands for the comparison. The operators == and ~= test real and imaginary parts. To test if two strings are equivalent, use strcmp, which allows vectors of dissimilar length to be compared. Examples If one of the operands is a scalar and the other a matrix, the scalar expands to the size of the matrix. For example, the two pairs of statements: X = 5; X >= [1 2 3; 4 5 6; 7 8 10] X = 5 ones(3,3); X >= [1 2 3; 4 5 6; 7 8 10] produce the same result: ans = 1 1 0 1 1 0 1 0 0 2-18 Relational Operators < > <= >= == ~= See Also all, any, find, strcmp The logical operators &, |, ~ 2-19 Logical Operators & | ~ Purpose Syntax 2Logical Operators & | ~ Logical operations A & B A | B ~A Description The symbols &, |, and ~ are the logical operators AND, OR, and NOT. They work element-wise on arrays, with 0 representing logical false (F), and anything nonzero representing logical true (T). The & operator does a logical AND, the| operator does a logical OR, and ~A complements the elements of A. The function xor(A,B) implements the exclusive OR operation. Truth tables for these operators and functions follow. Inputs A 0 0 1 1 and A&B 0 0 0 1 or A|B 0 1 1 1 xor xor(A,B) 0 1 1 0 NOT B 0 1 0 1 ~A 1 1 0 0 The precedence for the logical operators with respect to each other is: 1 not has the highest precedence. 2 and and or have equal precedence, and are evaluated from left to right. Remarks The logical operators have M-file function equivalents, as shown: and or not A&B A|B ~A and(A,B) or(A,B) not(A) Precedence of & and | Operators MATLAB always gives the & operator precedence over the | operator. Although MATLAB typically evaluates expressions from left to right, the 2-20 Logical Operators & | ~ expression a|b&c is evaluated as a|(b&c). It is a good idea to use parentheses to explicitly specify the intended precedence of statements containing combinations of & and |. Partial Evaluation Within the context of an if or while expression, MATLAB does not necessarily evaluate all parts of a logical expression. In some cases it is possible, and often advantageous, to determine whether an expression is true or false through only partial evaluation. For example, if A equals zero in statement 1 below, then the expression evaluates to false, regardless of the value of B. In this case, there is no need to evaluate B and MATLAB does not do so. In statement 2, if A is nonzero, then the expression is true, regardless of B. Again, MATLAB does not evaluate the latter part of the expression. 1) if (A & B) 2) if (A | B) You can use this property to your advantage to cause MATLAB to evaluate a part of an expression only if a preceding part evaluates to the desired state. Examples Here are some examples of using partial evaluation. while (b ~= 0) & (a/b > 18.5) if exist('myfun.m') & (myfun(x) >= y) if iscell(A) & all(cellfun('isreal', A)) See Also all, any, find, logical, xor The relational operators: <, <=, >, >=, ==, ~= 2-21 Special Characters [ ] ( ) {} = ' . ... , ; % ! Purpose Syntax Description [ ] 2Special Characters [ ] ( ) {} = ' . ... , ; % ! Special characters [ ] ( ) {} = ' . ... , ; % ! Brackets are used to form vectors and matrices. [6.9 9.64 sqrt( 1)] is a vector with three elements separated by blanks. [6.9, 9.64, i] is the same thing. [1+j 2 j 3] and [1 +j 2 j 3] are not the same. The rst has three elements, the second has ve. [11 12 13; 21 22 23] is a 2-by-3 matrix. The semicolon ends the rst row. Vectors and matrices can be used inside [ ] brackets. [A B;C] is allowed if the number of rows of A equals the number of rows of B and the number of columns of A plus the number of columns of B equals the number of columns of C. This rule generalizes in a hopefully obvious way to allow fairly complicated constructions. A = [ ] stores an empty matrix in A. A(m,:) = [ ] deletes row m of A. A(:,n) = [ ] deletes column n of A. A(n) = [ ] reshapes A into a column vector and deletes the third element. [A1,A2,A3...] = function assigns function output to multiple variables. For the use of [ and ] on the left of an = in multiple assignment statements, see lu, eig, svd, and so on. Curly braces are used in cell array assignment statements. For example, A(2,1) = {[1 2 3; 4 5 6]}, or A{2,2} = ('str'). See help paren for more information about { }. { } 2-22 Special Characters [ ] ( ) {} = ' . ... , ; % ! ( ) Parentheses are used to indicate precedence in arithmetic expressions in the usual way. They are used to enclose arguments of functions in the usual way. They are also used to enclose subscripts of vectors and matrices in a manner somewhat more general than usual. If X and V are vectors, then X(V) is [X(V(1)), X(V(2)), ..., X(V(n))]. The components of V must be integers to be used as subscripts. An error occurs if any such subscript is less than 1 or greater than the size of X. Some examples are X(3) is the third element of X. X([1 2 3]) is the first three elements of X. See help paren for more information about ( ). If X has n components, X(n: 1:1) reverses them. The same indirect subscripting works in matrices. If V has m components and W has n components, then A(V,W) is the m-by-n matrix formed from the elements of A whose subscripts are the elements of V and W. For example, A([1,5],:) = A([5,1],:) interchanges rows 1 and 5 of A. = Used in assignment statements. B = A stores the elements of A in B. == is the relational equals operator. See the Relational Operators page. Matrix transpose. X' is the complex conjugate transpose of X. X.' is the nonconjugate transpose. Quotation mark. 'any text' is a vector whose components are the ASCII codes for the characters. A quotation mark within the text is indicated by two quotation marks. ' . Decimal point. 314/100, 3.14 and .314e1 are all the same. Element-by-element operations. These are obtained using . , .^ , ./, or .\. See the Arithmetic Operators page. Field access. A.(field) and A(i).field, when A is a structure, access the contents of field. Parent directory. See cd. Continuation. Three or more points at the end of a line indicate continuation. . .. ... 2-23 Special Characters [ ] ( ) {} = ' . ... , ; % ! , Comma. Used to separate matrix subscripts and function arguments. Used to separate statements in multistatement lines. For multi-statement lines, the comma can be replaced by a semicolon to suppress printing. Semicolon. Used inside brackets to end rows. Used after an expression or statement to suppress printing or to separate statements. Percent. The percent symbol denotes a comment; it indicates a logical end of line. Any following text is ignored. MATLAB displays the rst contiguous comment lines in a M- le in response to a help command. Exclamation point. Indicates that the rest of the input line is issued as a command to the operating system. On the PC, adding & to the end of the ! command line, as in !dir &, causes the output to appear in a separate window. ; % ! Remarks Some uses of special characters have M-file function equivalents, as shown: Horizontal concatenation Vertical concatenation Subscript reference Subscript assignment [A,B,C...] [A;B;C...] A(i,j,k...) A(i,j,k...)= B horzcat(A,B,C...) vertcat(A,B,C...) subsref(A,S). See help subsref. subsasgn(A,S,B). See help subsasgn. See Also The arithmetic operators +, , *, /, \, ^, ' The relational operators <, <=, >, >=, ==, ~= The logical operators &, |, ~ 2-24 Colon : Purpose Description 2Colon : Create vectors, array subscripting, and for loop iterations The colon is one of the most useful operators in MATLAB. It can create vectors, subscript arrays, and specify for iterations. The colon operator uses the following rules to create regularly spaced vectors: j:k j:k j:i:k j:i:k is the same as [j,j+1,...,k] is empty if j > k is the same as [j,j+i,j+2i, ...,k] is empty if i > 0 and j > k or if i < 0 and j < k where i,j, and k are all scalars. Below are the definitions that govern the use of the colon to pick out selected rows, columns, and elements of vectors, matrices, and higher-dimensional arrays: A(:,j) A(i,:) A(:,:) A(j:k) A(:,j:k) A(:,:,k) A(i,j,k,:) A(:) is the j-th column of A is the i-th row of A is the equivalent two-dimensional array. For matrices this is the same as A. is A(j), A(j+1),...,A(k) is A(:,j), A(:,j+1),...,A(:,k) is the kth page of three-dimensional array A. is a vector in four-dimensional array A. The vector includes A(i,j,k,1), A(i,j,k,2), A(i,j,k,3), and so on. is all the elements of A, regarded as a single column. On the left side of an assignment statement, A(:) lls A, preserving its shape from before. In this case, the right side must contain the same number of elements as A. 2-25 Colon : Examples Using the colon with integers, D = 1:4 results in D = 1 2 3 4 Using two colons to create a vector with arbitrary real increments between the elements, E = 0:.1:.5 results in E = 0 0.1000 0.2000 0.3000 0.4000 0.5000 The command A(:,:,2) = pascal(3) generates a three-dimensional array whose first page is all zeros. A(:,:,1) = 0 0 0 0 0 0 A(:,:,2) = 1 1 1 2 1 3 0 0 0 1 3 6 See Also for, linspace, logspace, reshape 2-26 abs Purpose Syntax Description 2abs Absolute value and complex magnitude Y = abs(X) abs(X) returns the absolute value, X , for each element of X. If X is complex, abs(X) returns the complex modulus (magnitude), abs(X) = sqrt(real(X).^2 + imag(X).^2) Examples abs(-5) ans = 5 abs(3+4i) ans = 5 See Also angle, sign, unwrap 2-27 acos, acosh Purpose Syntax Description 2acos, acosh Inverse cosine and inverse hyperbolic cosine Y = acos(X) Y = acosh(X) The acos and acosh functions operate element-wise on arrays. The functions domains and ranges include complex values. All angles are in radians. Y = acos(X) returns the inverse cosine (arccosine) for each element of X. For real elements of X in the domain [ 1, 1 ] , acos(X) is real and in the range [ 0, ] . For real elements of X outside the domain [ 1, 1 ] , acos(X) is complex. Y = acosh(X) returns the inverse hyperbolic cosine for each element of X. Examples Graph the inverse cosine function over the domain 1 x 1, and the inverse hyperbolic cosine function over the domain 1 x . x = -1:.05:1; plot(x,acos(x)) x = 1:pi/40:pi; plot(x,acosh(x)) 3.5 2 1.8 3 1.6 2.5 1.4 1.2 1 0.8 1 0.6 0.4 0.5 0.2 0 -1 0 1 1.5 -0.8 -0.6 -0.4 -0.2 0 x 0.2 0.4 0.6 0.8 1 y=acosh(x) y=acos(x) 2 1.5 2 x 2.5 3 3.5 2-28 acos, acosh Algorithm acos and acosh use these algorithms. 1 -2 2 cos ( z) 1 = i log z + i ( 1 z ) 1 -2 cosh ( z ) = log z + ( z 1 ) 1 2 See Also cos, cosh 2-29 acot, acoth Purpose Syntax Description 2acot, acoth Inverse cotangent and inverse hyperbolic cotangent Y = acot(X) Y = acoth(X) The acot and acoth functions operate element-wise on arrays. The functions domains and ranges include complex values. All angles are in radians. Y = acot(X) returns the inverse cotangent (arccotangent) for each element of X. Y = acoth(X) returns the inverse hyperbolic cotangent for each element of X. Examples Graph the inverse cotangent over the domains 2 x < 0 and 0 < x 2 , and the inverse hyperbolic cotangent over the domains 30 x < 1 and 1 < x 30. x1 = -2*pi:pi/30:-0.1; x2 = 0.1:pi/30:2*pi; plot(x1,acot(x1),x2,acot(x2)) x1 = -30:0.1:-1.1; x2 = 1.1:0.1:30; plot(x1,acoth(x1),x2,acoth(x2)) 1.5 2 1.5 1 1 0.5 0.5 y=acoth(x) y=acot(x) 0 0 -0.5 -0.5 -1 -1 -1.5 -1.5 -8 -6 -4 -2 0 x1 x2 2 4 6 8 -2 -30 -20 -10 0 x1,x2 10 20 30 2-30 acot, acoth Algorithm acot and acoth use these algorithms. 1 cot 1 ( z ) = tan 1 -- z 1 coth 1 ( z ) = tanh 1 -- z See Also cot, coth 2-31 acsc, acsch Purpose Syntax Description 2acsc, acsch Inverse cosecant and inverse hyperbolic cosecant Y = acsc(X) Y = acsch(X) The acsc and acsch functions operate element-wise on arrays. The functions domains and ranges include complex values. All angles are in radians. Y = acsc(X) returns the inverse cosecant (arccosecant) for each element of X. Y = acsch(X) returns the inverse hyperbolic cosecant for each element of X. Examples Graph the inverse cosecant over the domains 10 x < 1 and 1 < x 10, and the inverse hyperbolic cosecant over the domains 20 x 1 and 1 x 20. x1 = -10:0.01:-1.01; x2 = 1.01:0.01:10; plot(x1,acsc(x1),x2,acsc(x2)) x1 = -20:0.01:-1; x2 = 1:0.01:20; plot(x1,acsch(x1),x2,acsch(x2)) 1.5 1 0.8 1 0.6 0.4 0.5 y=acsch(x) -8 -6 -4 -2 0 x1,x2 2 4 6 8 10 0.2 0 -0.2 -0.5 -0.4 -0.6 -1 -0.8 -1.5 -10 -1 -20 y=acsc(x) 0 -15 -10 -5 0 x1,x2 5 10 15 20 Algorithm acsc and acsch use these algorithms. 1 csc 1 ( z ) = sin 1 -- z 1 csch 1 ( z ) = sinh 1 -- z 2-32 acsc, acsch See Also csc, csch 2-33 actxcontrol Purpose Syntax 2actxcontrol Create an ActiveX control in a figure window. h =actxcontrol (progid [, position [, handle ... [,callback |{event1 eventhandler1; ... event2 eventhandler2; }]]]) progid Arguments String that is the name of the control to create. The control vendor provides this string. position Position vector containing the x and y location and the xsize and ysize of the control, expressed in pixel units as [x y xsize ysize]. Defaults to [20 20 60 60]. handle Handle Graphics handle of the figure window in which the control is to be created. If the control should be invisible, use the handle of an invisible figure window. Defaults to gcf. callback Name of an M-function that accepts a variable number of arguments. This function will be called whenever the control triggers an event. Each argument is converted to a MATLAB string; the first argument is always a string that represents the numerical value of the event that was triggered. These numerical values are defined by the control. (See the section, Writing Event Handlers in MATLAB External Interfaces, for more information on handling control events.) event Triggered event specified by either number or name. eventhandler Name of an M-function that accepts a variable number of arguments. This function will be called whenever the control triggers the event associated with it. The first argument is the activex object, the second number represents the numerical value of the event that was triggered. Note that the second number is not converted to a string as is the case in the callback M-file style. These values are defined by the control. See Writing Event Handlers in MATLAB External Interfaces for more information on handling control events. 2-34 actxcontrol Note There are two ways to handle events. You can create a single callback or you can specify a cell array that contains pairs of events and event handlers. In the cell array format, specify events by either number or name. Each control de nes event numbers and names. There is no limit to the number of pairs that can be speci ed in the cell array. Although using the single callback method may be easier in some cases, using the cell array technique creates more ef cient code that results in better performance. Returns A MATLAB activex object that represents the default interface for this control or server. Use the get, set, invoke, propedit, release, and delete methods on this object. A MATLAB error will be generated if this call fails. Create an ActiveX control at a particular location within a figure window. If the parent figure window is invisible, the control will be invisible. The returned MATLAB activex object represents the default interface for the control. This interface must be released through a call to release when it is no longer needed to free the memory and resources used by the interface. Note that releasing the interface does not delete the control itself (use the delete command to delete the control.) For an example callback event handler, see the file sampev.m in the toolbox\matlab\winfun directory. Description Example Callback style: f = figure ('pos', [100 200 200 200]); % create the control to fill the figure h = actxcontrol ('MWSAMP.MwsampCtrl.1', [0 0 200 200], ... gcf, 'sampev') Cell array style: h = actxcontrol ('SELECTOR.SelectorCtrl.l', ... [0 0 200 200], f, {-600 'myclick'; -601 'my2click'; ... -605 'mymoused'}) h = actxcontrol ('SELECTOR.SelectorCtrl.l', ... [0 0 200 200], f, {'Click' 'myclick'; ... 2-35 actxcontrol 'DblClick' 'my2click'; 'MouseDown' 'mymoused'}) where the event handlers, myclick.m, my2click.m, and mymoused.m are function myclick(varargin) disp('Single click function') function my2click(varargin) disp('Double click function') function mymoused(varargin) disp('You have reached the mouse down function') disp('The X position is: ') varargin(5) disp('The Y position is: ') varargin(6) You can use the same event handler for all the events you want to monitor using the cell array pairs. Response time will be better than using the callback style. For example h = actxcontrol('SELECTOR.SelectorCtrl.1', ... [0 0 200 200], f, {'Click' 'allevents'; ... 'DblClick' 'allevents'; 'MouseDown' 'allevents'}) and allevents.m is function allevents(varargin) if (varargin{2} = -600) disp ('Single Click Event Fired') elseif (varargin{2} = -601) disp ('Double Click Event Fired') elseif (varargin{2} = -605) disp ('Mousedown Event Fired') end 2-36 actxserver Purpose Syntax Arguments 2actxserver Create an ActiveX automation server and return an activex object for the server s default interface. h = actxserver (progid [, MachineName]) progid This is a string that is the name of the control to instantiate. This string is provided by the control or server vendor and should be obtained from the vendor s documentation. For example, the progid for Microsoft Excel is Excel.Application. MachineName This is the name of a remote machine on which the server is to be run. This argument is optional and is used only in environments that support Distributed Component Object Model (DCOM) see Using MATLAB As a DCOM Server Client in MATLAB External Interfaces. This can be an IP address or a DNS name. Returns An activex object that represents the server s default interface. Use the get, set, invoke, release, and delete methods on this object. A MATLAB error will be generated if this call fails. Create an ActiveX automation server and return a MATLAB activex object that represents the server s default interface. Local/Remote servers differ from controls in that they are run in a separate address space (and possibly on a separate machine) and are not part of the MATLAB process. Additionally, any user interface that they display will be in a separate window and will not be attached to the MATLAB process. Examples of local servers are Microsoft Excel and Microsoft Word. Note that automation servers do not use callbacks or event handlers. % Launches Microsoft Excel and makes main frame window visible. h = actxserver ('Excel.Application') set (h, 'Visible', 1); Description Example 2-37 addframe Purpose Syntax 2addframe Add a frame to an Audio Video Interleaved (AVI) file. aviobj aviobj aviobj aviobj = = = = addframe(aviobj,frame) addframe(aviobj,frame1,frame2,frame3,...) addframe(aviobj,mov) addframe(aviobj,h) Description aviobj = addframe(aviobj,frame) appends the data in frame to the AVI file identified by aviobj, which was created by a previous call to avifile. frame can be either an indexed image (m-by-n) or a truecolor image (m-by-n-by-3) of double or uint8 precision. If frame is not the first frame added to the AVI file, it must be consistent with the dimensions of the previous frames. addframe returns a handle to the updated AVI file object, aviobj. For example, addframe updates the TotalFrames property of the AVI file object each time it adds a frame to the AVI file. aviobj = addframe(aviobj,frame1,frame2,frame3,...) adds multiple frames to an AVI file. aviobj = addframe(aviobj,mov) appends the frame(s) contained in the MATLAB movie, mov, to the AVI file, aviobj. MATLAB movies that store frames as indexed images use the colormap in the first frame as the colormap for the AVI file, unless the colormap has been previously set. aviobj = addframe(aviobj,h) captures a frame from the figure or axis handle h, and appends this frame to the AVI file. addframe renders the figure into an offscreen array before appending it to the AVI file. This ensures that the figure is written correctly to the AVI file even if the figure is obscured on the screen by another window or screen saver. Note If an animation uses XOR graphics, you must use getframe to capture the graphics into a frame of a MATLAB movie. You can then add the frame to an AVI movie using the addframe syntax, aviobj = addframe(aviobj,mov). See the example for an illustration. Example This example calls addframe to add frames to the AVI file object, aviobj. 2-38 addframe fig=figure; set(fig,'DoubleBuffer','on'); set(gca,'xlim',[-80 80],'ylim',[-80 80],... 'nextplot','replace','Visible','off') aviobj = avifile('example.avi') x = -pi:.1:pi; radius = 0:length(x); for i=1:length(x) h = patch(sin(x)*radius(i),cos(x)*radius(i),... [abs(cos(x(i))) 0 0]); set(h,'EraseMode','xor'); frame = getframe(gca); aviobj = addframe(aviobj,frame); end aviobj = close(aviobj); See Also avifile, close, movie2avi 2-39 addpath Purpose Graphical Interface Syntax 2addpath Add directories to MATLAB search path As an alternative to the addpath function, use the Set Path dialog box. To open it, select Set Path from the File menu in the MATLAB desktop. addpath('directory') addpath('dir','dir2','dir3' ...) addpath('dir','dir2','dir3' ...'-flag') addpath dir1 dir2 dir3 ... -flag addpath('directory') prepends the specified directory to MATLAB s current Description search path, that is, it adds them to the front of the path. Use the full pathname for directory. addpath('dir','dir2','dir3' ...) prepends all the specified directories to the path. Use the full pathname for each dir. addpath('dir','dir2','dir3' ...'-flag') either prepends or appends the specified directories to the path depending on the value of flag. ag Argument 0 or begin 1 or end Result Prepend specified directories Append specified directories addpath dir1 dir2 dir3 ... -flag is the unquoted form of the syntax. Examples For the current path, viewed by typing path, MATLABPATH c:\matlab\toolbox\general c:\matlab\toolbox\ops c:\matlab\toolbox\strfun you can add c:\matlab\mymfiles to the front of the path by typing addpath('c:\matlab\mymfiles') 2-40 addpath Verify that the files were added to the path by typing path and MATLAB returns MATLABPATH c:\matlab\mymfiles c:\matlab\toolbox\general c:\matlab\toolbox\ops c:\matlab\toolbox\strfun See Also path, pathtool, genpath, rehash, rmpath 2-41 airy Purpose Syntax 2airy Airy functions W = airy(Z) W = airy(k,Z) [W,ierr] = airy(k,Z) De nition The Airy functions form a pair of linearly independent solutions to d W d Z2 2 ZW = 0 The relationship between the Airy and modified Bessel functions is 1 Ai ( Z ) = -- Z 3 Bi ( Z ) = where 2 3 2 = -- Z 3 K 1 3( ) Z 3 [ I 1 3 ( ) + I 1 3 ( ) ] Description W = airy(Z) returns the Airy function, Ai ( Z ) , for each element of the complex array Z. W = airy(k,Z) returns different results depending on the value of k. k 0 1 2 3 Returns The same result as airy(Z). The derivative, Ai ( Z ) . The Airy function of the second kind, Bi ( Z ) . The derivative, Bi ( Z ) . 2-42 airy [W,ierr] = airy(k,Z) also returns an array of error flags. ierr = 1 ierr = 2 ierr = 3 ierr = 4 ierr = 5 Illegal arguments. Over ow. Return Inf. Some loss of accuracy in argument reduction. Unacceptable loss of accuracy, Z too large. No convergence. Return NaN. See Also References besseli, besselj, besselk, bessely [1] [Amos, D. E., A Subroutine Package for Bessel Functions of a Complex Argument and Nonnegative Order, Sandia National Laboratory Report, SAND85-1018, May, 1985. [2] Amos, D. E., A Portable Package for Bessel Functions of a Complex Argument and Nonnegative Order, Trans. Math. Software, 1986. 2-43 alim Purpose Syntax 2alim Set or query the axes alpha limits alpha_limits = alim alim([amin amax]) alim_mode = alim('mode') alim('alim_mode') alim(axes_handle,...) alpha_limits = alim returns the alpha limits (the axes ALim property) of the Description current axes. alim([amin amax]) sets the alpha limits to the specified values. amin is the value of the data mapped to the first alpha value in the alphamap, and amax is the value of the data mapped to the last alpha value in the alphamap. Data values in between are linearly interpolated across the alphamap, while data values outside are clamped to either the first or last alphamap value, whichever is closest. alim_mode = alim('mode') returns the alpha limits mode (the axes ALimMode property) of the current axes. alim('alim_mode') sets the alpha limits mode on the current axes. alim_mode can be: auto MATLAB automatically sets the alpha limits based on the alpha data of the objects in the axes. manual MATLAB does not change the alpha limits. alim(axes_handle,...) operates on the specified axes. See Also alpha, alphamap, caxis Axes ALim and ALimMode properties Patch FaceVertexAlphaData property Image and surface AlphaData properties 2-44 all Purpose Syntax Description 2all Test to determine if all elements are nonzero B = all(A) B = all(A,dim) B = all(A) tests whether all the elements along various dimensions of an array are nonzero or logical true (1). If A is a vector, all(A) returns logical true (1) if all of the elements are nonzero, and returns logical false (0) if one or more elements are zero. If A is a matrix, all(A) treats the columns of A as vectors, returning a row vector of 1s and 0s. If A is a multidimensional array, all(A) treats the values along the first non-singleton dimension as vectors, returning a logical condition for each vector. B = all(A,dim) tests along the dimension of A specified by scalar dim. 1 1 1 1 1 0 1 1 0 1 0 A all(A,1) all(A,2) Examples Given, A = [0.53 0.67 0.01 0.38 0.07 0.42 0.69] then B = (A < 0.5) returns logical true (1) only where A is less than one half: 0 0 1 1 1 1 0 The all function reduces such a vector of logical conditions to a single condition. In this case, all(B) yields 0. This makes all particularly useful in if statements, if all(A < 0.5) do something end 2-45 all where code is executed depending on a single condition, not a vector of possibly conflicting conditions. Applying the all function twice to a matrix, as in all(all(A)), always reduces it to a scalar condition. all(all(eye(3))) ans = 0 See Also any, logical operators, relational operators, colon Other functions that collapse an array s dimensions include: max, mean, median, min, prod, std, sum, trapz 2-46 allchild Purpose Syntax Description 2allchild Find all children of specified objects child_handles = allchild(handle_list) child_handles = allchild(handle_list) returns the list of all children (including ones with hidden handles) for each handle. If handle_list is a single element, allchild returns the output in a vector. Otherwise, the output is a cell array. Examples Compare the results returned by these two statements. get(gca,'Children') allchild(gca) See Also findall, findobj 2-47 alpha Purpose Syntax 2alpha Set transparency properties for objects in current axes alpha(face_alpha) alpha(alpha_data) alpha(alpha_data_mapping) alpha(object_handle,...) alpha sets one of three transparency properties, depending on what arguments Description you specify with the call to this function. FaceAlpha alpha(face_alpha) set the FaceAlpha property of all image, patch, and surface objects in the current axes. You can set face_alpha to: a scalar set the FaceAlpha property to the specified value (for images, set the AlphaData property to the specified value) 'flat' set the FaceAlpha property to flat 'interp' set the FaceAlpha property to interp 'texture' set the FaceAlpha property to texture 'opaque' set the FaceAlpha property to 1 'clear' set the FaceAlpha property to 0 See Specifying a Single Transparency Value for more information. AlphaData (Surface Objects) alpha(alpha_data) sets the AlphaData property of all surface objects in the current axes. You can set alpha_data to: a matrix the same size as CData sets the AlphaData property to the specified values 'x' set the AlphaData property to be the same as XData 'y' set the AlphaData property to be the same as YData 'z' set the AlphaData property to be the same as ZData 'color' set the AlphaData property to be the same as CData 2-48 alpha 'rand' set the AlphaData property to a matrix of random values equal in size to CData AlphaData (Image Objects) alpha(alpha_data) sets the AlphaData property of all image objects in the current axes. You can set alpha_data to: a matrix the same size as CData sets the AlphaData property to the specified value 'x' ignored 'y' ignored 'z' ignored 'color' set the AlphaData property to be the same as CData 'rand' set the AlphaData property to a matrix of random values equal in size to CData FaceVertexAlphaData (Patch Objects) alpha(alpha_data) sets the FaceVertexAlphaData property of all patch objects in the current axes. You can set alpha_data to: a matrix the same size as FaceVertexCData sets the FaceVertexAlphaData property to the specified value 'x' set the FaceVertexAlphaData property to be the same as Vertices(:,1) 'y' set the FaceVertexAlphaData property to be the same as Vertices(:,2) 'z' set the FaceVertexAlphaData property to be the same as Vertices(:,3) 'color' set the FaceVertexAlphaData property to be the same as FaceVertexCData 'rand' set the FaceVertexAlphaData property to random values See Mapping Data to Transparency for more information. 2-49 alpha AlphaDataMapping alpha(alpha_data_mapping) sets the AlphaDataMapping property of all image, patch, and surface objects in the current axes. You can set alpha_data_mapping to: 'scaled' set the AlphaDataMapping property to scaled 'direct' set the AlphaDataMapping property to direct 'none' set the AlphaDataMapping property to none alpha(object_handle,value) set the transparency property only on the object identified by object_handle See Also alim, alphamap Image: AlphaData, AlphaDataMapping Patch: FaceAlpha, FaceVertexAlphaData, AlphaDataMapping Surface: FaceAlpha, AlphaData, AlphaDataMapping Transparency in 3-D Visualization 2-50 alphamap Purpose Syntax 2alphamap Specify the figure alphamap (transparency) alphamap(alpha_map) alphamap('parameter') alphamap('parameter',length) alphamap('parameter ,delta) alphamap(figure_handle,...) alpha_map = alphamap alpha_map = alphamap(figure_handle) alpha_map = alphamap( parameter ) alphamap enables you to set or modify a figure s Alphamap property. Unless you specify a figure handle as the first argument, alphamap operates on the current Description figure. alphamap(alpha_map) set the AlphaMap of the current figure to the specified m-by-1 array of alpha values. alphamap('parameter') create a new or modify the current alphamap. You can specify the following parameters: default set the AlphaMap property to the figure s default alphamap rampup create a linear alphamap with increasing opacity (default length equals the current alphamap length) rampdown create a linear alphamap with decreasing opacity (default length equals the current alphamap length) vup create an alphamap that is opaque in the center and becomes more transparent linearly towards the beginning and end (default length equals the current alphamap length) vdown create an alphamap that is transparent in the center and becomes more opaque linearly towards the beginning and end (default length equals the current alphamap length) increase modify the alphamap making it more opaque (default delta is .1, which is added to the current values) decrease modify the alphamap making it more transparent (default delta is .1, which is subtracted from the current values) 2-51 alphamap spin rotate the current alphamap (default delta is 1; note that delta must be an integer) alphamap('parameter',length) creates a new alphamap with the length specified by length (used with parameters: rampup, rampdown, vup, vdown) alphamap('parameter',delta) modifies the existing alphamap using the value specified by delta (used with parameters: increase, decrease, spin). alphamap(figure_handle,...) performs the operation on the alphamap of the figure identified by figure_handle. alpha_map = alphamap return the current alphamap. alpha_map = alphamap(figure_handle) returns the current alphamap from the figure identified by figure_handle. alpha_map = alphamap( parameter ) retruns the alphamap modified by the parameter, but does not set the AlphaMap property. See Also alim, alpha Image: AlphaData, AlphaDataMapping Patch: FaceAlpha, AlphaData, AlphaDataMapping Surface: FaceAlpha, AlphaData, AlphaDataMapping 2-52 angle Purpose Syntax Description 2angle Phase angle P = angle(Z) P = angle(Z) returns the phase angles, in radians, for each element of complex array Z. The angles lie between . For complex Z, the magnitude and phase angle are given by R = abs(Z) theta = angle(Z) % magnitude % phase angle and the statement Z = R.*exp(i*theta) converts back to the original complex Z. Examples Z = 1.0000 1.0000 1.0000 1.0000 + + 1.0000i 2.0000i 3.0000i 4.0000i 2.0000 2.0000 2.0000 2.0000 + + - 1.0000i 2.0000i 3.0000i 4.0000i 3.0000 3.0000 3.0000 3.0000 + + 1.0000i 2.0000i 3.0000i 4.0000i 4.0000 4.0000 4.0000 4.0000 + + - 1.0000i 2.0000i 3.0000i 4.0000i P = angle(Z) P = -0.7854 1.1071 -1.2490 1.3258 0.4636 -0.7854 0.9828 -1.1071 -0.3218 0.5880 -0.7854 0.9273 0.2450 -0.4636 0.6435 -0.7854 Algorithm angle can be expressed as: angle(z) = imag(log(z)) = atan2(imag(z),real(z)) See Also abs, unwrap 2-53 ans Purpose Syntax Description Examples 2ans The most recent answer ans The ans variable is created automatically when no output argument is specified. The statement 2+2 is the same as ans = 2+2 See Also display 2-54 any Purpose Syntax Description 2any Test for any nonzeros B = any(A) B = any(A,dim) B = any(A) tests whether any of the elements along various dimensions of an array are nonzero or logical true (1). If A is a vector, any(A) returns logical true (1) if any of the elements of A are nonzero, and returns logical false (0) if all the elements are zero. If A is a matrix, any(A) treats the columns of A as vectors, returning a row vector of 1s and 0s. If A is a multidimensional array, any(A) treats the values along the first non-singleton dimension as vectors, returning a logical condition for each vector. B = any(A,dim) tests along the dimension of A specified by scalar dim. 1 0 1 0 0 0 1 0 1 1 0 A any(A,1) any(A,2) Examples Given, A = [0.53 0.67 0.01 0.38 0.07 0.42 0.69] then B = (A < 0.5) returns logical true (1) only where A is less than one half: 0 0 1 1 1 1 0 The any function reduces such a vector of logical conditions to a single condition. In this case, any(B) yields 1. This makes any particularly useful in if statements, if any(A < 0.5) do something end 2-55 any where code is executed depending on a single condition, not a vector of possibly conflicting conditions. Applying the any function twice to a matrix, as in any(any(A)), always reduces it to a scalar condition. any(any(eye(3))) ans = 1 See Also all, logical operators, relational operators, colon Other functions that collapse an array s dimensions include: max, mean, median, min, prod, std, sum, trapz 2-56 area Purpose Syntax 2area Area fill of a two-dimensional plot area(Y) area(X,Y) area(...,ymin) area(...,'PropertyName',PropertyValue,...) h = area(...) Description An area plot displays elements in Y as one or more curves and fills the area beneath each curve. When Y is a matrix, the curves are stacked showing the relative contribution of each row element to the total height of the curve at each x interval. area(Y) plots the vector Y or the sum of each column in matrix Y. The x-axis automatically scales depending on length(Y) when Y is a vector and on size(Y,1)when Y is a matrix. area(X,Y) plots Y at the corresponding values of X. If X is a vector, length(X) must equal length(Y) and X must be monotonic. If X is a matrix, size(X) must equal size(Y) and each column in X must be monotonic. To make a vector or matrix monotonic, use sort. area(...,ymin) specifies the lower limit in the y direction for the area fill. The default ymin is 0. area(...,'PropertyName',PropertyValue,...) specifies property name and property value pairs for the patch graphics object created by area. h = area(...) returns handles of patch graphics objects. area creates one patch object per column in Y. Remarks area creates one curve from all elements in a vector or one curve per column in a matrix. The colors of the curves are selected from equally spaced intervals throughout the entire range of the colormap. Examples Plot the values in Y as a stacked area plot. Y = [ 1, 5, 3; 3, 2, 7; 2-57 area 1, 5, 3; 2, 6, 1]; area(Y) grid on colormap summer set(gca,'Layer','top') title 'Stacked Area Plot' Stacked Area Plot 12 10 8 6 4 2 0 1 1.5 2 2.5 3 3.5 4 See Also plot 2-58 asec, asech Purpose Syntax Description 2asec, asech Inverse secant and inverse hyperbolic secant Y = asec(X) Y = asech(X) The asec and asech functions operate element-wise on arrays. The functions domains and ranges include complex values. All angles are in radians. Y = asec(X) returns the inverse secant (arcsecant) for each element of X. Y = asech(X) returns the inverse hyperbolic secant for each element of X. Examples Graph the inverse secant over the domains 1 x 5 and 5 x 1, and the inverse hyperbolic secant over the domain 0 < x 1. x1 = -5:0.01:-1; x2 = 1:0.01:5; plot(x1,asec(x1),x2,asec(x2)) x = 0.01:0.001:1; plot(x,asech(x)) 3.5 1 0.8 3 0.6 2.5 0.4 0.2 0 -0.2 -0.4 -0.6 0.5 -0.8 0 -5 -1 -20 y=asec(x) 2 1.5 1 -4 -3 -2 -1 0 x1,x2 1 2 3 4 5 y=acsch(x) -15 -10 -5 0 x1,x2 5 10 15 20 2-59 asec, asech Algorithm asec and asech use these algorithms. 1 sec 1 ( z ) = cos 1 -- z 1 sech 1 ( z ) = cosh 1 -- z See Also sec, sech 2-60 asin, asinh Purpose Syntax Description 2asin, asinh Inverse sine and inverse hyperbolic sine Y = asin(X) Y = asinh(X) The asin and asinh functions operate element-wise on arrays. The functions domains and ranges include complex values. All angles are in radians. Y = asin(X) returns the inverse sine (arcsine) for each element of X. For real elements of X in the domain [ 1, 1 ] , asin(X) is in the range [ 2, 2 ] . For real elements of x outside the range [ 1, 1 ] , asin(X) is complex. Y = asinh(X) returns the inverse hyperbolic sine for each element of X. Examples Graph the inverse sine function over the domain 1 x 1, and the inverse hyperbolic sine function over the domain 5 x 5. x = -1:.01:1; plot(x,asin(x)) x = -5:.01:5; plot(x,asinh(x)) 2 2.5 2 1.5 1.5 1 1 0.5 y=asinh(x) -0.8 -0.6 -0.4 -0.2 0 x 0.2 0.4 0.6 0.8 1 y=asin(x) 0.5 0 -0.5 -1 -1 -1.5 -1.5 -2 -2.5 -5 0 -0.5 -2 -1 -4 -3 -2 -1 0 x 1 2 3 4 5 2-61 asin, asinh Algorithm asin and asinh use these algorithms. 1 -2 2 sin ( z) 1 = i log iz + ( 1 z ) 1 -2 sinh ( z ) = log z + ( z + 1 ) 1 2 See Also sin, sinh 2-62 assignin Purpose Syntax Description 2assignin Assign a value to a workspace variable assignin(ws,'var',val) assignin(ws,'var',val) assigns the value val to the variable var in the workspace ws. var is created if it doesn t exist. ws can have a value of 'base' or 'caller' to denote the MATLAB base workspace or the workspace of the caller function. The assignin function is particularly useful for these tasks: Exporting data from a function to the MATLAB workspace Within a function, changing the value of a variable that is defined in the workspace of the caller function (such as a variable in the function argument list) Remarks The MATLAB base workspace is the workspace that is seen from the MATLAB command line (when not in the debugger). The caller workspace is the workspace of the function that called the M-file. Note the base and caller workspaces are equivalent in the context of an M-file that is invoked from the MATLAB command line. This example creates a dialog box for the image display function, prompting a user for an image name and a colormap name. The assignin function is used to export the user entered values to the MATLAB workspace variables imfile and cmap. prompt = {'Enter image name:','Enter colormap name:'}; title = 'Image display - assignin example'; lines = 1; def = {'my_image','hsv'}; answer = inputdlg(prompt,title,lines,def); assignin('base','imfile',answer{1}); assignin('base','cmap',answer{2}); Examples 2-63 assignin See Also evalin 2-64 atan, atanh Purpose Syntax Description 2atan, atanh Inverse tangent and inverse hyperbolic tangent Y = atan(X) Y = atanh(X) The atan and atanh functions operate element-wise on arrays. The functions domains and ranges include complex values. All angles are in radians. Y = atan(X) returns the inverse tangent (arctangent) for each element of X. For real elements of X, atan(X) is in the range [ 2, 2 ] . Y = atanh(X) returns the inverse hyperbolic tangent for each element of X. Examples Graph the inverse tangent function over the domain 20 x 20, and the inverse hyperbolic tangent function over the domain 1 < x < 1. x = -20:0.01:20; plot(x,atan(x)) x = -0.99:0.01:0.99; plot(x,atanh(x)) 2 3 1.5 2 1 1 0.5 y=atanh(x) y=atan(x) 0 0 -0.5 -1 -1 -2 -1.5 -3 -1 -2 -20 -15 -10 -5 0 x 5 10 15 20 -0.8 -0.6 -0.4 -0.2 0 x 0.2 0.4 0.6 0.8 1 2-65 atan, atanh Algorithm atan amd atanh use these algorithms. i i+z tan 1 ( z ) = --- log ---------- i z 2 1+z 1 tanh 1 ( z ) = -- log ----------- 1 z 2 See Also atan2, tan, tanh 2-66 atan2 Purpose Syntax Description 2atan2 Four-quadrant inverse tangent P = atan2(Y,X) P = atan2(Y,X) returns an array P the same size as X and Y containing the element-by-element, four-quadrant inverse tangent (arctangent) of the real parts of Y and X. Any imaginary parts are ignored. Elements of P lie in the closed interval [-pi,pi], where pi is MATLAB s floatingpoint representation of . The specific quadrant is determined by sign(Y) and sign(X). y /2 /2 0 x This contrasts with the result of atan(Y/X), which is limited to the interval [ 2, 2 ] , or the right side of this diagram. Examples Any complex number z = x + iy is converted to polar coordinates with r = abs(z) theta = atan2(imag(z),real(z)) To convert back to the original complex number: z = r *exp(i *theta) This is a common operation, so MATLAB provides a function, angle(z), that simply computes atan2(imag(z),real(z)). See Also atan, atanh, tan, tanh 2-67 atan2 2-68 audioplayer Purpose Syntax Description 2audioplayer Create an audio player object y = audioplayer(x,Fs) y = audioplayer(x,Fs,nbits) Note To use all of the audioplayer features, your system needs a properly installed and configured sound card with 8- and 16-bit I/O, two channels, and support for sampling rates of up to 48 kHz. y = audioplayer(x,Fs) returns a handle to an audio player object y using input audio signal x. The input signal x can be a vector or two-dimensional array containing single, double, int8, uint8, or int16 MATLAB data types. The input sample values for single and double data must be between -1 and 1. For int8, uint8 and int16 data, the ranges of sample values are -128 to 127, 0 to 255, and -32768 to 32767, respectively. Fs is the sampling rate in Hz to use for playback. Valid values for Fs depend on the specific audio hardware installed. Typical values supported by most sound cards are 8000, 11025, 22050, and 44100 Hz. y = audioplayer(x,Fs,nbits) returns a handle to an audio player object where nbits is the bit quantization to use for single or double data types. This is an optional parameter with a default value of 16. Valid values for nbits are 8 and 16. You do not need to specify nbits for int8 or uint8 or for int16 data because the quantization is set automatically to 8 or 16, respectively. After you create an audio player object, you can use the methods listed below on that object. y in each function is the name of the returned audio player. Each 2-69 audioplayer of these methods can use a dot notation. For example, play(y) and y.play are equivalent. Method play(y) play(y,start) play(y,[start stop]) play(y,range) Description Starts playback from the beginning and plays to the end, or from start sample to the end, or from start sample to stop sample. The values of start and stop can be specified in a two-element vector range. Same as play, but does not return control until playback completes. playblocking(y) playblocking(y,start) playblocking(y,[start stop]) playblocking(y,range) stop(y) pause(y) resume(y) Stops playback. Pauses playback. Restarts playback from where playback was paused. Indicates whether playback is in progress. If 0, playback is not in progress. If 1, playback is in progress. Displays all property information about audio player y. isplaying(y) display(y) disp(y) get(y) Audio player objects have the properties listed below. To set a user-settable property use this syntax set(y, 'property1', value,'property2',value,...) To view a read-only property get(y, property ) % Displays property setting. 2-70 audioplayer Property Type SampleRate BitsPerSample NumberOfChannels TotalSamples Description Type Name of the object s class Sampling frequency in Hz Number of bits per sample Number of channels Total length, in samples, of the audio data Status of the audio player ('on' or 'off') Current sample being played by the audio output device (If it is not playing, currentsample is the next sample to be played with play or resume.) User data of any type User-speci ed object label string read-only user-settable read-only read-only read-only read-only read-only Running CurrentSample UserData Tag user-settable user-settable Example Load a sample audio file, create an audio player object, and play the audio at a higher sampling rate. y contains the audio samples and Fs is the sampling rate. You can use any of the audioplayer functions listed above on the player. load handel; player=audioplayer(y,Fs); player.play([1 (player.SampleRate*3)]); To stop the playback, use this command: stop(player); % Equivalent to player.stop See Also audiorecorder, sound, wavplay, wavwrite, wavread, get, set, methods 2-71 audiorecorder Purpose Syntax Description 2audiorecorder Create an audio recorder object y = audiorecorder y = audiorecorder(Fs,nbits,channels) Note To use all of the audio recorder object features, your system must have a properly installed and con gured sound card with 8- and 16-bit I/O and support for sampling rates of up to 48 kHz. y = audiorecorder returns a handle to an 8-kHz, 8-bit, mono audio recorder. y = audiorecorder(Fs,nbits,channels) returns a handle to an audio recorder using the sampling rate, Fs, in Hz, the sample size of nbits, and the number of channels. Fs can be any sampling rate supported by the audio hardware. Common sampling rates are 8000, 11025, 22050, and 44000. The value of nbits must be 8 or 16. For mono or stereo, channels must be 1 or 2, respectively. After you create an audio recorder object, you can use the methods listed below on that object. y in each function is the name of the returned audio recorder. Each of these methods can use a dot notatation. For example, record(y) and y.record are equivalent. Method record(y) record(y,length) recordblocking(y) recordblocking(y,length) stop(y) pause(y) resume(y) Description Starts recording. Records for length number of seconds. Same as record but does not return control until recording completes. Stops recording. Pauses recording. Restarts recording from where recording was paused. 2-72 audiorecorder Method isrecording(y) Description Indicates whether recording is in progress. If 0, recording is not in progress. If 1, recording is in progress. Creates an audioplayer, plays the recorded audio data, and returns a handle to the created audioplayer. Creates an audioplayer and returns a handle to the created audioplayer. Returns the recorded audio data to the MATLAB workspace. type is a string containing the desired data type. Supported data types are double, single, int16, int8, or uint8. If type is omitted, it defaults to 'double'. For double and single, the array contains values between -1 and 1. For int8, values are between -128 to 127, for uint8, values are from 0 to 255, and for int16, values are from -32768 to 32767. If the recording is in mono, the returned array has one column. If it is in stereo, the array has two columns one for each channel. Displays all property information about audio recorder y. play(y) getplayer(y) getaudiodata(y) getaudiodata(y,'type') display(y) disp(y) get(y) Audio recorder objects have the properties listed below. To set a user-settable property use this syntax set(y, 'property1', value,'property2',value,...) To view a read-only property 2-73 audiorecorder get(y, property ) %displays property setting. Property Type SampleRate BitsPerSample Description Type Name of the object s class Sampling frequency in Hz Number of bits per recorded sample Number of channels of recorded audio Total length, in samples, of the recording Status of the audio recorder ('on' or 'off') Current sample being recorded by the audio output device (If it is not recording, currentsample is the next sample to be recorded with record or resume.). User data of any type Number of buffers used for recording (You should adjust this only if you have skips, dropouts, etc. in your recording.) Length in seconds of buffer (You should adjust this only if you have skips, dropouts, etc. in your recording.) User-speci ed object label string read-only read-only read-only read-only read-only read-only read-only NumberOfChannels TotalSamples Running CurrentSample UserData NumberOfBuffers user-settable user-settable BufferLength user-settable Tag user-settable 2-74 audiorecorder Examples Example 1 Using a microphone, record 3.5 seconds of 44.1-kHz, 16-bit, stereo data, and then return the data to the MATLAB workspace as a double array. recorder = audiorecorder(44100,16,2); recordblocking(recorder,3.5); audioarray=getaudiodata(recorder); Example 2 Using a microphone, record 8-bit, 22-kHz mono data, play it back, record again and return the data to the MATLAB workspace as a uint8 array. micrecorder = audiorecorder(22050,8,1); record(micrecorder); % Now, speak into microphone stop(micrecorder); speechplayer = play(micrecorder); % Now, listen to the recording stop(speechplayer); speechdata = getaudiodata(micrecorder, 'uint8'); Remarks The current implementation of AudioRecorder is not intended for long, high sample rate recording because it uses system memory for storage and does not use disk buffering. When large recordings are attempted, MATLAB performance may degrade. audioplayer, wavread, wavrecord, wavwrite, get, set, methods See Also 2-75 auread Purpose Graphical Interface Syntax 2auread Read NeXT/SUN (.au) sound file As an alternative to auread, use the Import Wizard. To activate the Import Wizard, select Import data from the File menu. y = auread('aufile') [y,Fs,bits] = auread('aufile') [...] = auread('aufile',N) [...] = auread('aufile',[N1,N2]) siz = auread('aufile','size') y = auread('aufile') loads a sound file specified by the string aufile, returning the sampled data in y. The .au extension is appended if no extension is given. Amplitude values are in the range [ 1,+1]. auread supports Description multi-channel data in the following formats: 8-bit mu-law 8-, 16-, and 32-bit linear floating-point [y,Fs,bits] = auread('aufile') returns the sample rate (Fs) in Hertz and the number of bits per sample (bits) used to encode the data in the file. [...] = auread('aufile',N) returns only the first N samples from each channel in the file. [...] = auread('aufile',[N1 N2]) returns only samples N1 through N2 from each channel in the file. siz = auread('aufile','size') returns the size of the audio data contained in the file in place of the actual audio data, returning the vector siz = [samples channels]. See Also auwrite, wavread 2-76 auwrite Purpose Syntax 2auwrite Write NeXT/SUN (.au) sound file auwrite(y,'aufile') auwrite(y,Fs,'aufile') auwrite(y,Fs,N,'aufile') auwrite(y,Fs,N,'method','aufile') auwrite(y,'aufile') writes a sound file specified by the string aufile. The Description data should be arranged with one channel per column. Amplitude values outside the range [ 1,+1] are clipped prior to writing. auwrite supports multi-channel data for 8-bit mu-law, and 8- and 16-bit linear formats. auwrite(y,Fs,'aufile') specifies the sample rate of the data in Hertz. auwrite(y,Fs,N,'aufile') selects the number of bits in the encoder. Allowable settings are N = 8 and N = 16. auwrite(y,Fs,N,'method','aufile') allows selection of the encoding method, which can be either mu or linear. Note that mu-law files must be 8-bit. By default, method = 'mu'. See Also auread, wavwrite 2-77 avifile Purpose Syntax 2avifile Create a new Audio Video Interleaved (AVI) file aviobj = avifile(filename) aviobj = avifile(filename,'PropertyName',value,'PropertyName',value,...) aviobj = avifile(filename) creates an AVI file, giving it the name specified in filename, using default values for all AVI file object properties. If filename does not include an extension, avifile appends .avi to the filename. AVI is a Description file format for storing audio and video data. avifile returns a handle to an AVI file object, aviobj. You use this object to refer to the AVI file in other functions. An AVI file object supports properties and methods that control aspects of the AVI file created. creates an AVI file with the specified parameter settings. This table lists available parameters. aviobj = avifile(filename,'Param',Value,'Param',Value,...) Parameter 'colormap' Value Default An m-by-3 matrix de ning the colormap to be used for indexed AVI movies, where m must be no greater than 256 (236 if using Indeo compression). You must set this parameter before calling addframe, unless you are using addframe with the MATLAB movie syntax. A text string specifying which compression codec to use. On Windows: 'Indeo3' 'Indeo5' 'Cinepak' 'MSVC' 'None' There is no default colormap. 'compression' On Unix: 'None' 'Indeo3', on Windows. 'None' on Unix. 2-78 avifile Parameter Value Default To use a custom compression codec, specify the four-character code that identifies the codec (typically included in the codec documentation). The addframe function reports an error if it can not find the specified custom compressor. 'fps' A scalar value specifying the speed of the AVI movie in frames per second (fps). For compressors that support temporal compression, this is the number of key frames per second. A descriptive name for the video stream. This parameter must be no greater than 64 characters long. A number between 0 and 100. This parameter has no effect on uncompressed movies. Higher quality numbers result in higher video quality and larger file sizes. Lower quality numbers result in lower video quality and smaller file sizes. 15 fps 'keyframe' 2 key frames per second. The default is the filename. 75 'name' 'quality' You can also use structure syntax to set AVI file object properties. For example, to set the quality property to 100 use the following syntax: aviobj = avifile(filename); aviobj.Quality = 100; Example This example shows how to use the avifile function to create the AVI file example.avi. fig=figure; set(fig,'DoubleBuffer','on'); 2-79 avifile set(gca,'xlim',[-80 80],'ylim',[-80 80],... 'NextPlot','replace','Visible','off') mov = avifile('example.avi') x = -pi:.1:pi; radius = 0:length(x); for k=1:length(x) h = patch(sin(x)*radius(k),cos(x)*radius(k),... [abs(cos(x(k))) 0 0]); set(h,'EraseMode','xor'); F = getframe(gca); mov = addframe(mov,F); end mov = close(mov); See Also addframe, close, movie2avi 2-80 aviinfo Purpose Syntax Description 2aviinfo Return information about an Audio Video Interleaved (AVI) file fileinfo = aviinfo(filename) fileinfo = aviinfo(filename) returns a structure whose fields contain information about the AVI file specified in the string, filename. If filename does not include an extension, then .avi is used. The file must be in the current working directory or in a directory on the MATLAB path. The set of fields in the fileinfo structure are shown below. Field Name AudioFormat Description A string containing the name of the format used to store the audio data, if audio data is present An integer indicating the sample rate in Hertz of the audio stream, if audio data is present A string specifying the name of the le A string containing the modi cation date of the le An integer indicating the size of the le in bytes An integer indicating the desired frames per second An integer indicating the height of the AVI movie in pixels A string indicating the type of image. Either 'truecolor' for a truecolor (RGB) image, or 'indexed' for an indexed image. An integer indicating the number of channels in the audio stream, if audio data is present An integer indicating the total number of frames in the movie AudioRate Filename FileModDate FileSize FramesPerSecond Height ImageType NumAudioChannels NumFrames 2-81 aviinfo Field Name NumColormapEntries Description An integer specifying the number of colormap entries A number between 0 and 100 indicating the video quality in the AVI file. Higher quality numbers indicate higher video quality; lower quality numbers indicate lower video quality. This value is not always set in AVI files and therefore may be inaccurate. A string containing the compressor used to compress the AVI le. If the compressor is not Microsoft Video 1, Run Length Encoding (RLE), Cinepak, or Intel Indeo, aviinfo returns a four-character code. An integer indicating the width of the AVI movie in pixels Quality VideoCompression Width See also avifile, aviread 2-82 aviread Purpose Syntax Description 2aviread Read an Audio Video Interleaved (AVI) file. mov = aviread(filename) mov = aviread(filename,index) mov = aviread(filename) reads the AVI movie filename into the MATLAB movie structure mov. If filename does not include an extension, then .avi is used. Use the movie function to view the movie, mov. On UNIX, filename must be an uncompressed AVI file. mov has two fields, cdata and colormap. The content of these fields varies depending on the type of image. Image Type Truecolor mov.cdata Field mov.colormap Field height-by-width-by-3 array height-by-width array Empty m-by-3 array Indexed mov = aviread(filename,index) reads only the frame(s) specified by index. index can be a single index or an array of indices into the video stream. In AVI files, the first frame has the index value 1, the second frame has the index value 2, and so on. See also aviinfo, avifile, movie 2-83 axes Purpose Syntax 2axes Create axes graphics object axes axes('PropertyName',PropertyValue,...) axes(h) h = axes(...) axes is the low-level function for creating axes graphics objects. axes creates an axes graphics object in the current figure using default Description property values. axes('PropertyName',PropertyValue,...) creates an axes object having the specified property values. MATLAB uses default values for any properties that you do not explicitly define as arguments. axes(h) makes existing axes h the current axes. It also makes h the first axes listed in the figure s Children property and sets the figure s CurrentAxes property to h. The current axes is the target for functions that draw image, line, patch, surface, and text graphics objects. h = axes(...) returns the handle of the created axes object. Remarks MATLAB automatically creates an axes, if one does not already exist, when you issue a command that draws image, light, line, patch, surface, or text graphics objects. The axes function accepts property name/property value pairs, structure arrays, and cell arrays as input arguments (see the set and get commands for examples of how to specify these data types). These properties, which control various aspects of the axes object, are described in the Axes Properties section. Use the set function to modify the properties of an existing axes or the get function to query the current values of axes properties. Use the gca command to obtain the handle of the current axes. The axis (not axes) function provides simplified access to commonly used properties that control the scaling and appearance of axes. 2-84 axes While the basic purpose of an axes object is to provide a coordinate system for plotted data, axes properties provide considerable control over the way MATLAB displays data. Stretch-to-Fill By default, MATLAB stretches the axes to fill the axes position rectangle (the rectangle defined by the last two elements in the Position property). This results in graphs that use the available space in the rectangle. However, some 3-D graphs (such as a sphere) appear distorted because of this stretching, and are better viewed with a specific three-dimensional aspect ratio. Stretch-to-fill is active when the DataAspectRatioMode, PlotBoxAspectRatioMode, and CameraViewAngleMode are all auto (the default). However, stretch-to-fill is turned off when the DataAspectRatio, PlotBoxAspectRatio, or CameraViewAngle is user-specified, or when one or more of the corresponding modes is set to manual (which happens automatically when you set the corresponding property value). This picture shows the same sphere displayed both with and without the stretch-to-fill. The dotted lines show the axes Position rectangle. 1 8 6 4 2 0 2 4 6 8 1 1 1 0.8 0.6 0.4 0.2 0 0.2 0.4 0.6 0.8 1 1 0.8 0.6 0.4 0.2 0 0.2 0.4 0.6 0.8 1 0.5 0 0.5 1 Stretch-to-fill active Stretch-to-fill disabled When stretch-to-fill is disabled, MATLAB sets the size of the axes to be as large as possible within the constraints imposed by the Position rectangle without introducing distortion. In the picture above, the height of the rectangle constrains the axes size. 2-85 axes Examples Zooming Zoom in using aspect ratio and limits: sphere set(gca,'DataAspectRatio',[1 1 1],... 'PlotBoxAspectRatio',[1 1 1],'ZLim',[ 0.6 0.6]) Zoom in and out using the CameraViewAngle: sphere set(gca,'CameraViewAngle',get(gca,'CameraViewAngle') 5) set(gca,'CameraViewAngle',get(gca,'CameraViewAngle')+5) Note that both examples disable MATLAB s stretch-to-fill behavior. Positioning the Axes The axes Position property enables you to define the location of the axes within the figure window. For example, h = axes('Position',position_rectangle) creates an axes object at the specified position within the current figure and returns a handle to it. Specify the location and size of the axes with a rectangle defined by a four-element vector, position_rectangle = [left, bottom, width, height]; The left and bottom elements of this vector define the distance from the lower-left corner of the figure to the lower-left corner of the rectangle. The width and height elements define the dimensions of the rectangle. You specify these values in units determined by the Units property. By default, MATLAB uses normalized units where (0,0) is the lower-left corner and (1.0,1.0) is the upper-right corner of the figure window. You can define multiple axes in a single figure window: axes('position',[.1 .1 mesh(peaks(20)); axes('position',[.1 .7 pcolor([1:10;1:10]); .8 .8 .6]) .2]) 2-86 axes In this example, the first plot occupies the bottom two-thirds of the figure, and the second occupies the top third. 2 1.5 1 1 10 5 0 5 10 20 15 10 5 0 0 5 15 10 20 2 3 4 5 6 7 8 9 10 See Also axis, cla, clf, figure, gca, grid, subplot, title, xlabel, ylabel, zlabel, view 2-87 axes Object Hierarchy Root Figure Axes Uicontrol Uimenu Uicontextmenu Image Light Line Patch Rectangle Surface Text Setting Default Properties You can set default axes properties on the figure and root levels: set(0,'DefaultAxesPropertyName',PropertyValue,...) set(gcf,'DefaultAxesPropertyName',PropertyValue,...) where PropertyName is the name of the axes property and PropertyValue is the value you are specifying. Use set and get to access axes properties. Property List The following table lists all axes properties and provides a brief description of each. The property name links take you an expanded description of the properties. Property Description Property Value Property Name Controlling Style and Appearance Box Toggle axes plot box on and off This property has no effect; axes are always clipped to the gure window Line style used to draw axes grid lines Values: on, off Default: off Clipping GridLineStyle Values: , , :, -., none Default: : (dotted line) 2-88 axes Property Name Layer Property Description Property Value Draw axes above or below graphs Sequence of line styles used for multiline plots Width of axis lines, in points (1/72" per point) Highlight axes when selected (Selected property set to on) Direction of axis tick marks Use MATLAB or user-speci ed tick mark direction Length of tick marks normalized to axis line length, speci ed as two-element vector Make axes visible or invisible Toggle grid lines on and off in respective axis Values: bottom, top Default: bottom Values: LineSpec Default: (solid line for) Values: number of points Default: 0.5 points Values: on, off Default: on Values: in, out Default: in (2-D), out (3-D) Values: auto, manual Default: auto Values: [2-D 3-D] Default: [0.01 0.025} Values: on, off Default: on Values: on, off Default: off LineStyleOrder LineWidth SelectionHighlight TickDir TickDirMode TickLength Visible XGrid, YGrid, ZGrid General Information About the Axes Children Handles of the images, lights, lines, patches, surfaces, and text objects displayed in the axes Location of last mouse button click de ned in the axes data units Specify whether axes can become the current object (see gure CurrentObject property) Values: vector of handles CurrentPoint Values: a 2-by-3 matrix Values: on, off Default: on HitTest 2-89 axes Property Name Parent Property Description Property Value Handle of the gure window containing the axes Location and size of axes within the gure Values: scalar gure handle Values: [left bottom width height] Default: [0.1300 0.1100 0.7750 0.8150] in normalized Units Values: on, off Default: on Values: any string Default: '' (empty string) Value: the string 'axes' Values: inches, centimeters, characters, normalized, points, pixels Default: normalized Values: any matrix Default: [] (empty matrix) Position Selected Indicate whether axes is in a selected state User-speci ed label The type of graphics object (read only) Units used to interpret the Position property Tag Type Units UserData User-speci ed data Selecting Fonts and Labels FontAngle Select italic or normal font Values: normal, italic, oblique Default: normal Values: a font supported by your system or the string FixedWidth FontName Font family name (e.g., Helvetica, Courier) Default: Typically Helvetica FontSize Size of the font used for title and labels Values: an integer in FontUnits Default: 10 2-90 axes Property Name FontUnits Property Description Property Value Units used to interpret the FontSize property Values: points, normalized, inches, centimeters, pixels Default: points Values: normal, bold, light, demi Default: normal Values: any valid text object handle Values: any valid text object handle Values: matrix of strings Defaults: numeric values selected automatically by MATLAB Values: auto, manual Default: auto FontWeight Select bold or normal font Title Handle of the title text object Handles of the respective axis label text objects Specify tick mark labels for the respective axis XLabel, YLabel, ZLabel XTickLabel, YTickLabel, ZTickLabel XTickLabelMode, YTickLabelMode, ZTickLabelMode Controlling Axis Scaling XAxisLocation Use MATLAB or user-speci ed tick mark labels Specify the location of the x-axis Specify the location of the y-axis Specify the direction of increasing values for the respective axes Specify the limits to the respective axes Values: top, bottom Default: bottom Values: right left Default: left Values: normal, reverse Default: normal Values: [min max] Default: min and max determined automatically by MATLAB YAxisLocation XDir, YDir, ZDir XLim, YLim, ZLim 2-91 axes Property Name XLimMode, YLimMode, ZLimMode XMinorGrid,YMinorGrid, ZMinorGrid Property Description Property Value Use MATLAB or user-speci ed values for the respective axis limits Determines whether MATLAB displays gridlines connecting minor tick marks in the respective axis. Determines whether MATLAB displays minor tick marks in the respective axis. Select linear or logarithmic scaling of the respective axis Values: auto, manual Default: auto Values: on, off Default: off Values: on, off Default: off Values: linear, log Default: linear (changed by plotting commands that create nonlinear plots) Values: a vector of data values locating tick marks Default: MATLAB automatically determines tick mark placement Values: auto, manual Default: auto XMinorTick,YMinorTick, ZMinorTick XScale, YScale, ZScale XTick, YTick, ZTick Specify the location of the axis ticks marks XTickMode, YTickMode, ZTickMode Use MATLAB or user-speci ed values for the respective tick mark locations Controlling the View CameraPosition Specify the position of point from which you view the scene Values: [x,y,z] axes coordinates Default: automatically determined by MATLAB Values: auto, manual Default: auto CameraPositionMode Use MATLAB or user-speci ed camera position 2-92 axes Property Name CameraTarget Property Description Property Value Center of view pointed to by camera Values: [x,y,z] axes coordinates Default: automatically determined by MATLAB Values: auto, manual Default: auto Values: [x,y,z] axes coordinates Default: automatically determined by MATLAB Values: auto, manual Default: auto Values: angle in degrees between 0 and 180 Default: automatically determined by MATLAB Values: auto, manual Default: auto Values: orthographic, perspective Default: orthographic CameraTargetMode Use MATLAB or user-speci ed camera target Direction that is oriented up CameraUpVector CameraUpVectorMode Use MATLAB or user-speci ed camera up vector Camera eld of view CameraViewAngle CameraViewAngleMode Use MATLAB or user-speci ed camera view angle Select type of projection Projection Controlling the Axes Aspect Ratio DataAspectRatio Relative scaling of data units Values: three relative values [dx dy dz] Default: automatically determined by MATLAB Values: auto, manual Default: auto DataAspectRatioMode Use MATLAB or user-speci ed data aspect ratio 2-93 axes Property Name PlotBoxAspectRatio Property Description Property Value Relative scaling of axes plot box Values: three relative values [dx dy dz] Default: automatically determined by MATLAB Values: auto, manual Default: auto PlotBoxAspectRatioMode Use MATLAB or user-speci ed plot box aspect ratio Controlling Callback Routine Execution BusyAction Specify how to handle events that interrupt execution callback routines De ne a callback routine that executes when a button is pressed over the axes De ne a callback routine that executes when an axes is created De ne a callback routine that executes when an axes is created Control whether an executing callback routine can be interrupted Associate a context menu with the axes Values: cancel, queue Default: queue Values: string Default: an empty string Values: string Default: an empty string Values: string Default: an empty string Values: on, off Default: on Values: handle of a Uicontextmenu ButtonDownFcn CreateFcn DeleteFcn Interruptible UIContextMenu Specifying the Rendering Mode DrawMode Specify the rendering method to use with the Painters renderer Values: normal, fast Default: normal Targeting Axes for Graphics Display HandleVisibility Control access to a speci c axes handle Values: on, callback, off Default: on 2-94 axes Property Name NextPlot Property Description Property Value Determine the eligibility of the axes for displaying graphics Values: add, replace, replacechildren Default: replace Properties that Specify Transparency ALim ALimMode Alpha axis limits Alpha axis limits mode Values: [amin amax] Values: auto | manual Default: auto Properties that Specify Color AmbientLightColor Color of the background light in a scene Control how data is mapped to colormap Use MATLAB or user-speci ed values for CLim Color of the axes background Line colors used for multiline plots Values: ColorSpec Default: [1 1 1] Values: [cmin cmax] Default: automatically determined by MATLAB Values: auto, manual Default: auto Values: none, ColorSpec Default: none Values: m-by-3 matrix of RGB values Default: depends on color scheme used Values: ColorSpec Default: depends on current color scheme CLim CLimMode Color ColorOrder XColor, YColor, ZColor Colors of the axis lines and tick marks 2-95 Axes Properties Modifying Properties 2Axes Properties You can set and query graphics object properties in two ways: The Property Editor is an interactive tool that enables you to see and change object property values. The set and get commands enable you to set and query the values of properties To change the default value of properties see Setting Default Property Values. Axes Property Descriptions This section lists property names along with the types of values each accepts. Curly braces { } enclose default values. ALim [amin, amax] Alpha axis limits. A two-element vector that determines how MATLAB maps the AlphaData values of surface, patch and image objects to the figure's alphamap. amin is the value of the data mapped to the first alpha value in the alphamap, and amax is the value of the data mapped to the last alpha value in the alphamap. Data values in between are linearly interpolated across the alphamap, while data values outside are clamped to either the first or last alphamap value, whichever is closest. When ALimMode is auto (the default), MATLAB assigns amin the minimum data value and amax the maximum data value in the graphics object's AlphaData. This maps AlphaData elements with minimum data values to the first alphamap entry and those with maximum data values to the last alphamap entry. Data values in between are mapped linearly to the values If the axes contains multiple graphics objects, MATLAB sets ALim to span the range of all objects' AlphaData (or FaceVertexAlphaData for patch objects). ALimMode {auto} | manual Alpha axis limits mode. In auto mode, MATLAB sets the ALim property to span the AlphaData limits of the graphics objects displayed in the axes. If ALimMode is manual, MATLAB does not change the value of ALim when the AlphaData limits of axes children change. Setting the ALim property sets ALimMode to manual. AmbientLightColor ColorSpec The background light in a scene. Ambient light is a directionless light that shines uniformly on all objects in the axes. However, if there are no visible light 2-96 Axes Properties objects in the axes, MATLAB does not use AmbientLightColor. If there are light objects in the axes, the AmbientLightColor is added to the other light sources. AspectRatio (Obsolete) This property produces a warning message when queried or changed. It has been superseded by the DataAspectRatio[Mode] and PlotBoxAspectRatio[Mode] properties. Box on | {off} Axes box mode. This property specifies whether to enclose the axes extent in a box for 2-D views or a cube for 3-D views. The default is to not display the box. BusyAction cancel | {queue} Callback routine interruption. The BusyAction property enables you to control how MATLAB handles events that potentially interrupt executing callback routines. If there is a callback routine executing, subsequently invoked callback routines always attempt to interrupt it. If the Interruptible property of the object whose callback is executing is set to on (the default), then interruption occurs at the next point where the event queue is processed. If the Interruptible property is off, the BusyAction property (of the object owning the executing callback) determines how MATLAB handles the event. The choices are: cancel discard the event that attempted to execute a second callback routine. queue queue the event that attempted to execute a second callback routine until the current callback finishes. ButtonDownFcn string Button press callback routine. A callback routine that executes whenever you press a mouse button while the pointer is within the axes, but not over another graphics object displayed in the axes. For 3-D views, the active area is defined by a rectangle that encloses the axes. Define this routine as a string that is a valid MATLAB expression or the name of an M-file. The expression executes in the MATLAB workspace. 2-97 Axes Properties CameraPosition [x, y, z] axes coordinates The location of the camera. This property defines the position from which the camera views the scene. Specify the point in axes coordinates. If you fix CameraViewAngle, you can zoom in and out on the scene by changing the CameraPosition, moving the camera closer to the CameraTarget to zoom in and farther away from the CameraTarget to zoom out. As you change the CameraPosition, the amount of perspective also changes, if Projection is perspective. You can also zoom by changing the CameraViewAngle; however, this does not change the amount of perspective in the scene. CameraPositionMode {auto} | manual Auto or manual CameraPosition. When set to auto, MATLAB automatically calculates the CameraPosition such that the camera lies a fixed distance from the CameraTarget along the azimuth and elevation specified by view. Setting a value for CameraPosition sets this property to manual. CameraTarget [x, y, z] axes coordinates Camera aiming point. This property specifies the location in the axes that the camera points to. The CameraTarget and the CameraPosition define the vector (the view axis) along which the camera looks. CameraTargetMode {auto} | manual Auto or manual CameraTarget placement. When this property is auto, MATLAB automatically positions the CameraTarget at the centroid of the axes plotbox. Specifying a value for CameraTarget sets this property to manual. CameraUpVector [x, y, z] axes coordinates Camera rotation. This property specifies the rotation of the camera around the viewing axis defined by the CameraTarget and the CameraPosition properties. Specify CameraUpVector as a three-element array containing the x, y, and z components of the vector. For example, [0 1 0] specifies the positive y-axis as the up direction. The default CameraUpVector is [0 0 1], which defines the positive z-axis as the up direction. CameraUpVectorMode {auto} | manual Default or user-specified up vector. When CameraUpVectorMode is auto, MATLAB uses a value of [0 0 1] (positive z-direction is up) for 3-D views and 2-98 Axes Properties [0 1 0] (positive y-direction is up) for 2-D views. Setting a value for CameraUpVector sets this property to manual. CameraViewAngle scalar greater than 0 and less than or equal to 180 (angle in degrees) The field of view. This property determines the camera field of view. Changing this value affects the size of graphics objects displayed in the axes, but does not affect the degree of perspective distortion. The greater the angle, the larger the field of view, and the smaller objects appear in the scene. CameraViewAngleMode{auto} | manual Auto or manual CameraViewAngle. When in auto mode, MATLAB sets CameraViewAngle to the minimum angle that captures the entire scene (up to 180 ). The following table summarizes MATLAB s automatic camera behavior. CameraView Angle auto Camera Target auto Camera Position auto Behavior CameraTarget is set to plot box centroid, CameraViewAngle is set to capture entire scene, CameraPosition is set along the view axis. CameraTarget is set to plot box centroid, CameraViewAngle is set to capture entire scene. CameraViewAngle is set to capture entire scene, CameraPosition is set along the view axis. CameraViewAngle is set to capture entire scene. CameraTarget is set to plot box centroid, CameraPosition is set along the view axis. CameraTarget is set to plot box centroid CameraPosition is set along the view axis. auto auto manual auto manual auto auto manual manual auto manual auto manual manual manual auto manual manual manual auto manual All Camera properties are user-speci ed. 2-99 Axes Properties Children vector of graphics object handles Children of the axes. A vector containing the handles of all graphics objects rendered within the axes (whether visible or not). The graphics objects that can be children of axes are images, lights, lines, patches, surfaces, and text. You can change the order of the handles and thereby change the stacking of the objects on the display. The text objects used to label the x-, y-, and z-axes are also children of axes, but their HandleVisibility properties are set to callback. This means their handles do not show up in the axes Children property unless you set the Root ShowHiddenHandles property to on. CLim [cmin, cmax] Color axis limits. A two-element vector that determines how MATLAB maps the CData values of surface and patch objects to the figure s colormap. cmin is the value of the data mapped to the first color in the colormap, and cmax is the value of the data mapped to the last color in the colormap. Data values in between are linearly interpolated across the colormap, while data values outside are clamped to either the first or last colormap color, whichever is closest. When CLimMode is auto (the default), MATLAB assigns cmin the minimum data value and cmax the maximum data value in the graphics object s CData. This maps CData elements with minimum data value to the first colormap entry and with maximum data value to the last colormap entry. If the axes contains multiple graphics objects, MATLAB sets CLim to span the range of all objects CData. CLimMode {auto} | manual Color axis limits mode. In auto mode, MATLAB sets the CLim property to span the CData limits of the graphics objects displayed in the axes. If CLimMode is manual, MATLAB does not change the value of CLim when the CData limits of axes children change. Setting the CLim property sets this property to manual. Clipping {on} | off This property has no effect on axes. 2-100 Axes Properties Color {none} | ColorSpec Color of the axes back planes. Setting this property to none means the axes is transparent and the figure color shows through. A ColorSpec is a three-element RGB vector or one of MATLAB s predefined names. Note that while the default value is none, the matlabrc.m file may set the axes color to a specific color. ColorOrder m-by-3 matrix of RGB values Colors to use for multiline plots. ColorOrder is an m-by-3 matrix of RGB values that define the colors used by the plot and plot3 functions to color each line plotted. If you do not specify a line color with plot and plot3, these functions cycle through the ColorOrder to obtain the color for each line plotted. To obtain the current ColorOrder, which may be set during startup, get the property value: get(gca,'ColorOrder') Note that if the axes NextPlot property is set to replace (the default), high-level functions like plot reset the ColorOrder property before determining the colors to use. If you want MATLAB to use a ColorOrder that is different from the default, set NextPlot to replacechildren. You can also specify your own default ColorOrder. CreateFcn string Callback routine executed during object creation. This property defines a callback routine that executes when MATLAB creates an axes object. You must define this property as a default value for axes. For example, the statement, set(0,'DefaultAxesCreateFcn','set(gca,''Color'',''b'')') defines a default value on the Root level that sets the current axes background color to blue whenever you (or MATLAB) create an axes. MATLAB executes this routine after setting all properties for the axes. Setting this property on an existing axes object has no effect. The handle of the object whose CreateFcn is being executed is accessible only through the Root CallbackObject property, which can be queried using gcbo. CurrentPoint 2-by-3 matrix Location of last button click, in axes data units. A 2-by-3 matrix containing the coordinates of two points defined by the location of the pointer. These two 2-101 Axes Properties points lie on the line that is perpendicular to the plane of the screen and passes through the pointer. The 3-D coordinates are the points, in the axes coordinate system, where this line intersects the front and back surfaces of the axes volume (which is defined by the axes x, y, and z limits). The returned matrix is of the form: x back y back z back x front y front z front MATLAB updates the CurrentPoint property whenever a button-click event occurs. The pointer does not have to be within the axes, or even the figure window; MATLAB returns the coordinates with respect to the requested axes regardless of the pointer location. DataAspectRatio [dx dy dz] Relative scaling of data units. A three-element vector controlling the relative scaling of data units in the x, y, and z directions. For example, setting this property t o [1 2 1] causes the length of one unit of data in the x direction to be the same length as two units of data in the y direction and one unit of data in the z direction. Note that the DataAspectRatio property interacts with the PlotBoxAspectRatio, XLimMode, YLimMode, and ZLimMode properties to control how MATLAB scales the x-, y-, and z-axis. Setting the DataAspectRatio will disable the stretch-to-fill behavior, if DataAspectRatioMode, PlotBoxAspectRatioMode, and CameraViewAngleMode are all auto. The 2-102 Axes Properties following table describes the interaction between properties when stretch-to-fill behavior is disabled. X-, Y-, Z-Limits auto DataAspect Ratio auto PlotBox AspectRatio auto Behavior Limits chosen to span data range in all dimensions. Limits chosen to span data range in all dimensions. DataAspectRatio is modi ed to achieve the requested PlotBoxAspectRatio within the limits selected by MATLAB. Limits chosen to span data range in all dimensions. PlotBoxAspectRatio is modi ed to achieve the requested DataAspectRatio within the limits selected by MATLAB. Limits chosen to completely t and center the plot within the requested PlotBoxAspectRatio given the requested DataAspectRatio (this may produce empty space around 2 of the 3 dimensions). Limits are honored. The DataAspectRatio and PlotBoxAspectRatio are modi ed as necessary. Limits and PlotBoxAspectRatio are honored. The DataAspectRatio is modi ed as necessary. Limits and DataAspectRatio are honored. The PlotBoxAspectRatio is modi ed as necessary. The 2 automatic limits are selected to honor the speci ed aspect ratios and limit. See Examples Limits and DataAspectRatio are honored; the PlotBoxAspectRatio is ignored. auto auto manual auto manual auto auto manual manual manual auto auto manual auto manual manual manual auto 1 manual 2 auto 2 or 3 manual manual manual manual manual 2-103 Axes Properties DataAspectRatioMode{auto} | manual User or MATLAB controlled data scaling. This property controls whether the values of the DataAspectRatio property are user defined or selected automatically by MATLAB. Setting values for the DataAspectRatio property automatically sets this property to manual. Changing DataAspectRatioMode to manual disables the stretch-to-fill behavior, if DataAspectRatioMode, PlotBoxAspectRatioMode, and CameraViewAngleMode are all auto. DeleteFcn string Delete axes callback routine. A callback routine that executes when the axes object is deleted (e.g., when you issue a delete or a close command). MATLAB executes the routine before destroying the object s properties so the callback routine can query these values. The handle of the object whose DeleteFcn is being executed is accessible only through the Root CallbackObject property, which can be queried using gcbo. DrawMode {normal} | fast Rendering method. This property controls the method MATLAB uses to render graphics objects displayed in the axes, when the figure Renderer property is painters. normal mode draws objects in back to front ordering based on the current view in order to handle hidden surface elimination and object intersections. fast mode draws objects in the order in which you specify the drawing commands, without considering the relationships of the objects in three dimensions. This results in faster rendering because it requires no sorting of objects according to location in the view, but may produce undesirable results because it bypasses the hidden surface elimination and object intersection handling provided by normal DrawMode. When the figure Renderer is zbuffer, DrawMode is ignored, and hidden surface elimination and object intersection handling are always provided. FontAngle {normal} | italic | oblique Select italic or normal font. This property selects the character slant for axes text. normal specifies a nonitalic font. italic and oblique specify italic font. 2-104 Axes Properties FontName A name such as Courier or the string FixedWidth Font family name. The font family name specifying the font to use for axes labels. To display and print properly, FontName must be a font that your system supports. Note that the x-, y-, and z-axis labels do not display in a new font until you manually reset them (by setting the XLabel, YLabel, and ZLabel properties or by using the xlabel, ylabel, or zlabel command). Tick mark labels change immediately. Specifying a Fixed-Width Font If you want an axes to use a fixed-width font that looks good in any locale, you should set FontName to the string FixedWidth: set(axes_handle,'FontName','FixedWidth') This eliminates the need to hardcode the name of a fixed-width font, which may not display text properly on systems that do not use ASCII character encoding (such as in Japan where multibyte character sets are used). A properly written MATLAB application that needs to use a fixed-width font should set FontName to FixedWidth (note that this string is case sensitive) and rely on FixedWidthFontName to be set correctly in the end-user s environment. End users can adapt a MATLAB application to different locales or personal environments by setting the root FixedWidthFontName property to the appropriate value for that locale from startup.m. Note that setting the root FixedWidthFontName property causes an immediate update of the display to use the new font. FontSize Font size specified in FontUnits Font size. An integer specifying the font size to use for axes labels and titles, in units determined by the FontUnits property. The default point size is 12. The x-, y-, and z-axis text labels do not display in a new font size until you manually reset them (by setting the XLabel, YLabel, or ZLabel properties or by using the xlabel, ylabel, or zlabel command). Tick mark labels change immediately. FontUnits {points} | normalized | inches | centimeters | pixels Units used to interpret the FontSize property. When set to normalized, MATLAB interprets the value of FontSize as a fraction of the height of the axes. For example, a normalized FontSize of 0.1 sets the text characters to a 2-105 Axes Properties font whose height is one tenth of the axes height. The default units (points), are equal to 1/72 of an inch. FontWeight {normal} | bold | light | demi Select bold or normal font. The character weight for axes text. The x-, y-, and z-axis text labels do not display in bold until you manually reset them (by setting the XLabel, YLabel, and ZLabel properties or by using the xlabel, ylabel, or zlabel commands). Tick mark labels change immediately. GridLineStyle | | {:} | . | none Line style used to draw grid lines. The line style is a string consisting of a character, in quotes, specifying solid lines ( ), dashed lines ( ), dotted lines(:), or dash-dot lines ( .). The default grid line style is dotted. To turn on grid lines, use the grid command. HandleVisibility {on} | callback | off Control access to object s handle by command-line users and GUIs. This property determines when an object s handle is visible in its parent s list of children. HandleVisibility is useful for preventing command-line users from accidentally drawing into or deleting a figure that contains only user interface devices (such as a dialog box). Handles are always visible when HandleVisibility is on. Setting HandleVisibility to callback causes handles to be visible from within callback routines or functions invoked by callback routines, but not from within functions invoked from the command line. This provides a means to protect GUIs from command-line users, while allowing callback routines to have complete access to object handles. Setting HandleVisibility to off makes handles invisible at all times. This may be necessary when a callback routine invokes a function that might potentially damage the GUI (such as evaluating a user-typed string) and so temporarily hides its own handles during the execution of that function. When a handle is not visible in its parent s list of children, it cannot be returned by functions that obtain handles by searching the object hierarchy or querying handle properties. This includes get, findobj, gca, gcf, gco, newplot, cla, clf, and close. 2-106 Axes Properties When a handle s visibility is restricted using callback or off, the object s handle does not appear in its parent s Children property, figures do not appear in the Root s Currentfigure property, objects do not appear in the Root s CallbackObject property or in the figure s CurrentObject property, and axes do not appear in their parent s Currentaxes property. You can set the Root ShowHiddenHandles property to on to make all handles visible, regardless of their HandleVisibility settings (this does not affect the values of the HandleVisibility properties). Handles that are hidden are still valid. If you know an object s handle, you can set and get its properties, and pass it to any function that operates on handles. HitTest {on} | off Selectable by mouse click. HitTest determines if the axes can become the current object (as returned by the gco command and the figure CurrentObject property) as a result of a mouse click on the axes. If HitTest is off, clicking on the axes selects the object below it (which is usually the figure containing it). Interruptible {on} | off Callback routine interruption mode. The Interruptible property controls whether an axes callback routine can be interrupted by subsequently invoked callback routines. Only callback routines defined for the ButtonDownFcn are affected by the Interruptible property. MATLAB checks for events that can interrupt a callback routine only when it encounters a drawnow, figure, getframe, or pause command in the routine. See the BusyAction property for related information. Setting Interruptible to on allows any graphics object s callback routine to interrupt callback routines originating from an axes property. Note that MATLAB does not save the state of variables or the display (e.g., the handle returned by the gca or gcf command) when an interruption occurs. Layer {bottom} | top Draw axis lines below or above graphics objects. This property determines if axis lines and tick marks draw on top or below axes children objects for any 2-D view (i.e., when you are looking along the x-, y-, or z-axis). This is useful for placing grid lines and tick marks on top of images. 2-107 Axes Properties LineStyleOrder LineSpec Order of line styles and markers used in a plot. This property specifies which line styles and markers to use and in what order when creating multiple-line plots. For example, set(gca,'LineStyleOrder', ' *|:|o') sets LineStyleOrder to solid line with asterisk marker, dotted line, and hollow circle marker. The default is ( ), which specifies a solid line for all data plotted. Alternatively, you can create a cell array of character strings to define the line styles: set(gca,'LineStyleOrder',{' *',':','o'}) MATLAB supports four line styles, which you can specify any number of times in any order. MATLAB cycles through the line styles only after using all colors defined by the ColorOrder property. For example, the first eight lines plotted use the different colors defined by ColorOrder with the first line style. MATLAB then cycles through the colors again, using the second line style specified, and so on. You can also specify line style and color directly with the plot and plot3 functions or by altering the properties of the line objects. Note that, if the axes NextPlot property is set to replace (the default), high-level functions like plot reset the LineStyleOrder property before determining the line style to use. If you want MATLAB to use a LineStyleOrder that is different from the default, set NextPlot to replacechildren. You can also specify your own default LineStyleOrder. LineWidth linewidth in points Width of axis lines. This property specifies the width, in points, of the x-, y-, and z-axis lines. The default line width is 0.5 points (1 point = 1/72 inch). NextPlot add | {replace} | replacechildren Where to draw the next plot. This property determines how high-level plotting functions draw into an existing axes. add use the existing axes to draw graphics objects. replace reset all axes properties, except Position, to their defaults and delete all axes children before displaying graphics (equivalent to cla reset). 2-108 Axes Properties replacechildren remove all child objects, but do not reset axes properties (equivalent to cla). The newplot function simplifies the use of the NextPlot property and is used by M-file functions that draw graphs using only low-level object creation routines. See the M-file pcolor.m for an example. Note that figure graphics objects also have a NextPlot property. Parent figure handle Axes parent. The handle of the axes parent object. The parent of an axes object is the figure in which it is displayed. The utility function gcf returns the handle of the current axes Parent. You can reparent axes to other figure objects. PlotBoxAspectRatio [px py pz] Relative scaling of axes plotbox. A three-element vector controlling the relative scaling of the plot box in the x-, y-, and z-directions. The plot box is a box enclosing the axes data region as defined by the x-, y-, and z-axis limits. Note that the PlotBoxAspectRatio property interacts with the DataAspectRatio, XLimMode, YLimMode, and ZLimMode properties to control the way graphics objects are displayed in the axes. Setting the PlotBoxAspectRatio disables stretch-to-fill behavior, if DataAspectRatioMode, PlotBoxAspectRatioMode, and CameraViewAngleMode are all auto. PlotBoxAspectRatioMode{auto} | manual User or MATLAB controlled axis scaling. This property controls whether the values of the PlotBoxAspectRatio property are user defined or selected automatically by MATLAB. Setting values for the PlotBoxAspectRatio property automatically sets this property to manual. Changing the PlotBoxAspectRatioMode to manual disables stretch-to-fill behavior, if DataAspectRatioMode, PlotBoxAspectRatioMode, and CameraViewAngleMode are all auto. Position four-element vector Position of axes. A four-element vector specifying a rectangle that locates the axes within the figure window. The vector is of the form: [left bottom width height] 2-109 Axes Properties where left and bottom define the distance from the lower-left corner of the figure window to the lower-left corner of the rectangle. width and height are the dimensions of the rectangle. All measurements are in units specified by the Units property. When axes stretch-to-fill behavior is enabled (when DataAspectRatioMode, PlotBoxAspectRatioMode, CameraViewAngleMode are all auto), the axes are stretched to fill the Position rectangle. When stretch-to-fill is disabled, the axes are made as large as possible, while obeying all other properties, without extending outside the Position rectangle Projection {orthographic} | perspective Type of projection. This property selects between two projection types: orthographic This projection maintains the correct relative dimensions of graphics objects with regard to the distance a given point is from the viewer. Parallel lines in the data are drawn parallel on the screen. perspective This projection incorporates foreshortening, which allows you to perceive depth in 2-D representations of 3-D objects. Perspective projection does not preserve the relative dimensions of objects; a distant line segment displays smaller than a nearer line segment of the same length. Parallel lines in the data may not appear parallel on screen. Selected on | off Is object selected. When you set this property to on, MATLAB displays selection handles at the corners and midpoints if the SelectionHighlight property is also on (the default). You can, for example, define the ButtonDownFcn callback routine to set this property to on, thereby indicating that the axes has been selected. SelectionHighlight {on} | off Objects highlight when selected. When the Selected property is on, MATLAB indicates the selected state by drawing four edge handles and four corner handles. When SelectionHighlight is off, MATLAB does not draw the handles. Tag string (GUIDE sets this property) User-specified object label. The Tag property provides a means to identify graphics objects with a user-specified label. This is particularly useful when constructing interactive graphics programs that would otherwise need to 2-110 Axes Properties define object handles as global variables or pass them as arguments between callback routines. For example, suppose you want to direct all graphics output from an M-file to a particular axes, regardless of user actions that may have changed the current axes. To do this, identify the axes with a Tag: axes('Tag','Special Axes') Then make that axes the current axes before drawing by searching for the Tag with findobj: axes(findobj('Tag','Special Axes')) TickDir in | out Direction of tick marks. For 2-D views, the default is to direct tick marks inward from the axis lines; 3-D views direct tick marks outward from the axis line. TickDirMode {auto} | manual Automatic tick direction control. In auto mode, MATLAB directs tick marks inward for 2-D views and outward for 3-D views. When you specify a setting for TickDir, MATLAB sets TickDirMode to manual. In manual mode, MATLAB does not change the specified tick direction. TickLength [2DLength 3DLength] Length of tick marks. A two-element vector specifying the length of axes tick marks. The first element is the length of tick marks used for 2-D views and the second element is the length of tick marks used for 3-D views. Specify tick mark lengths in units normalized relative to the longest of the visible X-, Y-, or Z-axis annotation lines. Title handle of text object Axes title. The handle of the text object that is used for the axes title. You can use this handle to change the properties of the title text or you can set Title to the handle of an existing text object. For example, the following statement changes the color of the current title to red: set(get(gca,'Title'),'Color','r') To create a new title, set this property to the handle of the text object you want to use: 2-111 Axes Properties set(gca,'Title',text('String','New Title','Color','r')) However, it is generally simpler to use the title command to create or replace an axes title: title('New Title','Color','r') Type string (read only) Type of graphics object. This property contains a string that identifies the class of graphics object. For axes objects, Type is always set to 'axes'. UIContextMenu handle of a uicontextmenu object Associate a context menu with the axes. Assign this property the handle of a Uicontextmenu object created in the axes parent figure. Use the uicontextmenu function to create the context menu. MATLAB displays the context menu whenever you right-click over the axes. Units inches | centimeters | {normalized} | points | pixels | characters Position units. The units used to interpret the Position property. All units are measured from the lower-left corner of the figure window. normalized units map the lower-left corner of the figure window to (0,0) and the upper-right corner to (1.0, 1.0). inches, centimeters, and points are absolute units (one point equals 1/72 of an inch). Character units are defined by characters from the default system font; the width of one character is the width of the letter x, the height of one character is the distance between the baselines of two lines of text. UserData matrix User specified data. This property can be any data you want to associate with the axes object. The axes does not use this property, but you can access it using the set and get functions. View Obsolete The functionality provided by the View property is now controlled by the axes camera properties CameraPosition, CameraTarget, CameraUpVector, and CameraViewAngle. See the view command. 2-112 Axes Properties Visible {on} | off Visibility of axes. By default, axes are visible. Setting this property to off prevents axis lines, tick marks, and labels from being displayed. The visible property does not affect children of axes. XAxisLocation top | {bottom} Location of x-axis tick marks and labels. This property controls where MATLAB displays the x-axis tick marks and labels. Setting this property to top moves the x-axis to the top of the plot from its default position at the bottom. YAxisLocation right | {left} Location of y-axis tick marks and labels. This property controls where MATLAB displays the y-axis tick marks and labels. Setting this property to right moves the y-axis to the right side of the plot from its default position on the left side. See the plotyy function for a simple way to use two y-axes. Properties That Control the X-, Y-, or Z-Axis XColor, YColor, ZColorColorSpec Color of axis lines. A three-element vector specifying an RGB triple, or a predefined MATLAB color string. This property determines the color of the axis lines, tick marks, tick mark labels, and the axis grid lines of the respective x-, y-, and z-axis. The default color axis color is black. See ColorSpec for details on specifying colors. XDir, YDir, ZDir {normal} | reverse Direction of increasing values. A mode controlling the direction of increasing axis values. axes form a right-hand coordinate system. By default: x-axis values increase from left to right. To reverse the direction of increasing x values, set this property to reverse. set(gca,'XDir','reverse') y-axis values increase from bottom to top (2-D view) or front to back (3-D view). To reverse the direction of increasing y values, set this property to reverse. set(gca,'YDir','reverse') 2-113 Axes Properties z-axis values increase pointing out of the screen (2-D view) or from bottom to top (3-D view). To reverse the direction of increasing z values, set this property to reverse. set(gca,'ZDir','reverse') XGrid, YGrid, ZGrid on | {off} Axis gridline mode. When you set any of these properties to on, MATLAB draws grid lines perpendicular to the respective axis (i.e., along lines of constant x, y, or z values). Use the grid command to set all three properties on or off at once. set(gca,'XGrid','on') XLabel, YLabel, ZLabelhandle of text object Axis labels. The handle of the text object used to label the x, y, or z-axis, respectively. To assign values to any of these properties, you must obtain the handle to the text string you want to use as a label. This statement defines a text object and assigns its handle to the XLabel property: set(get(gca,'XLabel'),'String','axis label') MATLAB places the string 'axis label' appropriately for an x-axis label. Any text object whose handle you specify as an XLabel, YLabel, or ZLabel property is moved to the appropriate location for the respective label. Alternatively, you can use the xlabel, ylabel, and zlabel functions, which generally provide a simpler means to label axis lines. XLim, YLim, ZLim [minimum maximum] Axis limits. A two-element vector specifying the minimum and maximum values of the respective axis. Changing these properties affects the scale of the x-, y-, or z-dimension as well as the placement of labels and tick marks on the axis. The default values for these properties are [0 1]. XLimMode, YLimMode, ZLimMode{auto} | manual MATLAB or user-controlled limits. The axis limits mode determines whether MATLAB calculates axis limits based on the data plotted (i.e., the XData, YData, or ZData of the axes children) or uses the values explicitly set with the XLim, YLim, or ZLim property, in which case, the respective limits mode is set to manual. 2-114 Axes Properties XMinorGrid, YMinorGrid, ZMinorGridon | {off} Enable or disable minor gridlines. When set to on, MATLAB draws gridlines aligned with the minor tick marks of the respective axis. Note that you do not have to enable minor ticks to display minor grids. XMinorTick, YMinorTick, ZMinorTickon | {off} Enable or disable minor tick marks. When set to on, MATLAB draws tick marks between the major tick marks of the respective axis. MATLAB automaticaly determines the number of minor ticks based on the space between the major ticks. XScale, YScale, ZScale{linear} | log Axis scaling. Linear or logarithmic scaling for the respective axis. See also loglog, semilogx, and semilogy. XTick, YTick, ZTickvector of data values locating tick marks Tick spacing. A vector of x-, y-, or z-data values that determine the location of tick marks along the respective axis. If you do not want tick marks displayed, set the respective property to the empty vector, [ ]. These vectors must contain monotonically increasing values. XTickLabel, YTickLabel, ZTickLabelstring Tick labels. A matrix of strings to use as labels for tick marks along the respective axis. These labels replace the numeric labels generated by MATLAB. If you do not specify enough text labels for all the tick marks, MATLAB uses all of the labels specified, then reuses the specified labels. For example, the statement, set(gca,'XTickLabel',{'One';'Two';'Three';'Four'}) labels the first four tick marks on the x-axis and then reuses the labels until all ticks are labeled. Labels can be specified as cell arrays of strings, padded string matrices, string vectors separated by vertical slash characters, or as numeric vectors (where each number is implicitly converted to the equivalent string using num2str). All of the following are equivalent: set(gca,'XTickLabel',{'1';'10';'100'}) set(gca,'XTickLabel','1|10|100') 2-115 Axes Properties set(gca,'XTickLabel',[1;10;100]) set(gca,'XTickLabel',['1 ';'10 ';'100']) Note that tick labels do not interpret TeX character sequences (however, the Title, XLabel, YLabel, and ZLabel properties do). XTickMode, YTickMode, ZTickMode{auto} | manual MATLAB or user controlled tick spacing. The axis tick modes determine whether MATLAB calculates the tick mark spacing based on the range of data for the respective axis (auto mode) or uses the values explicitly set for any of the XTick, YTick, and ZTick properties (manual mode). Setting values for the XTick, YTick, or ZTick properties sets the respective axis tick mode to manual. XTickLabelMode, YTickLabelMode, ZTickLabelMode{auto} | manual MATLAB or user determined tick labels. The axis tick mark labeling mode determines whether MATLAB uses numeric tick mark labels that span the range of the plotted data (auto mode) or uses the tick mark labels specified with the XTickLabel, YTickLabel, or ZTickLabel property (manual mode). Setting values for the XTickLabel, YTickLabel, or ZTickLabel property sets the respective axis tick label mode to manual. 2-116 axis Purpose Syntax 2axis Axis scaling and appearance axis([xmin xmax ymin ymax]) axis([xmin xmax ymin ymax zmin zmax cmin cmax]) v = axis axis axis axis axis auto manual tight fill axis ij axis xy axis axis axis axis axis equal image square vis3d normal axis off axis on [mode,visibility,direction] = axis('state') Description axis manipulates commonly used axes properties. (See Algorithm section.) axis([xmin xmax ymin ymax]) sets the limits for the x- and y-axis of the current axes. axis([xmin xmax ymin ymax zmin zmax cmin cmax]) sets the x-, y-, and z-axis limits and the color scaling limits (see caxis) of the current axes. v = axis returns a row vector containing scaling factors for the x-, y-, and z-axis. v has four or six components depending on whether the current axes is 2-D or 3-D, respectively. The returned values are the current axes XLim, Ylim, and ZLim properties. 2-117 axis axis auto sets MATLAB to its default behavior of computing the current axes limits automatically, based on the minimum and maximum values of x, y, and z data. You can restrict this automatic behavior to a specific axis. For example, axis 'auto x' computes only the x-axis limits automatically; axis 'auto yz' computes the y- and z-axis limits automatically. axis manual and axis(axis) freezes the scaling at the current limits, so that if hold is on, subsequent plots use the same limits. This sets the XLimMode, YLimMode, and ZLimMode properties to manual. axis tight sets the axis limits to the range of the data. axis fill sets the axis limits to the range of the data. axis ij places the coordinate system origin in the upper-left corner. The i-axis is vertical, with values increasing from top to bottom. The j-axis is horizontal with values increasing from left to right. axis xy draws the graph in the default Cartesian axes format with the coordinate system origin in the lower-left corner. The x-axis is horizontal with values increasing from left to right. The y-axis is vertical with values increasing from bottom to top. axis equal sets the aspect ratio so that the data units are the same in every direction. The aspect ratio of the x-, y-, and z-axis is adjusted automatically according to the range of data units in the x, y, and z directions. axis image is the same as axis equal except that the plot box fits tightly around the data. axis square makes the current axes region square (or cubed when three-dimensional). MATLAB adjusts the x-axis, y-axis, and z-axis so that they have equal lengths and adjusts the increments between data units accordingly. axis vis3d freezes aspect ratio properties to enable rotation of 3-D objects and overrides stretch-to-fill. axis normal automatically adjusts the aspect ratio of the axes and the aspect ratio of the data units represented on the axes to fill the plot box. 2-118 axis axis off turns off all axis lines, tick marks, and labels. axis on turns on all axis lines, tick marks, and labels. [mode,visibility,direction] = axis('state') returns three strings indicating the current setting of axes properties: Output Argument mode visibility direction Strings Returned 'auto' | 'manual' 'on' | 'off' 'xy' | 'ij' mode is auto if XLimMode, YLimMode, and ZLimMode are all set to auto. If XLimMode, YLimMode, or ZLimMode is manual, mode is manual. Examples The statements x = 0:.025:pi/2; plot(x,tan(x),'-ro') 2-119 axis use the automatic scaling of the y-axis based on ymax = tan(1.57), which is well over 1000: 1400 1200 1000 800 600 400 200 0 0 0.2 0.4 0.6 0.8 1 1.2 1.4 1.6 The right figure shows a more satisfactory plot after typing 2-120 axis axis([0 pi/2 0 5]) 5 4.5 4 3.5 3 2.5 2 1.5 1 0.5 0 0 0.5 1 1.5 Algorithm When you specify minimum and maximum values for the x-, y-, and z-axes, axis sets the XLim, Ylim, and ZLim properties for the current axes to the respective minimum and maximum values in the argument list. Additionally, the XLimMode, YLimMode, and ZLimMode properties for the current axes are set to manual. axis auto sets the current axes XLimMode, YLimMode, and ZLimMode properties to 'auto'. axis manual sets the current axes XLimMode, YLimMode, and ZLimMode properties to 'manual'. 2-121 axis The following table shows the values of the axes properties set by axis equal, axis normal, axis square, and axis image. Axes Property DataAspectRatio DataAspectRatioMode PlotBoxAspectRatio PlotBoxAspectRatioMode Stretch-to-fill axis equal [1 1 1] manual [3 4 4] manual disabled axis normal not set auto not set auto active axis square not set auto [1 1 1] manual disabled axis tightequal [1 1 1] manual auto auto disabled See Also axes, get, grid, set, subplot Properties of axes graphics objects 2-122 balance Purpose Syntax Description 2balance Improve accuracy of computed eigenvalues [T,B] = balance(A) B = balance(A) [T,B] = balance(A) returns a permutation of a diagonal matrix T whose elements are integer powers of two, and a balanced matrix B so that B = T\A*T. If A is symmetric, then B == A and T is the identity matrix. B = balance(A) returns just the balanced matrix B. Remarks Nonsymmetric matrices can have poorly conditioned eigenvalues. Small perturbations in the matrix, such as roundoff errors, can lead to large perturbations in the eigenvalues. The condition number of the eigenvector matrix, cond(V) = norm(V)*norm(inv(V)) where [V,T] = eig(A) relates the size of the matrix perturbation to the size of the eigenvalue perturbation. Note that the condition number of A itself is irrelevant to the eigenvalue problem. Balancing is an attempt to concentrate any ill conditioning of the eigenvector matrix into a diagonal scaling. Balancing usually cannot turn a nonsymmetric matrix into a symmetric matrix; it only attempts to make the norm of each row equal to the norm of the corresponding column. Furthermore, the diagonal scale factors are limited to powers of two so they do not introduce any roundoff error. Note MATLAB s eigenvalue function, eig(A), automatically balances A before computing its eigenvalues. Turn off the balancing with eig(A,'nobalance'). 2-123 balance Examples This example shows the basic idea. The matrix A has large elements in the upper right and small elements in the lower left. It is far from being symmetric. A = [1 100 10000; .01 1 100; .0001 A = 1.0e+04 * 0.0001 0.0100 1.0000 0.0000 0.0001 0.0100 0.0000 0.0000 0.0001 .01 1] Balancing produces a diagonal T matrix with elements that are powers of two and a balanced matrix B that is closer to symmetric than A. [T,B] = balance(A) T = 1.0e+03 * 2.0480 0 0 0.0320 0 0 B = 1.0000 1.5625 0.6400 1.0000 0.8192 1.2800 0 0 0.0003 1.2207 0.7813 1.0000 To see the effect on eigenvectors, first compute the eigenvectors of A. [V,E] = eig(A); V V = -1.0000 0.9999 0.0050 0.0100 0.0000 0.0001 0.9937 -0.1120 0.0010 Note that all three vectors have the first component the largest. This indicates V is badly conditioned; in fact cond(V) is 8.7766e+003. Next, look at the eigenvectors of B. [V,E] = eig(B); V V = -0.8873 0.6933 0.2839 0.4437 0.3634 0.5679 0.0898 -0.6482 -0.7561 2-124 balance Now the eigenvectors are well behaved and cond(V) is 1.4421. The ill conditioning is concentrated in the scaling matrix; cond(T) is 8192. This example is small and not really badly scaled, so the computed eigenvalues of A and B agree within roundoff error; balancing has little effect on the computed results. Algorithm The eig function automatically uses balancing to prepare its input matrix. balance uses LAPACK routines DGEBAL (real) and ZGEBAL (complex). If you request the output T, it also uses the LAPACK routines DGEBAK (real) and ZGEBAK (complex). Balancing can destroy the properties of certain matrices; use it with some care. If a matrix contains small elements that are due to roundoff error, balancing may scale them up to make them as significant as the other elements of the original matrix. condeig, eig, hess, schur Limitations See Also 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-125 bar, barh Purpose Syntax 2bar, barh Bar chart bar(Y) bar(x,Y) bar(...,width) bar(...,'style') bar(...,LineSpec) h = bar(...) barh(...) h = barh(...) Description A bar chart displays the values in a vector or matrix as horizontal or vertical bars. bar(Y) draws one bar for each element in Y. If Y is a matrix, bar groups the bars produced by the elements in each row. The x-axis scale ranges from 1 to length(Y) when Y is a vector, and 1 to size(Y,1), which is the number of rows, when Y is a matrix. bar(x,Y) draws a bar for each element in Y at locations specified in x, where x is a monotonically increasing vector defining the x-axis intervals for the vertical bars. If Y is a matrix, bar clusters the elements in the same row in Y at locations corresponding to an element in x. bar(...,width) sets the relative bar width and controls the separation of bars within a group. The default width is 0.8, so if you do not specify x, the bars within a group have a slight separation. If width is 1, the bars within a group touch one another. bar(...,'style') specifies the style of the bars. 'style' is 'grouped' or 'stacked'. 'group' is the default mode of display. 'grouped' displays n groups of m vertical bars, where n is the number of rows and m is the number of columns in Y. The group contains one bar per column in Y. 'stacked' displays one bar for each row in Y. The bar height is the sum of the elements in the row. Each bar is multi-colored, with colors corresponding to 2-126 bar, barh distinct elements and showing the relative contribution each row element makes to the total sum. bar(...,LineSpec) displays all bars using the color specified by LineSpec. h = bar(...) returns a vector of handles to patch graphics objects. bar creates one patch graphics object per column in Y. barh(...), and h = barh(...) create horizontal bars. Y determines the bar length. The vector x is a monotonic vector defining the y-axis intervals for horizontal bars. Examples Plot a bell shaped curve: x = 2.9:0.2:2.9; bar(x,exp( x.*x)) colormap hsv 1 0.9 0.8 0.7 0.6 0.5 0.4 0.3 0.2 0.1 0 3 2 1 0 1 2 3 Create four subplots showing the effects of various bar arguments: Y = round(rand(5,3)*10); subplot(2,2,1) bar(Y,'group') title 'Group' 2-127 bar, barh subplot(2,2,2) bar(Y,'stack') title 'Stack' subplot(2,2,3) barh(Y,'stack') title 'Stack' subplot(2,2,4) bar(Y,1.5) title 'Width = 1.5' Group 10 8 6 4 2 0 1 2 3 Stack 10 5 4 3 2 1 0 5 10 15 20 25 4 2 0 1 2 8 6 4 5 25 20 15 10 5 0 1 2 Stack 3 4 5 Width = 1.5 3 4 5 2-128 bar, barh See Also bar3, ColorSpec, patch, stairs, hist 2-129 bar3, bar3h Purpose Syntax 2bar3, bar3h Three-dimensional bar chart bar3(Y) bar3(x,Y) bar3(...,width) bar3(...,'style') bar3(...,LineSpec) h = bar3(...) bar3h(...) h = bar3h(...) Description bar3 and bar3h draw three-dimensional vertical and horizontal bar charts. bar3(Y) draws a three-dimensional bar chart, where each element in Y corresponds to one bar. When Y is a vector, the x-axis scale ranges from 1 to length(Y). When Y is a matrix, the x-axis scale ranges from 1 to size(Y,2), which is the number of columns, and the elements in each row are grouped together. bar3(x,Y) draws a bar chart of the elements in Y at the locations specified in x, where x is a monotonic vector defining the y-axis intervals for vertical bars. If Y is a matrix, bar3 clusters elements from the same row in Y at locations corresponding to an element in x. Values of elements in each row are grouped together. bar3(...,width) sets the width of the bars and controls the separation of bars within a group. The default width is 0.8, so if you do not specify x, bars within a group have a slight separation. If width is 1, the bars within a group touch one another. bar3(...,'style') specifies the style of the bars. 'style' is 'detached', 'grouped', or 'stacked'. 'detached' is the default mode of display. 'detached' displays the elements of each row in Y as separate blocks behind one another in the x direction. 'grouped' displays n groups of m vertical bars, where n is the number of rows and m is the number of columns in Y. The group contains one bar per column in Y. 2-130 bar3, bar3h 'stacked' displays one bar for each row in Y. The bar height is the sum of the elements in the row. Each bar is multi-colored, with colors corresponding to distinct elements and showing the relative contribution each row element makes to the total sum. bar3(...,LineSpec) displays all bars using the color specified by LineSpec. h = bar3(...) returns a vector of handles to patch graphics objects. bar3 creates one patch object per column in Y. bar3h(...) and h = bar3h(...) create horizontal bars. Y determines the bar length. The vector x is a monotonic vector defining the y-axis intervals for horizontal bars. Examples This example creates six subplots showing the effects of different arguments for bar3. The data Y is a seven-by-three matrix generated using the cool colormap: Y = cool(7); subplot(3,2,1) bar3(Y,'detached') title('Detached') subplot(3,2,2) bar3(Y,0.25,'detached') title('Width = 0.25') subplot(3,2,3) bar3(Y,'grouped') title('Grouped') subplot(3,2,4) bar3(Y,0.5,'grouped') title('Width = 0.5') 2-131 bar3, bar3h subplot(3,2,5) bar3(Y,'stacked') title('Stacked') subplot(3,2,6) bar3(Y,0.3,'stacked') title('Width = 0.3') colormap([1 0 0;0 1 0;0 0 1]) 2-132 bar3, bar3h Detached 1 1 Width = 0.25 0.5 0.5 0 1 2 3 0 1 4 5 6 2 3 4 5 7 6 7 Grouped 1 1 Width = 0.5 0.5 0.5 0 1 2 3 0 1 4 5 6 2 3 4 5 7 6 7 Stacked 2 1.5 1 0.5 0 1 2 3 2 1.5 1 0.5 0 1 4 5 6 2 3 Width = 0.3 4 5 7 6 7 See Also bar, LineSpec, patch 2-133 base2dec Purpose Syntax Description 2base2dec Base to decimal number conversion d = base2dec('strn',base) d = base2dec('strn',base) converts the string number strn of the specified base into its decimal (base 10) equivalent. base must be an integer between 2 and 36. If 'strn' is a character array, each row is interpreted as a string in the specified base. Examples See Also The expression base2dec('212',3) converts 2123 to decimal, returning 23. dec2base 2-134 beep Purpose Syntax 2beep Produce a beep sound beep beep on beep off s = beep beep produces you computer s default beep sound beep on turns the beep on beep off turn the beep off s = beep returns the current beep mode (on or off) Description 2-135 besselh Purpose Syntax 2besselh Bessel functions of the third kind (Hankel functions) H = besselh(nu,K,Z) H = besselh(nu,Z) H = besselh(nu,1,Z,1) H = besselh(nu,2,Z,1) [H,ierr] = besselh(...) De nitions The differential equation z 2d 2 y 2 dz dy 2 2 + z ------ + ( z ) y = 0 dz where is a nonnegative constant, is called Bessel s equation, and its solutions are known as Bessel functions. J ( z ) and J ( z ) form a fundamental set of solutions of Bessel s equation for noninteger . Y ( z ) is a second solution of Bessel s equation linearly independent of J ( z ) defined by J ( z ) cos ( ) J ( z ) Y ( z ) = ----------------------------------------------------------sin ( ) The relationship between the Hankel and Bessel functions is H ( z) = J ( z) + i Y ( z) H2 ( z ) = J ( z ) i Y ( z ) (1) Description H = besselh(nu,K,Z) for K = 1 or 2 computes the Hankel functions H ( z ) or H ( z ) for each element of the complex array Z. If nu and Z are arrays of the same size, the result is also that size. If either input is a scalar, it is expanded to the other input's size. If one input is a row vector and the other is a column vector, the result is a two-dimensional table of function values. H = besselh(nu,Z) uses K = 1. H = besselh(nu,1,Z,1) scales H ( z ) by exp(-i*z). H = besselh(nu,2,Z,1) scales H ( z ) by exp(+i*z). (2) (1) (1) (2) 2-136 besselh [H,ierr] = besselh(...) also returns an array of error flags: ierr = 1 ierr = 2 ierr = 3 ierr = 4 ierr = 5 Illegal arguments. Over ow. Return Inf. Some loss of accuracy in argument reduction. Unacceptable loss of accuracy, Z or nu too large. No convergence. Return NaN. 2-137 besseli, besselk Purpose Syntax 2besseli, besselk Modified Bessel functions I = besseli(nu,Z) Modified Bessel function of the 1st kind K = besselk(nu,Z) Modified Bessel function of the 2nd kind I = besseli(nu,Z,1) K = besselk(nu,Z,1) [I,ierr] = besseli(...) [K,ierr] = besselk(...) De nitions The differential equation z2 d y dy + z ------ ( z 2 + 2 ) y = 0 dz d z2 2 where is a real constant, is called the modified Bessel s equation, and its solutions are known as modified Bessel functions. I ( z ) and I ( z ) form a fundamental set of solutions of the modified Bessel s equation for noninteger . K ( z ) is a second solution, independent of I ( z ) . I ( z ) and K ( z ) are defined by z I ( z ) = -- 2 k=0 z ----- 4 --------------------------------------k! ( + k + 1 ) 2 k I ( z ) I ( z ) K ( z ) = -- ---------------------------------- 2 sin ( ) where (a) is the gamma function. Description I = besseli(nu,Z) computes modified Bessel functions of the first kind, I ( z ) , for each element of the array Z. The order nu need not be an integer, but must be real. The argument Z can be complex. The result is real where Z is positive. If nu and Z are arrays of the same size, the result is also that size. If either input is a scalar, it is expanded to the other input's size. If one input is a row vector 2-138 besseli, besselk and the other is a column vector, the result is a two-dimensional table of function values. K = besselk(nu,Z) computes modified Bessel functions of the second kind, K ( z ) , for each element of the complex array Z. I = besseli(nu,Z,1) computes besseli(nu,Z).*exp(-abs(real(Z))). K = besselk(nu,Z,1) computes besselk(nu,Z).*exp(Z). [I,ierr] = besseli(...) and [K,ierr] = besselk(...) also return an array of error flags: ierr = 1 ierr = 2 ierr = 3 ierr = 4 ierr = 5 Illegal arguments. Over ow. Return Inf. Some loss of accuracy in argument reduction. Unacceptable loss of accuracy, Z or nu too large. No convergence. Return NaN. Examples format long z = (0:0.2:1)'; besseli(1,z) ans = 0 0.10050083402813 0.20402675573357 0.31370402560492 0.43286480262064 0.56515910399249 besselk(1,z) ans = Inf 4.77597254322047 2.18435442473269 2-139 besseli, besselk 1.30283493976350 0.86178163447218 0.60190723019723 besseli(3:9,(0:.2,10)',1) generates the entire table on page 423 of [1] Abramowitz and Stegun, Handbook of Mathematical Functions. besselk(3:9,(0:.2:10)',1) generates part of the table on page 424 of [1] Abramowitz and Stegun, Handbook of Mathematical Functions. Algorithm See Also References The besseli and besselk functions use a Fortran MEX-file to call a library developed by D. E. Amos [3] [4]. airy, besselj, bessely [1] Abramowitz, M. and I.A. Stegun, Handbook of Mathematical Functions, National Bureau of Standards, Applied Math. Series #55, Dover Publications, 1965, sections 9.1.1, 9.1.89 and 9.12, formulas 9.1.10 and 9.2.5. [2] Carrier, Krook, and Pearson, Functions of a Complex Variable: Theory and Technique, Hod Books, 1983, section 5.5. [3] Amos, D. E., A Subroutine Package for Bessel Functions of a Complex Argument and Nonnegative Order, Sandia National Laboratory Report, SAND85-1018, May, 1985. [4] Amos, D. E., A Portable Package for Bessel Functions of a Complex Argument and Nonnegative Order, Trans. Math. Software, 1986. 2-140 besselj, bessely Purpose Syntax 2besselj, bessely Bessel functions J = besselj(nu,Z) Bessel function of the 1st kind Y = bessely(nu,Z) Bessel function of the 2nd kind J = besselj(nu,Z,1) Y = bessely(nu,Z,1) [J,ierr] = besselj(nu,Z) [Y,ierr] = bessely(nu,Z) De nition The differential equation z 2d 2 y 2 dz dy 2 2 + z ------ + ( z ) y = 0 dz where is a real constant, is called Bessel s equation, and its solutions are known as Bessel functions. J ( z ) and J ( z ) form a fundamental set of solutions of Bessel s equation for noninteger . J ( z ) is defined by z J ( z ) = -- 2 k=0 z ----- 4 --------------------------------------k! ( + k + 1 ) 2 k where (a) is the gamma function. Y ( z ) is a second solution of Bessel s equation that is linearly independent of J ( z ) and defined by J ( z ) cos ( ) J ( z ) Y ( z ) = ----------------------------------------------------------sin ( ) Description J = besselj(nu,Z) computes Bessel functions of the first kind, J ( z ) , for each element of the complex array Z. The order nu need not be an integer, but must be real. The argument Z can be complex. The result is real where Z is positive. If nu and Z are arrays of the same size, the result is also that size. If either input is a scalar, it is expanded to the other input's size. If one input is a row vector 2-141 besselj, bessely and the other is a column vector, the result is a two-dimensional table of function values. Y = bessely(nu,Z) computes Bessel functions of the second kind, Y ( z ) , for real, nonnegative order nu and argument Z. J = besselj(nu,Z,1) computes besselj(nu,Z).*exp(-abs(imag(Z))). Y = bessely(nu,Z,1) computes bessely(nu,Z).*exp(-abs(imag(Z))). [J,ierr] = besselj(nu,Z) and [Y,ierr] = bessely(nu,Z) also return an array of error flags: ierr = 1 ierr = 2 ierr = 3 ierr = 4 ierr = 5 Illegal arguments. Over ow. Return Inf. Some loss of accuracy in argument reduction. Unacceptable loss of accuracy, Z or nu too large. No convergence. Return NaN. Remarks The Bessel functions are related to the Hankel functions, also called Bessel functions of the third kind, H ( z) = J ( z) + i Y ( z) H ( z) = J ( z) i Y ( z) where J ( z ) is besselj, and Y ( z ) is bessely. The Hankel functions also form a fundamental set of solutions to Bessel s equation (see besselh). (2) (1) Examples format long z = (0:0.2:1)'; besselj(1,z) ans = 0 0.09950083263924 2-142 besselj, bessely 0.19602657795532 0.28670098806392 0.36884204609417 0.44005058574493 bessely(1,z) ans = -Inf -3.32382498811185 -1.78087204427005 -1.26039134717739 -0.97814417668336 -0.78121282130029 besselj(3:9,(0:.2:10)') generates the entire table on page 398 of [1] Abramowitz and Stegun, Handbook of Mathematical Functions. bessely(3:9,(0:.2:10)') generates the entire table on page 399 of [1] Abramowitz and Stegun, Handbook of Mathematical Functions. Algorithm See Also References The besselj and bessely functions use a Fortran MEX-file to call a library developed by D. E. Amos [3] [4]. airy, besseli, besselk [1] Abramowitz, M. and I.A. Stegun, Handbook of Mathematical Functions, National Bureau of Standards, Applied Math. Series #55, Dover Publications, 1965, sections 9.1.1, 9.1.89 and 9.12, formulas 9.1.10 and 9.2.5. [2] Carrier, Krook, and Pearson, Functions of a Complex Variable: Theory and Technique, Hod Books, 1983, section 5.5. [3] Amos, D. E., A Subroutine Package for Bessel Functions of a Complex Argument and Nonnegative Order, Sandia National Laboratory Report, SAND85-1018, May, 1985. [4] Amos, D. E., A Portable Package for Bessel Functions of a Complex Argument and Nonnegative Order, Trans. Math. Software, 1986. 2-143 beta, betainc, betaln Purpose Syntax 2beta, betainc, betaln Beta functions B = beta(Z,W) I = betainc(X,Z,W) L = betaln(Z,W) De nition The beta function is B ( z, w ) = 0 t z 1 ( 1 t ) w 1 dt x 1 ( z ) ( w ) = ----------------------- ( z + w) where ( z ) is the gamma function. The incomplete beta function is 1 I x ( z, w ) = ------------------B ( z, w ) 0 t z 1 ( 1 t ) w 1 dt Description B = beta(Z,W) computes the beta function for corresponding elements of the complex arrays Z and W. The arrays must be the same size (or either can be scalar). I = betainc(X,Z,W) computes the incomplete beta function. The elements of X must be in the closed interval [0,1] . L = betaln(Z,W) computes the natural logarithm of the beta function, log(beta(Z,W)), without computing beta(Z,W). Since the beta function can range over very large or very small values, its logarithm is sometimes more useful. Examples format rat beta((0:10)',3) ans = 1/0 1/3 1/12 1/30 1/60 1/105 2-144 beta, betainc, betaln 1/168 1/252 1/360 1/495 1/660 In this case, with integer arguments, beta(n,3) = (n-1)!*2!/(n+2)! = 2/(n*(n+1)*(n+2)) is the ratio of fairly small integers and the rational format is able to recover the exact result. For x = 510, betaln(x,x) = -708.8616, which is slightly less than log(realmin). Here beta(x,x) would underflow (or be denormal). Algorithm beta(z,w) = exp(gammaln(z)+gammaln(w)-gammaln(z+w)) betaln(z,w) = gammaln(z)+gammaln(w)-gammaln(z+w) 2-145 bicg Purpose Syntax 2bicg BiConjugate Gradients method x = bicg(A,b) bicg(A,b,tol) bicg(A,b,tol,maxit) bicg(A,b,tol,maxit,M) bicg(A,b,tol,maxit,M1,M2) bicg(A,b,tol,maxit,M1,M2,x0) bicg(afun,b,tol,maxit,mfun1,mfun2,x0,p1,p2,...) [x,flag] = bicg(A,b,...) [x,flag,relres] = bicg(A,b,...) [x,flag,relres,iter] = bicg(A,b,...) [x,flag,relres,iter,resvec] = bicg(A,b,...) x = bicg(A,b) attempts to solve the system of linear equations A*x = b for x. The n-by-n coefficient matrix A must be square and 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 bicg converges, a message to that effect is displayed. If bicg 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. bicg(A,b,tol specifies the tolerance of the method. If tol is [], then bicg uses the default, 1e-6. bicg(A,b,tol,maxit) specifies the maximum number of iterations. If maxit is [], then bicg uses the default, min(n,20). bicg(A,b,tol,maxit,M) and bicg(A,b,tol,maxit,M1,M2) use the preconditioner M or M = M1*M2 and effectively solve the system inv(M)*A*x = inv(M)*b for x. If M is [] then bicg applies no preconditioner. M can be a function mfun such that mfun(x) returns M\x and mfun(x,'transp') returns M'\x. bicg(A,b,tol,maxit,M1,M2,x0) specifies the initial guess. If x0 is [], then bicg uses the default, an all-zero vector. 2-146 bicg bicg(afun,b,tol,maxit,m1fun,m2fun,x0,p1,p2,...) passes parameters p1,p2,... to functions afun(x,p1,p2,...) and afun(x,p1,p2,...,'transp'), and similarly to the preconditioner functions m1fun and m2fun. [x,flag] = bicg(A,b,...) also returns a convergence flag. Flag 0 Convergence bicg converged to the desired tolerance tol within maxit iterations. 1 2 3 4 bicg iterated maxit times but did not converge. Preconditioner M was ill-conditioned. bicg stagnated. (Two consecutive iterates were the same.) One of the scalar quantities calculated during bicg became too small or too large to continue computing. Whenever flag is not 0, the solution x returned is that with minimal norm residual computed over all the iterations. No messages are displayed if the flag output is specified. [x,flag,relres] = bicg(A,b,...) also returns the relative residual norm(b-A*x)/norm(b). If flag is 0, relres <= tol. [x,flag,relres,iter] = bicg(A,b,...) also returns the iteration number at which x was computed, where 0 <= iter <= maxit. [x,flag,relres,iter,resvec] = bicg(A,b,...) also returns a vector of the residual norms at each iteration including norm(b-A*x0). Examples Example 1. n = 100; on = ones(n,1); A = spdiags([-2*on 4*on -on],-1:1,n,n); b = sum(A,2); tol = 1e-8; 2-147 bicg maxit = 15; M1 = spdiags([on/(-2) on],-1:0,n,n); M2 = spdiags([4*on -on],0:1,n,n); x = bicg(A,b,tol,maxit,M1,M2,[]); bicg converged at iteration 9 to a solution with relative residual 5.3e-009 Alternatively, use this matrix-vector product function function y = afun(x,n,transp_flag) if (nargin > 2) & strcmp(transp_flag,'transp') y = 4 * x; y(1:n-1) = y(1:n-1) - 2 * x(2:n); y(2:n) = y(2:n) - x(1:n-1); else y = 4 * x; y(2:n) = y(2:n) - 2 * x(1:n-1); y(1:n-1) = y(1:n-1) - x(2:n); end as input to bicg. x1 = bicg(@afun,b,tol,maxit,M1,M2,[],n); Example 2. Start with A = west0479 and make the true solution the vector of all ones. load west0479; A = west0479; b = sum(A,2); You can accurately solve A*x = b using backslash since A is not so large. x = A \ b; norm(b-A*x) / norm(b) ans = 1.2454e-017 Now try to solve A*x = b with bicg. [x,flag,relres,iter,resvec] = bicg(A,b) 2-148 bicg flag = 1 relres = 1 iter = 0 The value of flag indicates that bicg iterated the default 20 times without converging. The value of iter shows that the method behaved so badly that the initial all-zero guess was better than all the subsequent iterates. The value of relres supports this: relres = norm(b-A*x)/norm(b) = norm(b)/norm(b) = 1. You can confirm that the unpreconditioned method oscillates rather wildly by plotting the relative residuals at each iteration. semilogy(0:20,resvec/norm(b),'-o') xlabel('iteration number') ylabel('relative residual') 10 5 10 4 relative residual 10 3 10 2 10 1 10 0 0 2 4 6 8 10 12 iteration number 14 16 18 20 Now, try an incomplete LU factorization with a drop tolerance of 1e-5 for the preconditioner. 2-149 bicg [L1,U1] = luinc(A,1e-5); Warning: Incomplete upper triangular factor has 1 zero diagonal. It cannot be used as a preconditioner for an iterative method. nnz(A) ans = 1887 nnz(L1) ans = 5562 nnz(U1) ans = 4320 The zero on the main diagonal of the upper triangular U1 indicates that U1 is singular. If you try to use it as a preconditioner, [x,flag,relres,iter,resvec] = bicg(A,b,1e-6,20,L1,U1) flag = 2 relres = 1 iter = 0 resvec = 7.0557e+005 the method fails in the very first iteration when it tries to solve a system of equations involving the singular U1 using backslash. bicg is forced to return the initial estimate since no other iterates were produced. Try again with a slightly less sparse preconditioner. [L2,U2] = luinc(A,1e-6) nnz(L2) ans = 6231 nnz(U2) ans = 2-150 bicg 4559 This time U2 is nonsingular and may be an appropriate preconditioner. [x,flag,relres,iter,resvec] = bicg(A,b,1e-15,10,L2,U2) flag = 0 relres = 2.0248e-16 iter = 8 and bicg converges to within the desired tolerance at iteration number 8. Decreasing the value of the drop tolerance increases the fill-in of the incomplete factors but also increases the accuracy of the approximation to the original matrix. Thus, the preconditioned system becomes closer to inv(U)*inv(L)*L*U*x = inv(U)*inv(L)*b, where L and U are the true LU factors, and closer to being solved within a single iteration. The next graph shows the progress of bicg using six different incomplete LU factors as preconditioners. Each line in the graph is labeled with the drop tolerance of the preconditioner used in bicg. 2-151 bicg 10 0 10 relative residual 5 10 10 10 15 1e 12 1e 14 0 1 2 3 1e 10 1e 8 6 7 1e 6 8 4 5 iteration number This does not give us any idea of the time involved in creating the incomplete factors and then computing the solution. The following graph plots the drop tolerance of the incomplete LU factors against the time to compute the preconditioner, the time to iterate once the preconditioner has been computed, and their sum, the total time to solve the problem. The time to produce the factors does not increase very quickly with the fill-in, but it does slow down the average time for an iteration. Since fewer iterations are performed, the total time to solve the problem decreases. west0479 is quite a small matrix, only 139-by-139, and preconditioned bicg still takes longer than backslash. 2-152 bicg 0.4 precondition and iterate iterate compute preconditioner time to precondition and converge to 1e 12 0.35 0.3 0.25 0.2 0.15 0.1 0.05 14 10 10 13 10 10 10 10 10 drop tolerance of incomplete LU preconditioner 12 11 10 9 8 10 7 10 6 See Also bicgstab, cgs, gmres, lsqr, luinc, minres, pcg, qmr, symmlq @ (function handle), \ (backslash) References [1] Barrett, R., M. Berry, T. F. Chan, et al., Templates for the Solution of Linear Systems: Building Blocks for Iterative Methods, SIAM, Philadelphia, 1994. 2-153 bicgstab Purpose Syntax 2bicgstab BiConjugate Gradients Stabilized method x = bicgstab(A,b) bicgstab(A,b,tol) bicgstab(A,b,tol,maxit) bicgstab(A,b,tol,maxit,M) bicgstab(A,b,tol,maxit,M1,M2) bicgstab(A,b,tol,maxit,M1,M2,x0) bicgstab(afun,b,tol,maxit,m1fun,m2fun,x0,p1,p2,...) [x,flag] = bicgstab(A,b,...) [x,flag,relres] = bicgstab(A,b,...) [x,flag,relres,iter] = bicgstab(A,b,...) [x,flag,relres,iter,resvec] = bicgstab(A,b,...) x = bicgstab(A,b) attempts to solve the system of linear equations A*x=b for x. The n-by-n coefficient matrix A must be square and the column vector b must have length n. A can be a function afun such that afun(x) returns A*x. Description If bicgstab converges, a message to that effect is displayed. If bicgstab fails to converge after the maximum number of iterations or halts for any reason, a warning message is printed displaying the relative residual norm(b-A*x)/ norm(b) and the iteration number at which the method stopped or failed. bicgstab(A,b,tol) specifies the tolerance of the method. If tol is [], then bicgstab uses the default, 1e-6. bicgstab(A,b,tol,maxit) specifies the maximum number of iterations. If maxit is [], then bicgstab uses the default, min(n,20). bicgstab(A,b,tol,maxit,M) and bicgstab(A,b,tol,maxit,M1,M2) use preconditioner M or M = M1*M2 and effectively solve the system inv(M)*A*x = inv(M)*b for x. If M is [] then bicgstab applies no preconditioner. M can be a function that returns M\x. bicgstab(A,b,tol,maxit,M1,M2,x0) specifies the initial guess. If x0 is [], then bicgstab uses the default, an all zero vector. 2-154 bicgstab bicgstab(afun,b,tol,maxit,m1fun,m2fun,x0,p1,p2,...) passes parameters p1,p2,... to functions afun(x,p1,p2,...), m1fun(x,p1,p2,...), and m2fun(x,p1,p2,...). [x,flag] = bicgstab(A,b,...) also returns a convergence flag. Flag 0 Convergence bicgstab converged to the desired tolerance tol within maxit iterations. bicgstab iterated maxit times but did not converge. 1 2 3 Preconditioner M was ill-conditioned. bicgstab stagnated. (Two consecutive iterates were the same.) 4 One of the scalar quantities calculated during bicgstab became too small or too large to continue computing. Whenever flag is not 0, the solution x returned is that with minimal norm residual computed over all the iterations. No messages are displayed if the flag output is specified. [x,flag,relres] = bicgstab(A,b,...) also returns the relative residual norm(b-A*x)/norm(b). If flag is 0, relres <= tol. [x,flag,relres,iter] = bicgstab(A,b,...) also returns the iteration number at which x was computed, where 0 <= iter <= maxit. iter can be an integer + 0.5, indicating convergence half way through an iteration. [x,flag,relres,iter,resvec] = bicgstab(A,b,...) also returns a vector of the residual norms at each half iteration, including norm(b-A*x0). Example Example 1. A = gallery('wilk',21); b = sum(A,2); tol = 1e-12; maxit = 15; 2-155 bicgstab M1 = diag([10:-1:1 1 1:10]); x = bicgstab(A,b,tol,maxit,M1,[],[]); bicgstab converged at iteration 12.5 to a solution with relative residual 1.2e-014 Alternatively, use this matrix-vector product function function y = afun(x,n) y = [0; x(1:n-1)] + [((n-1)/2:-1:0)'; (1:(n-1)/2)'] .*x + [x(2:n); 0]; and this preconditioner backsolve function function y = mfun(r,n) y = r ./ [((n-1)/2:-1:1)'; 1; (1:(n-1)/2)']; as inputs to bicgstab x1 = bicgstab(@afun,b,tol,maxit,@mfun,[],[],21); Note that both afun and mfun must accept bicgstab's extra input n=21. Example 2. load west0479; A = west0479; b = sum(A,2); [x,flag] = bicgstab(A,b) flag is 1 because bicgstab does not converge to the default tolerance 1e-6 within the default 20 iterations. [L1,U1] = luinc(A,1e-5); [x1,flag1] = bicgstab(A,b,1e-6,20,L1,U1) flag1 is 2 because the upper triangular U1 has a zero on its diagonal. This causes bicgstab to fail in the first iteration when it tries to solve a system such as U1*y = r using backslash. [L2,U2] = luinc(A,1e-6); [x2,flag2,relres2,iter2,resvec2] = bicgstab(A,b,1e-15,10,L2,U2) 2-156 bicgstab flag2 is 0 because bicgstab converges to the tolerance of 3.1757e-016 (the value of relres2) at the sixth iteration (the value of iter2) when preconditioned by the incomplete LU factorization with a drop tolerance of 1e-6. resvec2(1) = norm(b) and resvec2(13) = norm(b-A*x2). You can follow the progress of bicgstab by plotting the relative residuals at the halfway point and end of each iteration starting from the initial estimate (iterate number 0). semilogy(0:0.5:iter2,resvec2/norm(b),'-o') xlabel('iteration number') ylabel('relative residual') 10 0 10 2 10 4 10 relative residual 6 10 8 10 10 10 12 10 14 10 16 0 1 2 3 iteration number 4 5 6 See Also bicg, cgs, gmres, lsqr, luinc, minres, pcg, qmr, symmlq @ (function handle), \ (backslash) 2-157 bicgstab References [1] Barrett, R., M. Berry, T. F. Chan, et al., Templates for the Solution of Linear Systems: Building Blocks for Iterative Methods, SIAM, Philadelphia, 1994. [2] van der Vorst, H. A., BI-CGSTAB: A fast and smoothly converging variant of BI-CG for the solution of nonsymmetric linear systems , SIAM J. Sci. Stat. Comput., March 1992,Vol. 13, No. 2, pp. 631-644. 2-158 bin2dec Purpose Syntax Description Examples See Also 2bin2dec Binary to decimal number conversion bin2dec(binarystr) bin2dec(binarystr) interprets the binary string binarystr and returns the equivalent decimal number. bin2dec('010111') returns 23. dec2bin 2-159 bitand Purpose Syntax Description 2bitand Bit-wise AND C = bitand(A,B) C = bitand(A,B) returns the bit-wise AND of two nonnegative integer arguments A and B. To ensure the operands are integers, use the ceil, fix, floor, and round functions. Examples The five-bit binary representations of the integers 13 and 27 are 01101 and 11011, respectively. Performing a bit-wise AND on these numbers yields 01001, or 9. C = bitand(13,27) C = 9 See Also bitcmp, bitget, bitmax, bitor, bitset, bitshift, bitxor 2-160 bitcmp Purpose Syntax Description Example 2bitcmp Complement bits C = bitcmp(A,n) C = bitcmp(A,n) returns the bit-wise complement of A as an n-bit floating-point integer (flint). With eight-bit arithmetic, the ones complement of 01100011 (99, decimal) is 10011100 (156, decimal). C = bitcmp(99,8) C = 156 See Also bitand, bitget, bitmax, bitor, bitset, bitshift, bitxor 2-161 bitget Purpose Syntax Description 2bitget Get bit C = bitget(A,bit) C = bitget(A,bit) returns the value of the bit at position bit in A. Operand A must be a nonnegative integer, and bit must be a number between 1 and the number of bits in the floating-point integer (flint) representation of A (52 for IEEE flints). To ensure the operand is an integer, use the ceil, fix, floor, and round functions. Example The dec2bin function converts decimal numbers to binary. However, you can also use the bitget function to show the binary representation of a decimal number. Just test successive bits from most to least significant: disp(dec2bin(13)) 1101 C = bitget(13,4:-1:1) C = 1 1 0 1 See Also bitand, bitcmp, bitmax, bitor, bitset, bitshift, bitxor 2-162 bitmax Purpose Syntax Description See Also 2bitmax Maximum floating-point integer bitmax bitmax returns the maximum unsigned floating-point integer for your computer. It is the value when all bits are set, namely the value 2 bitand, bitcmp, bitget, bitor, bitset, bitshift, bitxor 53 1. 2-163 bitor Purpose Syntax Description 2bitor Bit-wise OR C = bitor(A,B) C = bitor(A,B) returns the bit-wise OR of two nonnegative integer arguments A and B. To ensure the operands are integers, use the ceil, fix, floor, and round functions. Examples The five-bit binary representations of the integers 13 and 27 are 01101 and 11011, respectively. Performing a bit-wise OR on these numbers yields 11111, or 31. C = bitor(13,27) C = 31 See Also bitand, bitcmp, bitget, bitmax, bitset, bitshift, bitxor 2-164 bitset Purpose Syntax Description 2bitset Set bit C = bitset(A,bit) C = bitset(A,bit,v) C = bitset(A,bit) sets bit position bit in A to 1 (on). A must be a nonnegative integer and bit must be a number between 1 and the number of bits in the floating-point integer (flint) representation of A (52 for IEEE flints). To ensure the operand is an integer, use the ceil, fix, floor, and round functions. C = bitset(A,bit,v) sets the bit at position bit to the value v, which must be either 0 or 1. Examples Setting the fifth bit in the five-bit binary representation of the integer 9 (01001) yields 11001, or 25. C = bitset(9,5) C = 25 See Also bitand, bitcmp, bitget, bitmax, bitor, bitshift, bitxor 2-165 bitshift Purpose Syntax Description 2bitshift Bit-wise shift C = bitshift(A,k,n) C = bitshift(A,k) C = bitshift(A,k,n) returns the value of A shifted by k bits. If k>0, this is same as a multiplication by 2k (left shift). If k<0, this is the same as a division by 2k (right shift). An equivalent computation for this function is C = fix(A*2^k). If the shift causes C to overflow n bits, the overflowing bits are dropped. A must contain nonnegative integers between 0 and BITMAX, which you can ensure by using the ceil, fix, floor, and round functions. C = bitshift(A,k) uses the default value of n = 53. Examples Shifting 1100 (12, decimal) to the left two bits yields 110000 (48, decimal). C = bitshift(12,2) C = 48 See Also bitand, bitcmp, bitget, bitmax, bitor, bitset, bitxor, fix 2-166 bitxor Purpose Syntax Description 2bitxor Bit-wise XOR C = bitxor(A,B) C = bitxor(A,B) returns the bit-wise XOR of the two arguments A and B. Both A and B must be integers. You can ensure this by using the ceil, fix, floor, and round functions. Examples The five-bit binary representations of the integers 13 and 27 are 01101 and 11011, respectively. Performing a bit-wise XOR on these numbers yields 10110, or 22. C = bitxor(13,27) C = 22 See Also bitand, bitcmp, bitget, bitmax, bitor, bitset, bitshift 2-167 blanks Purpose Syntax Description Examples 2blanks A string of blanks blanks(n) blanks(n) is a string of n blanks. blanks is useful with the display function. For example, disp(['xxx' blanks(20) 'yyy']) displays twenty blanks between the strings 'xxx' and 'yyy'. disp(blanks(n)') moves the cursor down n lines. See Also clc, format, home 2-168 blkdiag Purpose Syntax Description 2blkdiag Construct a block diagonal matrix from input arguments out = blkdiag(a,b,c,d,...) out = blkdiag(a,b,c,d,...) , where a, b, c, d, ... are matrices, outputs a block diagonal matrix of the form a 0 0 0 0 0 b 0 0 0 0 0 c 0 0 0 0 0 d 0 0 0 0 0 The input matrices do not have to be square, nor do they have to be of equal size. blkdiag works not only for matrices, but for any MATLAB objects which support horzcat and vertcat operations. See Also diag 2-169 box Purpose Syntax 2box Control axes border box on box off box box(axes_handle,...) box on displays the boundary of the current axes. box off does not display the boundary of the current axes. box toggles the visible state of the current axes boundary. box(axes_handle,...) uses the axes specified by axes_handle instead of the Description current axes. Algorithm See Also The box function sets the axes Box property to on or off. axes, grid 2-170 break Purpose Syntax Description 2break Terminate execution of a for loop or while loop break break terminates the execution of a for or while loop. Statements in the loop that appear after the break statement, are not executed. In nested loops, break exits only from the loop in which it occurs. Control passes to the statement that follows the end of that loop. Remarks If you use break outside of a for or while loop in a MATLAB script or function, break terminates the script or function at that point. If break is executed in an if, switch-case, or try-catch statement, it terminates the statement at that point. Examples The example below shows a while loop that reads the contents of the file fft.m into a MATLAB character array. A break statement is used to exit the while loop when the first empty line is encountered. The resulting character array contains the M-file help for the fft program. fid = fopen('fft.m','r'); s = ''; while ~feof(fid) line = fgetl(fid); if isempty(line), break, end s = strvcat(s,line); end disp(s) See Also for, while, end, continue, return 2-171 brighten Purpose Syntax 2brighten Brighten or darken colormap brighten(beta) brighten(h,beta) newmap = brighten(beta) newmap = brighten(cmap,beta) brighten increases or decreases the color intensities in a colormap. The modified colormap is brighter if 0 < beta < 1 and darker if 1 < beta < 0. brighten(beta) replaces the current colormap with a brighter or darker colormap of essentially the same colors. brighten(beta), followed by brighten( beta), where beta < 1, restores the original map. brighten(h,beta) brightens all objects that are children of the figure having the handle h. newmap = brighten(beta) returns a brighter or darker version of the current Description colormap without changing the display. newmap = brighten(cmap,beta) returns a brighter or darker version of the colormap cmap without changing the display. Examples Brighten and then darken the current colormap: beta = .5; brighten(beta); beta = .5; brighten(beta); Algorithm The values in the colormap are raised to the power of gamma, where gamma is 1 , = 1 ----------- 1 + , >0 0 brighten has no effect on graphics objects defined with true color. See Also colormap, rgbplot 2-172 builtin Purpose Syntax Description 2builtin Execute builtin function from overloaded method builtin(function,x1,...,xn) [y1,..,yn] = builtin(function,x1,...,xn) builtin is used in methods that overload builtin functions to execute the original builtin function. If function is a string containing the name of a builtin function, then builtin(function,x1,...,xn) evaluates that function at the given arguments. [y1,..,yn] = builtin(function,x1,...,xn) returns multiple output arguments. Remarks builtin(...) is the same as feval(...) except that it calls the original builtin version of the function even if an overloaded one exists. (For this to work you must never overload builtin.) feval See Also 2-173 bvp4c Purpose Syntax 2bvp4c Solve two-point boundary value problems (BVPs) for ordinary differential equations sol = bvp4c(odefun,bcfun,solinit) sol = bvp4c(odefun,bcfun,solinit,options) sol = bvp4c(odefun,bcfun,solinit,options,p1,p2...) odefun Arguments A function that evaluates the differential equations f ( x, y ) . It can have the form dydx dydx dydx dydx = = = = odefun(x,y) odefun(x,y,p1,p2,...) odefun(x,y,parameters) odefun(x,y,parameters,p1,p2,...) where x is a scalar corresponding to x , and y is a column vector corresponding to y . parameters is a vector of unknown parameters, and p1,p2,... are known parameters. The output dydx is a column vector. bcfun A function that computes the residual in the boundary conditions bc ( y ( a ), y ( b ) ) . It can have the form res res res res = = = = bcfun(ya,yb) bcfun(ya,yb,p1,p2,...) bcfun(ya,yb,parameters) bcfun(ya,yb,parameters,p1,p2,...) where ya and yb are column vectors corresponding to y ( a ) and y ( b ) . parameters is a vector of unknown parameters, and p1,p2,... are known parameters. The output res is a column vector. solinit A structure with elds: x Ordered nodes of the initial mesh. Boundary conditions are imposed at a = solinit.x(1) and b = solinit.x(end). Initial guess for the solution such that solinit.y(:,i) is a guess for the solution at the node solinit.x(i). y 2-174 bvp4c parameters Optional. A vector that provides an initial guess for unknown parameters. The structure can have any name, but the elds must be named x, y, and parameters. You can form solinit with the helper function bvpinit. See bvpinit for details. options Optional integration argument. A structure you create using the bvpset function. See bvpset for details. p1,p2... Optional. Known parameters that the solver passes to odefun, bcfun, and all the functions the user speci es in options. Description sol = bvp4c(odefun,bcfun,solinit) integrates a system of ordinary differential equations of the form y = f ( x, y ) on the interval [a,b] subject to general two-point boundary conditions bc ( y ( a ), y ( b ) ) = 0 The bvp4c solver can also find unknown parameters p for problems of the form y = f ( x, y, p ) bc ( y ( a ), y ( b ), p ) = 0 where p corresponds to parameters. You provide bvp4c an initial guess for any unknown parameters in solinit.parameters. The bvp4c solver returns the final values of these unknown parameters in sol.parameters. bvp4c produces a solution that is continuous on [a,b] and has a continuous first derivative there. Use the function deval and the output sol of bvp4c to evaluate the solution at specific points xint in the interval [a,b]. sxint = deval(sol,xint) The structure sol returned by bvp4c has the following fields: sol.x sol.y sol.yp Mesh selected by bvp4c Approximation to y ( x ) at the mesh points of sol.x Approximation to y ( x ) at the mesh points of sol.x 2-175 bvp4c sol.parameters sol.solver Values returned by bvp4c for the unknown parameters, if any 'bvp4c' The structure sol can have any name, and bvp4c creates the elds x, y, yp, parameters, and solver. sol = bvp4c(odefun,bcfun,solinit,options) solves as above with default integration properties replaced by the values in options, a structure created with the bvpset function. See bvpset for details. sol = bvp4c(odefun,bcfun,solinit,options,p1,p2...) passes constant known parameters, p1, p2, ..., to odefun, bcfun, and all the functions the user speci es in options. Use options = [] as a placeholder if no options are set. Examples Example 1. Boundary value problems can have multiple solutions and one purpose of the initial guess is to indicate which solution you want. The second order differential equation y + y = 0 has exactly two solutions that satisfy the boundary conditions y(0) = 0 y ( 4 ) = 2 Prior to solving this problem with bvp4c, you must write the differential equation as a system of two first order ODEs y1 = y2 y2 = y1 Here y 1 = y and y 2 = y . This system has the required form y = f ( x, y ) bc ( y ( a ), y ( b ) ) = 0 The function f and the boundary conditions bc are coded in MATLAB as functions twoode and twobc. 2-176 bvp4c function dydx = twoode(x,y) dydx = [ y(2) -abs(y(1))]; function res = twobc(ya,yb) res = [ ya(1) yb(1) + 2]; Form a guess structure consisting of an initial mesh of five equally spaced points in [0,4] and a guess of constant values y 1( x) 1 and y 2( x) 0 with the command solinit = bvpinit(linspace(0,4,5),[1 0]); Now solve the problem with sol = bvp4c(@twoode,@twobc,solinit); Evaluate the numerical solution at 100 equally spaced points and plot y ( x ) with x = linspace(0,4); y = deval(sol,x); plot(x,y(1,:)); 2.5 2 1.5 1 0.5 0 0.5 1 1.5 2 0 0.5 1 1.5 2 2.5 3 3.5 4 You can obtain the other solution of this problem with the initial guess 2-177 bvp4c solinit = bvpinit(linspace(0,4,5),[-1 0]); 2.5 2 1.5 1 0.5 0 0.5 1 1.5 2 0 0.5 1 1.5 2 2.5 3 3.5 4 Example 2. This boundary value problem involves an unknown parameter. The task is to compute the fourth ( q = 5 ) eigenvalue of Mathieu's equation y + ( 2 q cos 2x ) y = 0 Because the unknown parameter is present, this second order differential equation is subject to three boundary conditions y ( 0 ) = 0 y ( ) = 0 y(0) = 1 It is convenient to use subfunctions to place all the functions required by bvp4c in a single M-file. function mat4bvp lambda = 15; solinit = bvpinit(linspace(0,pi,10),@mat4init,lambda); sol = bvp4c(@mat4ode,@mat4bc,solinit); 2-178 bvp4c fprintf('The fourth eigenvalue is approximately %7.3f.\n',... sol.parameters) xint = linspace(0,pi); Sxint = deval(sol,xint); plot(xint,Sxint(1,:)) axis([0 pi -1 1.1]) title('Eigenfunction of Mathieu''s equation.') xlabel('x') ylabel('solution y') % -----------------------------------------------------------function dydx = mat4ode(x,y,lambda) q = 5; dydx = [ y(2) -(lambda - 2*q*cos(2*x))*y(1) ]; % -----------------------------------------------------------function res = mat4bc(ya,yb,lambda) res = [ ya(2) yb(2) ya(1)-1 ]; % -----------------------------------------------------------function yinit = mat4init(x) yinit = [ cos(4*x) -4*sin(4*x) ]; The differential equation (converted to a first order system) and the boundary conditions are coded as subfunctions mat4ode and mat4bc, respectively. Because unknown parameters are present, these functions must accept three input arguments, even though some of the arguments are not used. The guess structure solinit is formed with bvpinit. An initial guess for the solution is supplied in the form of a function mat4init. We chose y = cos 4x because it satisfies the boundary conditions and has the correct qualitative behavior (the correct number of sign changes). In the call to bvpinit, the third argument (lambda = 15) provides an initial guess for the unknown parameter . After the problem is solved with bvp4c, the field sol.parameters returns the value = 17.097 , and the plot shows the eigenfunction associated with this eigenvalue. 2-179 bvp4c Eigenfunction of Mathieu s equation. 1 0.8 0.6 0.4 solution y 0.2 0 0.2 0.4 0.6 0.8 1 0 0.5 1 1.5 x 2 2.5 3 Algorithms bvp4c is a finite difference code that implements the three-stage Lobatto IIIa formula. This is a collocation formula and the collocation polynomial provides a C1-continuous solution that is fourth order accurate uniformly in [a,b]. Mesh selection and error control are based on the residual of the continuous solution. See Also References @ (function_handle), bvpget, bvpinit, bvpset, deval [1] Shampine, L.F., M.W. Reichelt, and J. Kierzenka, Solving Boundary Value Problems for Ordinary Differential Equations in MATLAB with bvp4c, available at ftp://ftp.mathworks.com/pub/doc/papers/bvp/. 2-180 bvpget Purpose Syntax Description 2bvpget Extract properties from the options structure created with bvpset val = bvpget(options,'name') val = bvpget(options,'name',default) val = bvpget(options,'name') extracts the value of the named property from the structure options, returning an empty matrix if the property value is not specified in options. It is sufficient to type only the leading characters that uniquely identify the property. Case is ignored for property names. [] is a valid options argument. val = bvpget(options,'name',default) extracts the named property as above, but returns val = default if the named property is not specified in options. For example, val = bvpget(opts,'RelTol',1e-4); returns val = 1e-4 if the RelTol is not specified in opts. See Also bvp4c, bvpinit, bvpset, deval 2-181 bvpinit Purpose Syntax 2bvpinit Form the initial guess for bvp4c solinit solinit solinit solinit = = = = bvpinit(x,v) bvpinit(x,v,parameters) bvpinit(sol,[anew bnew]) bvpinit(sol,[anew bnew],parameters) Description solinit = bvpinit(x,v) forms the initial guess for bvp4c in common circumstances. x is a vector that specifies an initial mesh. If you want to solve the boundary value problem (BVP) on [ a, b ] , then specify x(1) as a and x(end) as b . The function bvp4c adapts this mesh to the solution, so often a guess like x = linspace(a,b,10) suffices. However, in difficult cases, you must place mesh points where the solution changes rapidly. The entries of x must be ordered and distinct, so if a < b , then x(1) < x(2) < ... < x(end), and similarly for a > b . v is a guess for the solution. It can be either a vector, or a function: Vector For each component of the solution, bvpinit replicates the corresponding element of the vector as a constant guess across all mesh points. That is, v(i) is a constant guess for the ith component y(i,:) of the solution at all the mesh points in x. Function For a given mesh point, the function must return a vector whose elements are guesses for the corresponding components of the solution. The function must be of the form y = guess(x) where x is a mesh point and y is a vector whose length is the same as the number of components in the solution. For example, if you use @guess, bvpinit calls this function for each mesh point y(:,j) = guess(x(j)). solinit = bvpinit(x,v,parameters) indicates that the BVP involves unknown parameters. Use the vector parameters to provide a guess for all unknown parameters. 2-182 bvpinit solinit is a structure with the following fields. The structure can have any name, but the elds must be named x, y, and parameters. x y parameters Ordered nodes of the initial mesh. Initial guess for the solution with solinit.y(:,i) a guess for the solution at the node solinit.x(i). Optional. A vector that provides an initial guess for unknown parameters. solinit = bvpinit(sol,[anew bnew]) forms an initial guess on the interval [anew bnew] from a solution sol on an interval [ a, b ] . The new interval must be larger than the previous one, so either anew <= a < b <= bnew or anew >= a > b >= bnew. The solution sol is extrapolated to the new interval. If sol contains parameters, they are copied to solinit. solinit = bvpinit(sol,[anew bnew],parameters) forms solinit as described above, but uses parameters as a guess for unknown parameters in solinit. See Also @ (function_handle), bvp4c, bvpget, bvpset, deval 2-183 bvpset Purpose Syntax 2bvpset Create/alter boundary value problem (BVP) options structure options = bvpset('name1',value1,'name2',value2,...) options = bvpset(oldopts'name1',value1,...) options = bvpset(oldopts,newopts) bvpset options = bvpset('name1',value1,'name2',value2,...) creates a structure options in which the named properties have the specified values. Description Any unspecified properties have default values. It is sufficient to type only the leading characters that uniquely identify the property. Case is ignored for property names. options = bvpset(oldopts,'name1',value1,...) alters an existing options structure oldopts. options = bvpset(oldopts,newopts) combines an existing options structure oldopts with a new options structure newopts. Any new properties overwrite corresponding old properties. bvpset with no input arguments displays all property names and their possible values. BVP Properties Property RelTol These properties are available. Description Value Positive scalar {1e-3} A relative tolerance that applies to all components of the residual vector. The computed solution S ( x ) is the exact solution of S ( x) = F ( x, S ( x )) + res ( x ) . On each subinterval of the mesh, the residual res ( x ) satisfies (res(i)/max(abs(F(i)),AbsTol(i)/RelTol)) RelTol An absolue tolerance that applies to all components of the residual vector. Elements of a vector of tolerances apply to corresponding components of the residual vector. AbsTol Positive scalar or vector {1e-6} 2-184 bvpset Property Vectorized Value on | {off} Description Set on to inform bvp4c that you have coded the ODE function F so that F([x1 x2 ...],[y1 y2 ...]) returns [F(x1,y1) F(x2,y2) ...]. That is, your ODE function can pass to the solver a whole array of column vectors at once. This allows the solver to reduce the number of function evaluations, and may signi cantly reduce solution time. Analytic partial derivatives of ODEFUN. For example, when solving y = f ( x, y ), set this property to @FJAC if DFDY = FJAC(X,Y) evaluates the Jacobian of f with respect to y . If the problem involves unknown parameters p , [DFDY,DFDP] = FJAC(X,Y,P) must also return the partial derivative of f with respect to p . Analytic partial derivatives of BCFUN. For example, for boundary conditions bc( ya, yb) = 0 , set this property to @BCJAC if [DBCDYA,DBCDYB] = BCJAC(YA,YB) evaluates the partial derivatives of bc with respect to ya and to yb . If the problem involves unknown parameters p , then [DBCDYA,DBCDYB,DBCDP] = BCJAC(YA,YB,P) must also return the partial derivative of bc with respect to p . Maximum number of mesh points allowed. Display computational cost statistics. FJacobian Function BCJacobian Function Nmax positive integer {floor(1000/n)} on | {off} Stats See Also @ (function_handle), bvp4c, bvpget, bvpinit, deval 2-185 bvpval Purpose 2bvpval Evaluate the numerical solution of a boundary value problem (BVP) using the output of bvp4c Note bvpval is obsolete and will be removed in the future. Please use deval instead. Syntax Description sxint = bvpval(sol,xint) sxint = bvpval(sol,xint) uses sol, the output of bvp4c, to evaluate the solution of a boundary value problem at each element of the vector xint. For each i, sxint(:,i) is the solution corresponding to xint(i). bvp4c, bvpinit, bvpget, bvpset See Also 2-186 calendar Purpose Syntax 2calendar Calendar c = calendar c = calendar(d) c = calendar(y,m) calendar(...) Description c = calendar returns a 6-by-7 matrix containing a calendar for the current month. The calendar runs Sunday (first column) to Saturday. c = calendar(d), where d is a serial date number or a date string, returns a calendar for the specified month. c = calendar(y,m), where y and m are integers, returns a calendar for the specified month of the specified year. calendar(...) displays the calendar on the screen. Examples The command: calendar(1957,10) reveals that the Space Age began on a Friday (on October 4, 1957, when Sputnik 1 was launched). S 0 6 13 20 27 0 M 0 7 14 21 28 0 Tu 1 8 15 22 29 0 Oct 1957 W Th 2 3 9 10 16 17 23 24 30 31 0 0 F 4 11 18 25 0 0 S 5 12 19 26 0 0 See Also datenum 2-187 camdolly Purpose Syntax 2camdolly Move the camera position and target camdolly(dx,dy,dz) camdolly(dx,dy,dz,'targetmode') camdolly(dx,dy,dz,'targetmode','coordsys') camdolly(axes_handle,...) camdolly moves the camera position and the camera target by the specified Description amounts. camdolly(dx,dy,dz) moves the camera position and the camera target by the specified amounts (see Coordinate Systems ). camdolly(dx,dy,dz,'targetmode') The targetmode argument can take on two values that determine how MATLAB moves the camera: movetarget (default) move both the camera and the target fixtarget move only the camera camdolly(dx,dy,dz,'targetmode','coordsys') The coordsys argument can take on three values that determine how MATLAB interprets dx, dy, and dz: Coordinate Systems camera (default) move in the camera s coordinate system. dx moves left/ right, dy moves down/up, and dz moves along the viewing axis. The units are normalized to the scene. For example, setting dx to 1 moves the camera to the right, which pushes the scene to the left edge of the box formed by the axes position rectangle. A negative value moves the scene in the other direction. Setting dz to 0.5 moves the camera to a position halfway between the camera position and the camera target pixels interpret dx and dy as pixel offsets. dz is ignored. data interpret dx, dy, and dz as offesets in axes data coordinates. camdolly(axes_handle,...) operates on the axes identified by the first argument, axes_handle. When you do not specify an axes handle, camdolly operates on the current axes. 2-188 camdolly Remarks camdolly sets the axes CameraPosition and CameraTarget properties, which in turn causes the CameraPositionMode and CameraTargetMode properties to be set to manual. Examples This example moves the camera along the x- and y-axes in a series of steps. surf(peaks) axis vis3d t = 0:pi/20:2*pi; dx = sin(t)./40; dy = cos(t)./40; for i = 1:length(t); camdolly(dx(i),dy(i),0) drawnow end See Also axes, campos, camproj, camtarget, camup, camva The axes properties CameraPosition, CameraTarget, CameraUpVector, CameraViewAngle, Projection See Defining Scenes with Camera Graphics for more information on camera properties. 2-189 camlight Purpose Syntax 2camlight Create or move a light object in camera coordinates camlight headlight camlight right camlight left camlight camlight(az,el) camlight(... style ) camlight(light_handle,...) light_handle = camlight(...) camlight('headlight') creates a light at the camera position. camlight('right') creates a light right and up from camera. camlight('left') creates a light left and up from camera. camlight with no arguments is the same as camlight('right'). camlight(az,el) creates a light at the specified azimuth (az) and elevation (el) with respect to the camera position. The camera target is the center of rotation and az and el are in degrees. camlight(...,'style') The style argument can take on the two values: Description local (default) the light is a point source that radiates from the location in all directions. infinite the light shines in parallel rays. camlight(light_handle,...) uses the light specified in light_handle. light_handle = camlight(...) returns the light s handle. Remarks camlight sets the light object Position and Style properties. A light created with camlight will not track the camera. In order for the light to stay in a constant position relative to the camera, you must call camlight whenever you move the camera. 2-190 camlight Examples This example creates a light positioned to the left of the camera and then repositions the light each time the camera is moved: surf(peaks) axis vis3d h = camlight('left'); for i = 1:20; camorbit(10,0) camlight(h,'left') drawnow; end 2-191 camlookat Purpose Syntax 2camlookat Position the camera to view an object or group of objects camlookat(object_handles) camlookat(axes_handle) camlookat camlookat(object_handles) views the objects identified in the vector object_handles. The vector can contain the handles of axes children. camlookat(axes_handle) views the objects that are children of the axes identified by axes_handle. camlookat views the objects that are in the current axes. Description Remarks camlookat moves the camera position and camera target while preserving the relative view direction and camera view angle. The object (or objects) being viewed roughly fill the axes position rectangle. camlookat sets the axes CameraPosition and CameraTarget properties. Examples This example creates three spheres at different locations and then progressively positions the camera so that each sphere is the object around which the scene is composed: [x y z] = sphere; s1 = surf(x,y,z); hold on s2 = surf(x+3,y,z+3); s3 = surf(x,y,z+6); daspect([1 1 1]) view(30,10) camproj perspective camlookat(gca) % Compose pause(2) camlookat(s1) % Compose pause(2) camlookat(s2) % Compose pause(2) camlookat(s3) % Compose pause(2) camlookat(gca) the scene around the current axes the scene around sphere s1 the scene around sphere s2 the scene around sphere s3 2-192 camlookat See Also campos, camtarget 2-193 camorbit Purpose Syntax 2camorbit Rotate the camera position around the camera target camorbit(dtheta,dphi) camorbit(dtheta,dphi,'coordsys') camorbit(dtheta,dphi,'coordsys','direction') camorbit(axes_handle,...) camorbit(dtheta,dphi) rotates the camera position around the camera target by the amounts specified in dtheta and dphi (both in degrees). dtheta is the horizontal rotation and dphi is the vertical rotation. camorbit(dtheta,dphi,'coordsys') The coordsys argument determines the Description center of rotation. It can take on two values: data (default) rotate the camera around an axis defined by the camera target and the direction (default is the positive z direction). camera rotate the camera about the point defined by the camera target. camorbit(dtheta,dphi,'coordsys','direction') The direction argument, in conjunction with the camera target, defines the axis of rotation for the data coordinate system. Specify direction as a three-element vector containing the x, y, and z-components of the direction or one of the characters, x, y, or z, to indicate [1 0 0], [0 1 0], or [0 0 1] respectively. camorbit(axes_handle,...) operates on the axes identified by the first argument, axes_handle. When you do not specify an axes handle, camorbit operates on the current axes. Examples Compare rotation in the two coordinate systems with these for loops. The first rotates the camera horizontally about a line defined by the camera target point and a direction that is parallel to the y-axis. Visualize this rotation as a cone formed with the camera target at the apex and the camera position forming the base: surf(peaks) axis vis3d for i=1:36 camorbit(10,0,'data',[0 1 0]) drawnow 2-194 camorbit end Rotation in the camera coordinate system orbits the camera around the axes along a circle while keeping the center of a circle at the camera target. surf(peaks) axis vis3d for i=1:36 camorbit(10,0,'camera') drawnow end See Also axes, axis('vis3d'), camdolly, campan, camzoom, camroll 2-195 campan Purpose Syntax 2campan Rotate the camera target around the camera position campan(dtheta,dphi) campan(dtheta,dphi,'coordsys') campan(dtheta,dphi,'coordsys','direction') campan(axes_handle,...) campan(dtheta,dphi) rotates the camera target around the camera position by the amounts specified in dtheta and dphi (both in degrees). dtheta is the horizontal rotation and dphi is the vertical rotation. campan(dtheta,dphi,'coordsys') The coordsys argument determines the center of rotation. It can take on two values: Description data (default) rotate the camera target around an axis defined by the camera position and the direction (default is the positive z direction) camera rotate the camera about the point defined by the camera target. campan(dtheta,dphi,'coordsys','direction') The direction argument, in conjunction with the camera position, defines the axis of rotation for the data coordinate system. Specify direction as a three-element vector containing the x, y, and z-components of the direction or one of the characters, x, y, or z, to indicate [1 0 0], [0 1 0], or [0 0 1] respectively. campan(axes_handle,...) operates on the axes identified by the first argument, axes_handle. When you do not specify an axes handle, campan operates on the current axes. See Also axes, camdolly, camorbit, camtarget, camzoom, camroll 2-196 campos Purpose Syntax 2campos Set or query the camera position campos campos([camera_position]) campos('mode') campos('auto' campos('manual') campos(axes_handle,...) campos with no arguments returns the camera position in the current axes. campos([camera_position]) sets the position of the camera in the current Description axes to the specified value. Specify the position as a three-element vector containing the x-, y-, and z-coordinates of the desired location in the data units of the axes. campos('mode') returns the value of the camera position mode, which can be either auto (the default) or manual. campos('auto') sets the camera position mode to auto. campos('manual') sets the camera position mode to manual. campos(axes_handle,...) performs the set or query on the axes identified by the first argument, axes_handle. When you do not specify an axes handle, campos operates on the current axes. Remarks campos sets or queries values of the axes CameraPosition and CameraPositionMode properties. The camera position is the point in the Cartesian coordinate system of the axes from which you view the scene. Examples This example moves the camera along the x-axis in a series of steps: surf(peaks) axis vis3d off for x = 200:5:200 campos([x,5,10]) drawnow end 2-197 campos See Also axis, camproj, camtarget, camup, camva The axes properties CameraPosition, CameraTarget, CameraUpVector, CameraViewAngle, Projection 2-198 camproj Purpose Syntax 2camproj Set or query the projection type camproj camproj(projection_type) camproj(axes_handle,...) Description The projection type determines whether MATLAB uses a perspective or orthographic projection for 3-D views. camproj with no arguments returns the projection type setting in the current axes. camproj('projection_type') sets the projection type in the current axes to the specified value. Possible values for projection_type are: orthographic and perspective. camproj(axes_handle,...) performs the set or query on the axes identified by the first argument, axes_handle. When you do not specify an axes handle, camproj operates on the current axes. Remarks See Also camproj sets or queries values of the axes object Projection property. campos, camtarget, camup, camva The axes properties CameraPosition, CameraTarget, CameraUpVector, CameraViewAngle, Projection 2-199 camroll Purpose Syntax Description 2camroll Rotate the camera about the view axis camroll(dtheta) camroll(axes_handle,dtheta) camroll(dtheta) rotates the camera around the camera viewing axis by the amounts specified in dtheta (in degrees). The viewing axis is defined by the line passing through the camera position and the camera target. camroll(axes_handle,dtheta) operates on the axes identified by the first argument, axes_handle. When you do not specify an axes handle, camroll operates on the current axes. Remarks See Also camroll set the axes CameraUpVector property and thereby also sets the CameraUpVectorMode property to manual. axes, axis('vis3d'), camdolly, camorbit, camzoom, campan 2-200 camtarget Purpose Syntax 2camtarget Set or query the location of the camera target camtarget camtarget([camera_target]) camtarget('mode') camtarget('auto') camtarget('manual') camtarget(axes_handle,...) Description The camera target is the location in the axes that the camera points to. The camera remains oriented toward this point regardless of its position. camtarget with no arguments returns the location of the camera target in the current axes. camtarget([camera_target]) sets the camera target in the current axes to the specified value. Specify the target as a three-element vector containing the x-, y-, and z-coordinates of the desired location in the data units of the axes. camtarget('mode') returns the value of the camera target mode, which can be either auto (the default) or manual. camtarget('auto') sets the camera target mode to auto. camtarget('manual') sets the camera target mode to manual. camtarget(axes_handle,...) performs the set or query on the axes identified by the first argument, axes_handle. When you do not specify an axes handle, camtarget operates on the current axes. Remarks camtarget sets or queries values of the axes object Cameratarget and CameraTargetMode properties. When the camera target mode is auto, MATLAB positions the camera target at the center of the axes plot box. Examples This example moves the camera position and the camera target along the x-axis in a series of steps: surf(peaks); 2-201 camtarget axis vis3d xp = linspace( 150,40,50); xt = linspace(25,50,50); for i=1:50 campos([xp(i),25,5]); camtarget([xt(i),30,0]) drawnow end See Also axis, camproj, campos, camup, camva The axes properties CameraPosition, CameraTarget, CameraUpVector, CameraViewAngle, Projection 2-202 camup Purpose Syntax 2camup Set or query the camera up vector camup camup([up_vector]) camup('mode') camup('auto') camup('manual') camup(axes_handle,...) Description The camera up vector specifies the direction that is oriented up in the scene. camup with no arguments returns the camera up vector setting in the current axes. camup([up_vector]) sets the up vector in the current axes to the specified value. Specify the up vector as x-, y-, and z-components. See Remarks. camup('mode') returns the current value of the camera up vector mode, which can be either auto (the default) or manual. camup('auto') sets the camera up vector mode to auto. In auto mode, MATLAB uses a value for the up vector of [0 1 0] for 2-D views. This means the z-axis points up. camup('manual') sets the camera up vector mode to manual. In manual mode, MATLAB does not change the value of the camera up vector. camup(axes_handle,...) performs the set or query on the axes identified by the first argument, axes_handle. When you do not specify an axes handle, camup operates on the current axes. Remarks camup sets or queries values of the axes object CameraUpVector and CameraUpVectorMode properties. Specify the camera up vector as the x-, y-, and z-coordinates of a point in the axes coordinate system that forms the directed line segment PQ, where P is the point (0,0,0) and Q is the specified x-, y-, and z-coordinates. This line always points up. The length of the line PQ has no effect on the orientation of the scene. This means a value of [0 0 1] produces the same results as [0 0 25]. 2-203 camup See Also axis, camproj, campos, camtarget, camva The axes properties CameraPosition, CameraTarget, CameraUpVector, CameraViewAngle, Projection 2-204 camva Purpose Syntax 2camva Set or query the camera view angle camva camva(view_angle) camva('mode') camva('auto') camva('manual') camva(axes_handle,...) Description The camera view angle determines the field of view of the camera. Larger angles produce a smaller view of the scene. You can implement zooming by changing the camera view angle. camva with no arguments returns the camera view angle setting in the current axes. camva(view_angle) sets the view angle in the current axes to the specified value. Specify the view angle in degrees. camva('mode') returns the current value of the camera view angle mode, which can be either auto (the default) or manual. See Remarks. camva('auto') sets the camera view angle mode to auto. camva('manual') sets the camera view angle mode to manual. See Remarks. camva(axes_handle,...) performs the set or query on the axes identified by the first argument, axes_handle. When you do not specify an axes handle, camva operates on the current axes. Remarks camva sets or queries values of the axes object CameraViewAngle and CameraViewAngleMode properties. When the camera view angle mode is auto, MATLAB adjusts the camera view angle so that the scene fills the available space in the window. If you move the camera to a different position, MATLAB changes the camera view angle to maintain a view of the scene that fills the available area in the window. 2-205 camva Setting a camera view angle or setting the camera view angle to manual disables MATLAB s stretch-to-fill feature (stretching of the axes to fit the window). This means setting the camera view angle to its current value, camva(camva) can cause a change in the way the graph looks. See the Remarks section of the axes reference page for more information. Examples This example creates two pushbuttons, one that zooms in and another that zooms out. uicontrol('Style','pushbutton',... 'String','Zoom In',... 'Position',[20 20 60 20],... 'Callback','if camva <= 1;return;else;camva(camva-1);end'); uicontrol('Style','pushbutton',... 'String','Zoom Out',... 'Position',[100 20 60 20],... 'Callback','if camva >= 179;return;else;camva(camva+1);end'); Now create a graph to zoom in and out on: surf(peaks); Note the range checking in the callback statements. This keeps the values for the camera view angle in the range, greater than zero and less than 180. See Also axis, camproj, campos, camup, camtarget The axes properties CameraPosition, CameraTarget, CameraUpVector, CameraViewAngle, Projection 2-206 camzoom Purpose Syntax Description 2camzoom Zoom in and out on a scene camzoom(zoom_factor) camzoom(axes_handle,...) camzoom(zoom_factor) zooms in or out on the scene depending on the value specified by zoom_factor. If zoom_factor is greater than 1, the scene appears larger; if zoom_factor is greater than zero and less than 1, the scene appears smaller. camzoom(axes_handle,...) operates on the axes identified by the first argument, axes_handle. When you do not specify an axes handle, camzoom operates on the current axes. Remarks camzoom sets the axes CameraViewAngle property, which in turn causes the CameraViewAngleMode property to be set to manual. Note that setting the CameraViewAngle property disables MATLAB s stretch-to-fill feature (stretching of the axes to fit the window). This may result in a change to the aspect ratio of your graph. See the axes function for more information on this behavior. See Also axes, camdolly, camorbit, campan, camroll, camva 2-207 capture Purpose Syntax 2capture capture is obsolete in Release 11 (5.3). getframe provides the same functionality and supports TrueColor displays by returning TrueColor images. capture capture(h) [X,cmap] = capture(h) capture creates a bitmap copy of the contents of the current figure, including Description any uicontrol graphics objects. It creates a new figure and displays the bitmap copy as an image graphics object in the new figure. capture(h) creates a new figure that contains a copy of the figure identified by h. [X,cmap] = capture(h) returns an image matrix X and a colormap. You display this information using the statements colormap(cmap) image(X) Remarks See Also The resolution of a bitmap copy is less than that obtained with the print command. image, print 2-208 cart2pol Purpose Syntax Description 2cart2pol Transform Cartesian coordinates to polar or cylindrical [THETA,RHO,Z] = cart2pol(X,Y,Z) [THETA,RHO] = cart2pol(X,Y) [THETA,RHO,Z] = cart2pol(X,Y,Z) transforms three-dimensional Cartesian coordinates stored in corresponding elements of arrays X, Y, and Z, into cylindrical coordinates. THETA is a counterclockwise angular displacement in radians from the positive x-axis, RHO is the distance from the origin to a point in the x-y plane, and Z is the height above the x-y plane. Arrays X, Y, and Z must be the same size (or any can be scalar). [THETA,RHO] = cart2pol(X,Y) transforms two-dimensional Cartesian coordinates stored in corresponding elements of arrays X and Y into polar coordinates. Algorithm The mapping from two-dimensional Cartesian coordinates to polar coordinates, and from three-dimensional Cartesian coordinates to cylindrical coordinates is Y Z P P Y z rh o theta X rho theta X Two-Dimensional Mapping theta = atan2(y,x) rho = sqrt(x.^2 + y.^2) Three-Dimensional Mapping theta = atan2(y,x) rho = sqrt(x.^2 + y.^2) z = z See Also cart2sph, pol2cart, sph2cart 2-209 cart2sph Purpose Syntax Description 2cart2sph Transform Cartesian coordinates to spherical [THETA,PHI,R] = cart2sph(X,Y,Z) [THETA,PHI,R] = cart2sph(X,Y,Z) transforms Cartesian coordinates stored in corresponding elements of arrays X, Y, and Z into spherical coordinates. Azimuth THETA and elevation PHI are angular displacements in radians measured from the positive x-axis, and the x-y plane, respectively; and R is the distance from the origin to a point. Arrays X, Y, and Z must be the same size. Algorithm The mapping from three-dimensional Cartesian coordinates to spherical coordinates is Z P r phi th et a Y theta = atan2(y,x) phi = atan2(z, sqrt(x.^2 + y.^2)) r = sqrt(x.^2+y.^2+z.^2) X See Also cart2pol, pol2cart, sph2cart 2-210 case Purpose Description 2case Case switch case is part of the switch statement syntax, which allows for conditional execution. A particular case consists of the case statement itself, followed by a case expression, and one or more statements. A case is executed only if its associated case expression (case_expr) is the first to match the switch expression (switch_expr). Examples The general form of the switch statement is: switch switch_expr case case_expr statement,...,statement case {case_expr1,case_expr2,case_expr3,...} statement,...,statement ... otherwise statement,...,statement end See Also switch 2-211 cat Purpose Syntax Description 2cat Concatenate arrays C = cat(dim,A,B) C = cat(dim,A1,A2,A3,A4...) C = cat(dim,A,B) concatenates the arrays A and B along dim. C = cat(dim,A1,A2,A3,A4,...) concatenates all the input arrays (A1, A2, A3, A4, and so on) along dim. cat(2,A,B) is the same as [A,B] and cat(1,A,B) is the same as [A;B]. Remarks When used with comma separated list syntax, cat(dim,C{:}) or cat(dim,C.field) is a convenient way to concatenate a cell or structure array containing numeric matrices into a single matrix. Given, A = 1 3 2 4 B = 5 7 6 8 Examples concatenating along different dimensions produces: 1 3 5 7 2 4 6 8 5 7 1 3 2 4 6 8 1 3 2 4 5 7 6 8 C = cat(1,A,B) C = cat(2,A,B) C = cat(3,A,B) The commands A = magic(3); B = pascal(3); C = cat(4,A,B); produce a 3-by-3-by-1-by-2 array. See Also num2cell The special character [] 2-212 catch Purpose Description 2catch Begin catch 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 end, eval, evalin, try 2-213 caxis Purpose Syntax 2caxis Color axis scaling caxis([cmin cmax]) caxis auto caxis manual caxis(caxis) v = caxis caxis(axes_handle,...) caxis controls the mapping of data values to the colormap. It affects any surfaces, patches, and images with indexed CData and CDataMapping set to scaled. It does not affect surfaces, patches, or images with true color CData or with CDataMapping set to direct. caxis([cmin cmax]) sets the color limits to specified minimum and maximum values. Data values less than cmin or greater than cmax map to cmin and cmax, respectively. Values between cmin and cmax linearly map to the current Description colormap. caxis auto lets MATLAB compute the color limits automatically using the minimum and maximum data values. This is MATLAB s default behavior. Color values set to Inf map to the maximum color, and values set to Inf map to the minimum color. Faces or edges with color values set to NaN are not drawn. caxis manual and caxis(caxis) freeze the color axis scaling at the current limits. This enables subsequent plots to use the same limits when hold is on. v = caxis returns a two-element row vector containing the [cmin cmax] currently in use. caxis(axes_handle,...) uses the axes specified by axes_handle instead of the current axes. Remarks caxis changes the CLim and CLimMode properties of axes graphics objects. How Color Axis Scaling Works Surface, patch, and image graphics objects having indexed CData and CDataMapping set to scaled, map CData values to colors in the figure colormap 2-214 caxis each time they render. CData values equal to or less than cmin map to the first color value in the colormap, and CData values equal to or greater than cmax map to the last color value in the colormap. MATLAB performs the following linear transformation on the intermediate values (referred to as C below) to map them to an entry in the colormap (whose length is m, and whose row index is referred to as index below). index = fix((C cmin)/(cmax cmin) m)+1 Examples Create (X,Y,Z) data for a sphere and view the data as a surface. [X,Y,Z] = sphere; C = Z; surf(X,Y,Z,C) Values of C have the range [ 1 1]. Values of C near 1 are assigned the lowest values in the colormap; values of C near 1 are assigned the highest values in the colormap. To map the top half of the surface to the highest value in the color table, use caxis([ 1 0]) To use only the bottom half of the color table, enter caxis([ 1 3]) which maps the lowest CData values to the bottom of the colormap, and the highest values to the middle of the colormap (by specifying a cmax whose value is equal to cmin plus twice the range of the CData). The command caxis auto resets axis scaling back to auto-ranging and you see all the colors in the surface. In this case, entering caxis returns [ 1 1] 2-215 caxis Adjusting the color axis can be useful when using images with scaled color data. For example, load the image data and colormap for Cape Cod, Massachusetts. load cape This command loads the images data X and the image s colormap map into the workspace. Now display the image with CDataMapping set to scaled and install the image s colormap. image(X,'CDataMapping','scaled') colormap(map) MATLAB sets the color limits to span the range of the image data, which is 1 to 192: caxis ans = 1 192 2-216 caxis The blue color of the ocean is the first color in the colormap and is mapped to the lowest data value (1). You can effectively move sealevel by changing the lower color limit value. For example, Caxis = [1 192] 50 100 150 200 250 300 100 200 300 50 100 150 200 250 300 100 200 300 Caxis = [3 192] Caxis = [5 192] 50 100 150 200 250 300 100 200 300 50 100 150 200 250 300 100 Caxis = [6 192] 200 300 See Also axes, axis, colormap, get, mesh, pcolor, set, surf The CLim and CLimMode properties of axes graphics objects. The Colormap property of figure graphics objects. Axes Color Limits cd 2-217 Purpose Graphical Interface Syntax 2cd Change working directory As an alternative to the cd function, use the Current Directory field in the MATLAB desktop toolbar. cd w = cd cd('directory') cd('..') cd directory or cd .. cd prints out the current working directory. w = cd assigns the current working directory to w. cd('directory') sets the current working directory to directory. Use the full pathname for directory. On UNIX platforms, the character ~ is interpreted as the user s root directory. cd('..') changes the current working directory to the directory above it. cd directory or cd .. is the unquoted form of the syntax. Description Examples On UNIX cd('/usr/local/matlab/toolbox/demos') changes the current working directory to demos. On Windows cd('C:\TOOLBOX\MATLAB\DEMOS') changes the current working directory to DEMOS. Then typing cd .. changes the current working directory to MATLAB. See Also dir, path, pwd, what 2-218 cdf2rdf Purpose Syntax Description 2cdf2rdf Convert complex diagonal form to real block diagonal form [V,D] = cdf2rdf(V,D) If the eigensystem [V,D] = eig(X) has complex eigenvalues appearing in complex-conjugate pairs, cdf2rdf transforms the system so D is in real diagonal form, with 2-by-2 real blocks along the diagonal replacing the complex pairs originally there. The eigenvectors are transformed so that X = V*D/V continues to hold. The individual columns of V are no longer eigenvectors, but each pair of vectors associated with a 2-by-2 block in D spans the corresponding invariant vectors. Examples The matrix X = 1 0 0 2 4 -5 3 5 4 has a pair of complex eigenvalues. [V,D] = eig(X) V = 1.0000 0 0 D = 1.0000 0 0 0 4.0000 + 5.0000i 0 0 0 4.0000 - 5.0000i -0.0191 - 0.4002i 0 - 0.6479i 0.6479 -0.0191 + 0.4002i 0 + 0.6479i 0.6479 Converting this to real block diagonal form produces [V,D] = cdf2rdf(V,D) 2-219 cdf2rdf V = 1.0000 0 0 D = 1.0000 0 0 0 4.0000 -5.0000 0 5.0000 4.0000 -0.0191 0 0.6479 -0.4002 -0.6479 0 Algorithm See Also The real diagonal form for the eigenvalues is obtained from the complex form using a specially constructed similarity transformation. eig, rsf2csf 2-220 cdfinfo Purpose Syntax Description 2cdfinfo Return details about a CDF file info = cdfinfo(file) info = cdfinfo(file) returns information about the Common Data Format (CDF) file specified in the string, file. The function returns a structure, info, that contains the fields shown in the following table. Field FileModDate Filename FileSettings Description Return Type Date the le was last modi ed Name of the le Library settings used to create the le Size of the le, in bytes File format (CDF) Version of the CDF library used to create the le Global metadata Filenames containing the CDF le s data, if it is a multi le CDF Metadata for the variables Details about the variables in the le String String Structure array Double String String Structure array Cell array FileSize Format FormatVersion GlobalAttributes Subfiles VariableAttributes Variables Structure array Cell array The GlobalAttributes and VariableAttributes Fields GlobalAttributes and VariableAttributes are structure arrays that each contain one field for each global or variable attribute respectively. The name of the field corresponds to the name of an attribute. The data in that field, contained in a cell array, represents the entry values for that attribute. 2-221 cdfinfo For VariableAttributes, the attribute data resides in an N-by-2 cell array, where N is the number of variables. The first column of this cell array contains the variable names associated with the entries. The second column contains the entry values. Note Attribute names may not match the names of the attributes in the CDF le exactly. Because attribute names can contain characters that are illegal in MATLAB eld names, they may be translated into legal eld names. Illegal characters that appear at the beginning of attributes are removed; other illegal characters are replaced with underscores ('_'). If an attribute s name is modi ed, the attribute s internal number is appended to the end of the eld name. For example, Variable%Attribute might become Variable_Attribute_013. The Variables Field The Variables field of the returned info structure is an N-by-6 cell array, where N is the number of variables. The six columns of the cell array contain the following information. Column No. Description Return Type 1 2 3 4 5 6 Name of the variable Dimensions of the variable, as returned by the size function Number of records assigned for the variable Data type of the variable, as stored in the CDF le Record and dimension variance settings for the variable Sparsity of the variable s records String Double array Double String String String 2-222 cdfinfo Column 5 - Record and Dimension Variance This is a string indicating either true or false for one or more types of variance in the variable s values. The single T or F to the left of the slash designates whether values vary by record. The zero or more T or F letters to the right of the slash designate whether values vary at each dimension. Here are some examples. T/ F/T T/TFF for a scalar variable for a one-dimensional variable for a three-dimensional variable Column 6 - Record Sparsity This is a string holding one of three possible values: 'Full' 'Sparse (padded)' 'Sparse (nearest)' Examples info = cdfinfo('example.cdf') info = Filename: 'example.cdf' FileModDate: '29-Jun-1995 05:51:58' FileSize: 230513 Format: 'CDF' FormatVersion: '2.4.8' FileSettings: [1x1 struct] Subfiles: {} Variables: {7x6 cell} GlobalAttributes: [1x1 struct] VariableAttributes: [1x1 struct] info.Variables ans = 'L_gse' [1x2 double] 'Status%C1' [1x2 double] 'B_gse%C1' [1x2 double] 'B_nsigma%C1' [1x2 double] [ 1] [7493] [7493] [7493] 'char' 'F/T' 'uint8' 'T/T' 'single' 'T/T' 'single' 'T/' 'Full' 'Full' 'Full' 'Full' See Also cdfread 2-223 cdfread Purpose Syntax 2cdfread Read data from a CDF file data = data = data = data = [data, cdfread(file) cdfread(file, 'records', recnum, ...) cdfread(file, 'variables', varnames, ...) cdfread(file, 'slices', dimensionvalues, ...) inf0] = cdfread(file, ...) Description data = cdfread(file) reads all of the variables from each record of the Common Data Format (CDF) file specified in the string, file. The function returns a cell array, in which each row contains a record and each column represents a variable. data = cdfread(file, 'records', recnums, ...) reads only those records specified in the vector, recnums. The record numbers are zero-based. The function returns a cell array having length(recnums) number of rows and as many columns as there are variables. data = cdfread(file, 'variables', varnames, ...) reads only those variables specified in the 1-by-N or N-by-1 cell array of strings, varnames. Data is returned in a cell array having length(varnames) number of columns and a row for each record requested. data = cdfread(file, 'slices', dimensionvalues, ...) reads specific values from the records of one variable in the CDF file. The N-by-3 matrix, dimensionvalues, indicates which records are to be read by specifying start, interval, and count parameters for each of the N dimensions of the variable. The start parameter is zero-based. The number of rows in dimensionvalues must be less than or equal to the number dimensions of the variable. Unspecified rows default to [0 1 M], where M is the total number of values in a record. This causes cdfread to read every value from those dimensions. Because you can read just one variable at a time, you must also include a 'variables' parameter with this syntax. [data, inf0] = cdfread(file, ...) also returns details about the CDF file in the info structure. 2-224 cdfread Examples Read all of the data from the file. data = cdfread('example.cdf'); Read just the data from variable 'Time'. data = cdfread('example.cdf', 'Variable', {'Time'}); Read the first value in the first dimension, the second value in the second dimension, the first and third values in the third dimension, and all values in the remaining dimension of the variable 'multidimensional'. data = cdfread('example.cdf', 'Variable', ... {'multidimensional'}, 'Slices', [0 1 1; 1 1 1; 0 2 2]); This is similar to reading the whole variable into 'data', and then using the MATLAB command data{1}(1, 2, [1 3], :) See Also cdfinfo 2-225 ceil Purpose Syntax Description 2ceil Round toward infinity B = ceil(A) B = ceil(A) rounds the elements of A to the nearest integers greater than or equal to A. For complex A, the imaginary and real parts are rounded independently. Examples a = [-1.9, -0.2, 3.4, 5.6, 7, 2.4+3.6i] a = Columns 1 through 4 -1.9000 -0.2000 3.4000 5.6000 Columns 5 through 6 7.0000 2.4000 + 3.6000i ceil(a) ans = Columns 1 through 4 -1.0000 0 4.0000 6.0000 Columns 5 through 6 7.0000 3.0000 + 4.0000i See Also fix, floor, round 2-226 cell Purpose Syntax 2cell Create cell array c c c c c = = = = = cell(n) cell(m,n) or c = cell([m n]) cell(m,n,p,...) or c = cell([m n p ...]) cell(size(A)) cell(javaobj) Description c = cell(n) creates an n-by-n cell array of empty matrices. An error message appears if n is not a scalar. c = cell(m,n) or c = cell([m,n]) creates an m-by-n cell array of empty matrices. Arguments m and n must be scalars. c = cell(m,n,p,...) or c = cell([m n p ...]) creates an m-by-n-by-p-... cell array of empty matrices. Arguments m, n, p,... must be scalars. c = cell(size(A)) creates a cell array the same size as A containing all empty matrices. c = cell(javaobj) converts a Java array or Java object, javaobj, into a MATLAB cell array. Elements of the resulting cell array will be of the MATLAB type (if any) closest to the Java array elements or Java object. Examples This example creates a cell array that is the same size as another array, A. A = ones(2,2) A = 1 1 1 1 c = cell(size(A)) c = [] [] [] [] The next example converts an array of java.lang.String objects into a MATLAB cell array. 2-227 cell strArray = java_array('java.lang.String',3); strArray(1) = java.lang.String('one'); strArray(2) = java.lang.String('two'); strArray(3) = java.lang.String('three'); cellArray = cell(strArray) cellArray = 'one' 'two' 'three' See Also num2cell, ones, rand, randn, zeros 2-228 cell2struct Purpose Syntax Description 2cell2struct Convert cell array to structure array s = cell2struct(c,fields,dim) s = cell2struct(c,fields,dim) creates a structure array, s, from the information contained within cell array, c. The fields argument specifies field names for the structure array. fields can be a character array or a cell array of strings. The dim argument controls which axis of the cell array is to be used in creating the structure array. The length of c along the specified dimension must match the number of fields named in fields. In other words, the following must be true. size(c,dim) == length(fields) size(c,dim) == size(fields,1) % if fields is a cell array % if fields is a char array Examples The cell array, c, in this example contains information on trees. The three columns of the array indicate the common name, genus, and average height of a tree. c = {'birch','betula',65; c = 'birch' 'betula' 'maple' 'acer' 'maple','acer',50} [65] [50] To put this information into a structure with the fields name, genus, and height, use cell2struct along the second dimension of the 2-by-3 cell array. fields = {'name', 'genus', 'height'}; s = cell2struct(c, fields, 2); This yields the following 2-by-1 structure array. s(1) ans = name: 'birch' genus: 'betula' height: 65 s(2) ans = name: 'maple' genus: 'acer' height: 50 See Also fieldnames, struct2cell 2-229 celldisp Purpose Syntax Description 2celldisp Display cell array contents. celldisp(C) celldisp(C,name) celldisp(C) recursively displays the contents of a cell array. celldisp(C,name) uses the string name for the display instead of the name of the first input (or ans). Example Use celldisp to display the contents of a 2-by-3 cell array: C = {[1 2] 'Tony' 3+4i; [1 2;3 4] -5 'abc'}; celldisp(C) C{1,1} = 1 C{2,1} = 1 3 C{1,2} = Tony C{2,2} = -5 C{1,3} = 3.0000+ 4.0000i C{2,3} = abc 2 2 4 See Also cellplot 2-230 cellfun Purpose Syntax 2cellfun Apply a function to each element in a cell array D = cellfun('fname',C) D = cellfun('size',C,k) D = cellfun('isclass',C,classname) D = cellfun('fname',C) applies the function fname to the elements of the cell array C and returns the results in the double array D. Each element of D contains the value returned by fname for the corresponding element in C. The output array D is the same size as the cell array C. Description These functions are supported: Function isempty islogical isreal length ndims prodofsize Return Value true for an empty cell element true for a logical cell element true for a real cell element Length of the cell element Number of dimensions of the cell element Number of elements in the cell element D = cellfun('size',C,k) returns the size along the k-th dimension of each element of C. D = cellfun('isclass',C,'classname') returns true for each element of C that matches classname. This function syntax returns false for objects that are a subclass of classname. Limitations Example If the cell array contains objects, cellfun does not call overloaded versions of the function fname. Consider this 2-by-3 cell array: C{1,1} = [1 2; 4 5]; C{1,2} = 'Name'; 2-231 cellfun C{1,3} C{2,1} C{2,2} C{2,3} = = = = pi; 2 + 4i; 7; magic(3); cellfun returns a 2-by-3 double array: D = cellfun('isreal',C) D = 1 0 1 1 1 1 len = cellfun('length',C) len = 2 1 4 1 1 3 isdbl = cellfun('isclass',C,'double') isdbl = 1 1 0 1 1 1 See Also isempty, islogical, isreal, length, ndims, size 2-232 cellplot Purpose Syntax 2cellplot Graphically display the structure of cell arrays cellplot(c) cellplot(c,'legend') handles = cellplot(...) cellplot(c) displays a figure window that graphically represents the contents of c. Filled rectangles represent elements of vectors and arrays, while Description scalars and short text strings are displayed as text. cellplot(c,'legend') also puts a legend next to the plot. handles = cellplot(c) displays a figure window and returns a vector of surface handles. Limitations Examples The cellplot function can display only two-dimensional cell arrays. Consider a 2-by-2 cell array containing a matrix, a vector, and two text strings: c{1,1} c{1,2} c{2,1} c{2,2} = = = = '2-by-2'; 'eigenvalues of eye(2)'; eye(2); eig(eye(2)); The command cellplot(c) produces: 2 by 2 2-233 cellstr Purpose Syntax Description Examples 2cellstr Create cell array of strings from character array c = cellstr(S) c = cellstr(S) places each row of the character array S into separate cells of c. Use the char function to convert back to a string matrix. Given the string matrix S=['abc ';'defg';'hi S = abc defg hi whos S Name S '] Size 3x4 Bytes 24 Class char array The following command returns a 3-by-1 cell array. c = cellstr(S) c = 'abc' 'defg' 'hi' whos c Name c Size 3x1 Bytes 294 Class cell array See Also iscellstr, strings 2-234 cgs Purpose Syntax 2cgs Conjugate Gradients Squared method x = cgs(A,b) cgs(A,b,tol) cgs(A,b,tol,maxit) cgs(A,b,tol,maxit,M) cgs(A,b,tol,maxit,M1,M2) cgs(A,b,tol,maxit,M1,M2,x0) cgs(afun,b,tol,maxit,m1fun,m2fun,x0,p1,p2,...) [x,flag] = cgs(A,b,...) [x,flag,relres] = cgs(A,b,...) [x,flag,relres,iter] = cgs(A,b,...) [x,flag,relres,iter,resvec] = cgs(A,b,...) x = cgs(A,b) attempts to solve the system of linear equations A*x = b for x. The n-by-n coefficient matrix A must be square and the column vector b must have length n. A can be a function afun such that afun(x) returns A*x. Description If cgs converges, a message to that effect is displayed. If cgs fails to converge after the maximum number of iterations or halts for any reason, a warning message is printed displaying the relative residual norm(b-A*x)/norm(b) and the iteration number at which the method stopped or failed. cgs(A,b,tol) specifies the tolerance of the method, tol. If tol is [], then cgs uses the default, 1e-6. cgs(A,b,tol,maxit) specifies the maximum number of iterations, maxit. If maxit is [] then cgs uses the default, min(n,20). cgs(A,b,tol,maxit,M) and cgs(A,b,tol,maxit,M1,M2) use the preconditioner M or M = M1*M2 and effectively solve the system inv(M)*A*x = inv(M)*b for x. If M is [] then cgs applies no preconditioner. M can be a function that returns M\x. cgs(A,b,tol,maxit,M1,M2,x0) specifies the initial guess x0. If x0 is [], then cgs uses the default, an all-zero vector. 2-235 cgs cgs(afun,b,tol,maxit,m1fun,m2fun,x0,p1,p2,...) passes parameters p1,p2,... to functions afun(x,p1,p2,...), m1fun(x,p1,p2,...), and m2fun(x,p1,p2,...) [x,flag] = cgs(A,b,...) returns a solution x and a flag that describes the convergence of cgs. Flag 0 Convergence cgs converged to the desired tolerance tol within maxit iterations. 1 2 3 4 cgs iterated maxit times but did not converge. Preconditioner M was ill-conditioned. cgs stagnated. (Two consecutive iterates were the same.) One of the scalar quantities calculated during cgs became too small or too large to continue computing. Whenever flag is not 0, the solution x returned is that with minimal norm residual computed over all the iterations. No messages are displayed if the flag output is specified. [x,flag,relres] = cgs(A,b,...) also returns the relative residual norm(b-A*x)/norm(b). If flag is 0, then relres <= tol. [x,flag,relres,iter] = cgs(A,b,...) also returns the iteration number at which x was computed, where 0 <= iter <= maxit. [x,flag,relres,iter,resvec] = cgs(A,b,...) also returns a vector of the residual norms at each iteration, including norm(b-A*x0). Examples Example 1. A = gallery('wilk',21); b = sum(A,2); tol = 1e-12; maxit = 15; M1 = diag([10:-1:1 1 1:10]); x = cgs(A,b,tol,maxit,M1,[],[]); 2-236 cgs Alternatively, use this matrix-vector product function function y = afun(x,n) y = [ 0; x(1:n-1)] + [((n-1)/2:-1:0)'; (1:(n-1)/2)'] .*x + [x(2:n); 0 ]; and this preconditioner backsolve function function y = mfun(r,n) y = r ./ [((n-1)/2:-1:1)'; 1; (1:(n-1)/2)']; as inputs to cgs. x1 = cgs(@afun,b,tol,maxit,@mfun,[],[],21); Note that both afun and mfun must accept cgs s extra input n=21. Example 2. load west0479 A = west0479 b = sum(A,2) [x,flag] = cgs(A,b) flag is 1 because cgs does not converge to the default tolerance 1e-6 within the default 20 iterations. [L1,U1] = luinc(A,1e-5) [x1,flag1] = cgs(A,b,1e-6,20,L1,U1) flag1 is 2 because the upper triangular U1 has a zero on its diagonal, and cgs fails in the first iteration when it tries to solve a system such as U1*y = r for y with backslash. [L2,U2] = luinc(A,1e-6) [x2,flag2,relres2,iter2,resvec2] = cgs(A,b,1e-15,10,L2,U2) flag2 is 0 because cgs converges to the tolerance of 6.344e-16 (the value of relres2) at the fifth iteration (the value of iter2) when preconditioned by the incomplete LU factorization with a drop tolerance of 1e-6. resvec2(1) = norm(b) and resvec2(6) = norm(b-A*x2). You can follow the 2-237 cgs progress of cgs by plotting the relative residuals at each iteration starting from the initial estimate (iterate number 0) with semilogy(0:iter2,resvec2/norm(b),'-o') xlabel('iteration number') ylabel('relative residual') 10 0 10 2 10 4 10 relative residual 6 10 8 10 10 10 12 10 14 10 16 0 0.5 1 1.5 2 2.5 3 iteration number 3.5 4 4.5 5 See Also bicg, bicgstab, gmres, lsqr, luinc, minres, pcg, qmr, symmlq @ (function handle), \ (backslash) References [1] Barrett, R., M. Berry, T. F. Chan, et al., Templates for the Solution of Linear Systems: Building Blocks for Iterative Methods, SIAM, Philadelphia, 1994. [2] Sonneveld, Peter, CGS: A fast Lanczos-type solver for nonsymmetric linear systems , SIAM J. Sci. Stat. Comput., January 1989, Vol. 10, No. 1, pp. 36-52. 2-238 char Purpose Syntax 2char Create character array (string) S = char(X) S = char(C) S = char(t1,t2,t3...) S = char(X) converts the array X that contains positive integers representing character codes into a MATLAB character array (the first 127 codes are ASCII). The actual characters displayed depend on the character set encoding for a given font. The result for any elements of X outside the range from 0 to 65535 is not defined (and may vary from platform to platform). Use double to convert a character array into its numeric codes. S = char(C) when C is a cell array of strings, places each element of C into the rows of the character array s. Use cellstr to convert back. S = char(t1,t2,t3,..) forms the character array S containing the text strings T1,T2,T3,... as rows, automatically padding each string with blanks to form a valid matrix. Each text parameter, Ti, can itself be a character array. Description This allows the creation of arbitrarily large character arrays. Empty strings are significant. Remarks Ordinarily, the elements of A are integers in the range 32:127, which are the printable ASCII characters, or in the range 0:255, which are all 8-bit values. For noninteger values, or values outside the range 0:255, the characters printed are determined by fix(rem(A,256)). To print a 3-by-32 display of the printable ASCII characters: ascii ascii ! # @ A B ' a b = = $ C c char(reshape(32:127,32,3)') % & ' ( ) + , - . / 0 1 2 3 4 5 6 7 8 9 : ; < = > ? D E F G H I J K L M N O P Q R S T U V W X Y Z [ \ ] ^ _ d e f g h i j k l m n o p q r s t u v w x y z { | } ~ Examples 2-239 char See Also cellstr, double, get, set, strings, strvcat, text 2-240 checkin Purpose Graphical Interface Syntax 2checkin Check file into source control system As an alternative to the checkin function, use Source Control Check In in the Editor, Simulink, or Stateflow File menu. checkin('filename','comments','string') checkin({'filename1','filename2','filename3', ...},'comments', 'string') checkin('filename','option','value', ...) checkin('filename','comments','string') checks in the file named filename to the source control system. Use the full pathname for the filename. Description You must save the file before checking it in. The file can be open or closed when you use checkin. The string argument is a MATLAB string containing check-in comments for the source control system. You must supply the comments argument and 'string'. checkin({'filename1','filename2','filename3', ...},'comments', 'string') checks in the files named filename1 through filenamen to the source control system. Use the full pathnames for the files. Additional arguments apply to all files checked in. checkin('filename','option','value', ...) provides additional checkin options. The option and value arguments are shown in the table below. option Argument 'force' Purpose value Argument 'on' 'off' (default) When set to on, filename is checked in even if the file has not changed since it was checked out. The default value for force is off. When set to on, filename remains checked out. Comments are submitted. The default value for lock is off. 'lock' 'on' 'off' (default) You can check in a file that you checked out in a previous MATLAB session or that you checked out directly from your source control system. 2-241 checkin Examples Example 1 - Check in a File with Comments Typing checkin('/matlab/mymfiles/clock.m','comments','Adjustment for Y2K') checks in the file /matlab/mymfiles/clock.m to the source control system with the comment Adjustment for Y2K. Example 2 - Check in Multiple Files with Comments Typing checkin({'/matlab/mymfiles/clock.m', ... '/matlab/mymfiles/calendar.m'},'comments','Adjustment for Y2K') checks two files into the source control system using the same comment for each. Example 3 - Check a File in and Keep It Checked out Typing checkin('/matlab/mymfiles/clock.m','comments','Adjustment for Y2K','lock','on') checks the file /matlab/mymfiles/clock.m into the source control system and keeps the file checked out. See Also checkout, cmopts, undocheckout 2-242 checkout Purpose Graphical Interface Syntax 2checkout Check file out of source control system As an alternative to the checkout function, use Source Control Check Out in the Editor, Simulink, or Stateflow File menu. checkout('filename') checkout({'filename1','filename2','filename3', ...}) checkout('filename','option','value', ...) checkout('filename') checks out the file named filename from the source control system. filename must be the full pathname for the file. The file can be open or closed when you use checkout. checkout({'filename1','filename2','filename3', ...}) checks out the files named filename1 through filenamen from the source control system. Use Description the full pathnames for the files. Additional arguments apply to all files checked out. checkout('filename','option','value', ...) provides additional checkout options. The option and value arguments are shown in the following table. 2-243 checkout option Argument 'force' Purpose value Argument 'on' 'off' (default) When set to on, the checkout is forced, even if you already have the le checked out. This is effectively an undocheckout followed by a checkout. When force is set to off, you can t check out the le if you already have it checked out. When set to on, the checkout gets the le, allows you to write to it, and locks the le so that access to the le for others is read only. When set to off, the checkout gets a read-only version of the le, allowing another user to check out the le for updating. With lock set to off, you don t have to check in a le after checking it out. Checks out the speci ed revision of the le. 'lock' 'on' (default) 'off' 'revision' 'version_num' If you end the MATLAB session, the file remains checked out. You can check in the file from within MATLAB during a later session, or directly from your source control system. Examples Example 1 - Check out a File Typing checkout('/matlab/mymfiles/clock.m') checks out the file /matlab/mymfiles/clock.m from the source control system. 2-244 checkout Example 2 - Check out Multiple Files Typing checkout({'/matlab/mymfiles/clock.m',... '/matlab/mymfiles/calendar.m'}) checks out /matlab/mymfiles/clock.m and /matlab/mymfiles/calendar.m from the source control system. Example 3 - Force a Checkout, Even If File Is Already Checked out Typing checkout('/matlab/mymfiles/clock.m','force','on') checks out /matlab/mymfiles/clock.m even if clock.m is already checked out to you. Example 4 - Check out Specified Revision of File Typing checkout('/matlab/mymfiles/clock.m','revision','1.1') checks out revision 1.1 of clock.m . See Also checkin, cmopts, undocheckout 2-245 chol Purpose Syntax Description 2chol Cholesky factorization R = chol(X) [R,p] = chol(X) The chol function uses only the diagonal and upper triangle of X. The lower triangular is assumed to be the (complex conjugate) transpose of the upper. That is, X is Hermitian. R = chol(X), where X is positive definite produces an upper triangular R so that R'*R = X. If X is not positive definite, an error message is printed. [R,p] = chol(X), with two output arguments, never produces an error message. If X is positive definite, then p is 0 and R is the same as above. If X is not positive definite, then p is a positive integer and R is an upper triangular matrix of order q = p-1 so that R'*R = X(1:q,1:q). Examples The binomial coefficients arranged in a symmetric array create an interesting positive definite matrix. n = 5; X = pascal(n) X = 1 1 1 1 2 3 1 3 6 1 4 10 1 5 15 1 4 10 20 35 1 5 15 35 70 It is interesting because its Cholesky factor consists of the same coefficients, arranged in an upper triangular matrix. R = chol(X) R = 1 1 0 1 0 0 0 0 0 0 1 2 1 0 0 1 3 3 1 0 1 4 6 4 1 2-246 chol Destroy the positive definiteness (and actually make the matrix singular) by subtracting 1 from the last element. X(n,n) = X(n,n)-1 X = 1 1 1 1 1 1 2 3 4 5 1 3 6 10 15 1 4 10 20 35 1 5 15 35 69 Now an attempt to find the Cholesky factorization fails. Algorithm References chol uses the the LAPACK subroutines DPOTRF (real) and ZPOTRF (complex). [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. cholinc, cholupdate See Also 2-247 cholinc Purpose Syntax 2cholinc Sparse incomplete Cholesky and Cholesky-Infinity factorizations R = cholinc(X,droptol) R = cholinc(X,options) R = cholinc(X,'0') [R,p] = cholinc(X,'0') R = cholinc(X,'inf') cholinc produces two different kinds of incomplete Cholesky factorizations: Description the drop tolerance and the 0 level of fill-in factorizations. These factors may be useful as preconditioners for a symmetric positive definite system of linear equations being solved by an iterative method such as pcg (Preconditioned Conjugate Gradients). cholinc works only for sparse matrices. R = cholinc(X,droptol) performs the incomplete Cholesky factorization of X, with drop tolerance droptol. R = cholinc(X,options) allows additional options to the incomplete Cholesky factorization. options is a structure with up to three fields: droptol michol rdiag Drop tolerance of the incomplete factorization Modified incomplete Cholesky Replace zeros on the diagonal of R Only the fields of interest need to be set. droptol is a non-negative scalar used as the drop tolerance for the incomplete Cholesky factorization. This factorization is computed by performing the incomplete LU factorization with the pivot threshold option set to 0 (which forces diagonal pivoting) and then scaling the rows of the incomplete upper triangular factor, U, by the square root of the diagonal entries in that column. Since the nonzero entries U(i,j) are bounded below by droptol*norm(X(:,j)) (see luinc), the nonzero entries R(i,j) are bounded below by the local drop tolerance droptol*norm(X(:,j))/R(i,i). Setting droptol = 0 produces the complete Cholesky factorization, which is the default. 2-248 cholinc michol stands for modified incomplete Cholesky factorization. Its value is either 0 (unmodified, the default) or 1 (modified). This performs the modified incomplete LU factorization of X and scales the returned upper triangular factor as described above. rdiag is either 0 or 1. If it is 1, any zero diagonal entries of the upper triangular factor R are replaced by the square root of the local drop tolerance in an attempt to avoid a singular factor. The default is 0. R = cholinc(X,'0') produces the incomplete Cholesky factor of a real sparse matrix that is symmetric and positive definite using no fill-in. The upper triangular R has the same sparsity pattern as triu(X), although R may be zero in some positions where X is nonzero due to cancellation. The lower triangle of X is assumed to be the transpose of the upper. Note that the positive definiteness of X does not guarantee the existence of a factor with the required sparsity. An error message results if the factorization is not possible. If the factorization is successful, R'*R agrees with X over its sparsity pattern. [R,p] = cholinc(X,'0') with two output arguments, never produces an error message. If R exists, p is 0. If R does not exist, then p is a positive integer and R is an upper triangular matrix of size q-by-n where q = p-1. In this latter case, the sparsity pattern of R is that of the q-by-n upper triangle of X. R'*R agrees with X over the sparsity pattern of its first q rows and first q columns. R = cholinc(X,'inf') produces the Cholesky-Infinity factorization. This factorization is based on the Cholesky factorization, and additionally handles real positive semi-definite matrices. It may be useful for finding a solution to systems which arise in interior-point methods. When a zero pivot is encountered in the ordinary Cholesky factorization, the diagonal of the Cholesky-Infinity factor is set to Inf and the rest of that row is set to 0. This forces a 0 in the corresponding entry of the solution vector in the associated system of linear equations. In practice, X is assumed to be positive semi-definite so even negative pivots are replaced with a value of Inf. Remarks The incomplete factorizations may be useful as preconditioners for solving large sparse systems of linear equations. A single 0 on the diagonal of the upper triangular factor makes it singular. The incomplete factorization with a drop tolerance prints a warning message if the upper triangular factor has zeros on the diagonal. Similarly, using the rdiag option to replace a zero diagonal only 2-249 cholinc gets rid of the symptoms of the problem, but it does not solve it. The preconditioner may not be singular, but it probably is not useful, and a warning message is printed. The Cholesky-Infinity factorization is meant to be used within interior-point methods. Otherwise, its use is not recommended. Examples Example 1. Start with a symmetric positive definite matrix, S. S = delsq(numgrid('C',15)); S is the two-dimensional, five-point discrete negative Lapacian on the grid generated by numgrid('C',15). Compute the Cholesky factorization and the incomplete Cholesky factorization of level 0 to compare the fill-in. Make S singular by zeroing out a diagonal entry and compute the (partial) incomplete Cholesky factorization of level 0. C = chol(S); R0 = cholinc(S,'0'); S2 = S; S2(101,101) = 0; [R,p] = cholinc(S2,'0'); Fill-in occurs within the bands of S in the complete Cholesky factor, but none in the incomplete Cholesky factor. The incomplete factorization of the singular S2 stopped at row p = 101 resulting in a 100-by-139 partial factor. D1 = (R0'*R0).*spones(S)-S; D2 = (R'*R).*spones(S2)-S2; D1 has elements of the order of eps, showing that R0'*R0 agrees with S over its sparsity pattern. D2 has elements of the order of eps over its first 100 rows and first 100 columns, D2(1:100,:) and D2(:,1:100). 2-250 cholinc S 0 20 40 60 80 100 120 140 0 50 100 nz = 643 R0=cholinc(S, 0 ) 0 20 40 60 80 100 120 140 100 0 50 100 nz = 391 0 20 40 60 80 0 0 20 40 60 80 100 120 140 0 C= chol(S) 50 100 nz = 1557 Partial factor [R,p]=cholinc(S2, 0 ) 50 nz = 290 100 Example 2. The first subplot below shows that cholinc(S,0), the incomplete Cholesky factor with a drop tolerance of 0, is the same as the Cholesky factor of S. Increasing the drop tolerance increases the sparsity of the incomplete factors, as seen below. cholinc(S,0) 0 20 40 60 80 100 120 140 0 50 100 nz = 1557 cholinc(S,1e 2) 0 20 40 60 80 100 120 140 0 50 100 nz = 671 0 20 40 60 80 100 120 140 0 50 100 nz = 391 0 20 40 60 80 100 120 140 0 50 100 nz = 1211 cholinc(S,1e 1) cholinc(S,1e 3) 2-251 cholinc Unfortunately, the sparser factors are poor approximations, as is seen by the plot of drop tolerance versus norm(R'*R-S,1)/norm(S,1) in the next figure. Drop tolerance vs nnz(cholinc(S,droptol)) 1500 1000 500 0 4 10 0 10 3 10 2 10 1 10 0 Drop tolerance vs norm(R *R S)/norm(S) 10 10 10 10 10 1 2 3 4 10 4 10 3 10 2 10 1 10 0 Example 3. The Hilbert matrices have (i,j) entries 1/(i+j-1) and are theoretically positive definite: H3 = hilb(3) H3 = 1.0000 0.5000 0.3333 0.5000 0.3333 0.2500 0.3333 0.2500 0.2000 R3 = chol(H3) R3 = 1.0000 0.5000 0 0.2887 0 0 0.3333 0.2887 0.0745 In practice, the Cholesky factorization breaks down for larger matrices: H20 = sparse(hilb(20)); [R,p] = chol(H20); p = 14 2-252 cholinc For hilb(20), the Cholesky factorization failed in the computation of row 14 because of a numerically zero pivot. You can use the Cholesky-Infinity factorization to avoid this error. When a zero pivot is encountered, cholinc places an Inf on the main diagonal, zeros out the rest of the row, and continues with the computation: Rinf = cholinc(H20,'inf'); In this case, all subsequent pivots are also too small, so the remainder of the upper triangular factor is: full(Rinf(14:end,14:end)) ans = Inf 0 0 0 0 Inf 0 0 0 0 Inf 0 0 0 0 Inf 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 Inf 0 0 0 0 0 0 0 Inf 0 0 0 0 0 0 0 Inf Limitations Algorithm cholinc works on square sparse matrices only. For cholinc(X,'0') and cholinc(X,'inf'), X must be real. R = cholinc(X,droptol) is obtained from [L,U] = luinc(X,options), where options.droptol = droptol and options.thresh = 0. The rows of the uppertriangular U are scaled by the square root of the diagonal in that row, and this scaled factor becomes R. R = cholinc(X,options) is produced in a similar manner, except the rdiag option translates into the udiag option and the milu option takes the value of the michol option. R = cholinc(X,'0') is based on the KJI variant of the Cholesky factorization. Updates are made only to positions which are nonzero in the upper triangle of X. R = cholinc(X,'inf') is based on the algorithm in Zhang [2]. 2-253 cholinc See Also References chol, luinc, pcg [1] Saad, Yousef, Iterative Methods for Sparse Linear Systems, PWS Publishing Company, 1996. Chapter 10, Preconditioning Techniques. [2] Zhang, Yin, Solving Large-Scale Linear Programs by Interior-Point Methods Under the MATLAB Environment, Department of Mathematics and Statistics, University of Maryland Baltimore County, Technical Report TR96-01 2-254 cholupdate Purpose Syntax 2cholupdate Rank 1 update to Cholesky factorization R1 = cholupdate(R,x) R1 = cholupdate(R,x,'+') R1 = cholupdate(R,x,'-') [R1,p] = cholupdate(R,x,'-') R1 = cholupdate(R,x) where R = chol(A) is the original Cholesky factorization of A, returns the upper triangular Cholesky factor of A + x*x', where x is a column vector of appropriate length. cholupdate uses only the diagonal and upper triangle of R. The lower triangle of R is ignored. R1 = cholupdate(R,x,'+') is the same as R1 = cholupdate(R,x). R1 = cholupdate(R,x,'-') returns the Cholesky factor of A - x*x'. An error message reports when R is not a valid Cholesky factor or when the downdated matrix is not positive definite and so does not have a Cholesky factoriza- tion. [R1,p] = cholupdate(R,x,'-') will not return an error message. If p is 0, R1 is the Cholesky factor of A - x*x'. If p is greater than 0, R1 is the Cholesky factor of the original A. If p is 1, cholupdate failed because the downdated matrix is not positive definite. If p is 2, cholupdate failed because the upper triangle of R was not a valid Cholesky factor. Description Remarks Example cholupdate works only for full matrices. A = pascal(4) A = 1 1 1 1 1 2 3 4 1 3 6 10 1 4 10 20 R = chol(A) 2-255 cholupdate R = 1 0 0 0 1 1 0 0 1 2 1 0 1 3 3 1 x = [0 0 0 1]'; This is called a rank one update to A since rank(x*x') is 1: A + x*x' ans = 1 1 1 1 1 2 3 4 1 3 6 10 1 4 10 21 Instead of computing the Cholesky factor with R1 = chol(A + x*x'), we can use cholupdate: R1 = cholupdate(R,x) R1 = 1.0000 0 0 0 1.0000 1.0000 0 0 1.0000 2.0000 1.0000 0 1.0000 3.0000 3.0000 1.4142 Next destroy the positive definiteness (and actually make the matrix singular) by subtracting 1 from the last element of A. The downdated matrix is: A - x*x' ans = 1 1 1 1 1 2 3 4 1 3 6 10 1 4 10 19 2-256 cholupdate Compare chol with cholupdate: R1 = chol(A-x*x') ??? Error using ==> chol Matrix must be positive definite. R1 = cholupdate(R,x,'-') ??? Error using ==> cholupdate Downdated matrix must be positive definite. However, subtracting 0.5 from the last element of A produces a positive definite matrix, and we can use cholupdate to compute its Cholesky factor: x = [0 0 0 1/sqrt(2)]'; R1 = cholupdate(R,x,'-') R1 = 1.0000 1.0000 1.0000 0 1.0000 2.0000 0 0 1.0000 0 0 0 1.0000 3.0000 3.0000 0.7071 Algorithm cholupdate uses the algorithms from the LINPACK subroutines ZCHUD and ZCHDD. cholupdate is useful since computing the new Cholesky factor from scratch is an O ( N 3 ) algorithm, while simply updating the existing factor in this way is an O ( N 2 ) algorithm. chol, qrupdate See Also References [1] Dongarra, J.J., J.R. Bunch, C.B. Moler, and G.W. Stewart, LINPACK Users' Guide, SIAM, Philadelphia, 1979. 2-257 cla Purpose Syntax Description 2cla Clear current axes cla cla reset cla deletes from the current axes all graphics objects whose handles are not hidden (i.e., their HandleVisibility property is set to on). cla reset deletes from the current axes all graphics objects regardless of the setting of their HandleVisibility property and resets all axes properties, except Position and Units, to their default values. Remarks The cla command behaves the same way when issued on the command line as it does in callback routines it does not recognize the HandleVisibility setting of callback. This means that when issued from within a callback routine, cla deletes only those objects whose HandleVisibility property is set to on. clf, hold, newplot, reset See Also 2-258 clabel Purpose Syntax 2clabel Contour plot elevation labels clabel(C,h) clabel(C,h,v) clabel(C,h,'manual') clabel(C) clabel(C,v) clabel(C,'manual') Description The clabel function adds height labels to a two-dimensional contour plot. clabel(C,h) rotates the labels and inserts them in the contour lines. The function inserts only those labels that fit within the contour, depending on the size of the contour. clabel(C,h,v) creates labels only for those contour levels given in vector v, then rotates the labels and inserts them in the contour lines. clabel(C,h,'manual') places contour labels at locations you select with a mouse. Press the left mouse button (the mouse button on a single-button mouse) or the space bar to label a contour at the closest location beneath the center of the cursor. Press the Return key while the cursor is within the figure window to terminate labeling. The labels are rotated and inserted in the contour lines. clabel(C) adds labels to the current contour plot using the contour structure C output from contour. The function labels all contours displayed and randomly selects label positions. clabel(C,v) labels only those contour levels given in vector v. clabel(C,'manual') places contour labels at locations you select with a mouse. Remarks When the syntax includes the argument h, this function rotates the labels and inserts them in the contour lines (see Example). Otherwise, the labels are displayed upright and a '+' indicates which contour line the label is annotating. 2-259 clabel Examples Generate, draw, and label a simple contour plot. [x,y] = meshgrid( 2:.2:2); z = x.^exp( x.^2 y.^2); [C,h] = contour(x,y,z); clabel(C,h); 2 1.5 0.6 1 0. 8 0.2 9.869e 17 0.4 0.5 0.6 0.4 0.8 0.2 0.6 0 1 0. 2 0.5 0.4 1 0.2 0.6 1.5 0. 0. 9.86 2 9e 1 7 0.4 0.6 0.8 0.2 1 8 0.8 1 0.2 1 2 2 1.5 1 0.5 0 0.5 1 1.5 2 See Also contour, contourc, contourf 2-260 class Purpose Syntax 2class Create object or return class of object str obj obj obj = = = = class(object) class(s,'class_name') class(s,'class_name',parent1,parent2...) class(struct([]),'class_name',parent1,parent2...) Description str = class(object) returns a string specifying the class of object. The following table lists the object class names that may be returned. All except the last one are MATLAB classes. cell char double function handle int8 int16 int32 sparse struct uint8 uint16 uint32 'matlab_class_name' 'java_class_name' Cell array Characters array Double-precision oating point number array Array of values for calling functions indirectly 8-bit signed integer array 16-bit signed integer array 32-bit signed integer array 2-D real (or complex) sparse array Structure array 8-bit unsigned integer array 16-bit unsigned integer array 32-bit unsigned integer array Name of user-de ned MATLAB class Name of Java class obj = class(s,'class_name') creates an object of MATLAB class 'class_name' using structure s as a template. This syntax is valid only in a function named class_name.m in a directory named @class_name (where 'class_name' is the same as the string passed into class). 2-261 class obj = class(s,'class_name',parent1,parent2,...) creates an object of MATLAB class 'class_name' that inherits the methods and fields of the parent objects parent1, parent2, and so on. Structure s is used as a template for the object. obj = class(struct([]),'class_name',parent1,parent2,...) creates an object of MATLAB class 'class_name' that inherits the methods and fields of the parent objects parent1, parent2, and so on. Specifying the empty structure, struct([]), as the first argument ensures that the object created contains no fields other than those that are inherited from the parent objects. Examples To return in nameStr the name of the class of Java object j nameStr = class(j) To create a user-defined MATLAB object of class polynom p = class(p,'polynom') See Also inferiorto, isa, superiorto The MATLAB Classes and Objects and the Calling Java from MATLAB chapters in Programming and Data Types. 2-262 clc Purpose Graphical Interface Syntax Description 2clc Clear Command Window As an alternative to the clc function, use Clear Command Window in the MATLAB desktop Edit menu. clc clc clears all input and output from the Command Window display, giving you a clean screen. After using clc, you cannot use the scroll bar to see the history of functions, but still can use the up arrow to see one previous line at a time. Examples See Also Use clc in an M-file to always display output in the same starting position on the screen. clear, clf, close, home 2-263 clear Purpose Graphical Interface Syntax 2clear Remove items from workspace, freeing up system memory As an alternative to the clear function, use Clear Workspace in the MATLAB desktop Edit menu, or in the context menu in the Workspace browser. clear clear name clear name1 name2 name3 ... clear global name clear keyword clear('name1','name2','name3',...) clear removes all variables from the workspace. This frees up system memory. clear name removes just the M-file or MEX-file function or variable name from the workspace. You can use wildcards (*) to remove items selectively. For example, clear my* removes any variables whose names begin with the string my. It removes debugging breakpoints in M-files and reinitializes persistent variables, since the breakpoints for a function and persistent variables are cleared whenever the M-file is changed or cleared. If name is global, it is removed from the current workspace, but left accessible to any functions declaring it global. If name has been locked by mlock, it remains in memory. Description Use a partial path to distinguish between different overloaded versions of a function. For example, clear inline/display clears only the display method for inline objects, leaving any other implementations in memory. clear name1 name2 name3 ... removes name1, name2, and name3 from the workspace. clear global name removes the global variable name. If name is global, clear name removes name from the current workspace, but leaves it accessible to any functions declaring it global. Use clear global name to completely remove a global variable. 2-264 clear clear keyword clears the items indicated by keyword. Keyword all Items Cleared Removes all variables, functions, and MEX- les from memory, leaving the workspace empty. Using clear all removes debugging breakpoints in M-files and reinitializes persistent variables, since the breakpoints for a function and persistent variables are cleared whenever the M-file is changed or cleared. When issued from the Command Window prompt, also removes the Java packages import list. The same as clear all, but also clears MATLAB class de nitions. If any objects exist outside the workspace (e.g., in user data or persistent variables in a locked M- le), a warning is issued and the class de nition is not cleared. Issue a clear classes function if the number or names of elds in a class are changed. Clears all the currently compiled M-functions and MEX-functions from memory. Using clear function removes debugging breakpoints in the function M-file and reinitializes persistent variables, since the breakpoints for a function and persistent variables are cleared whenever the M-file is changed or cleared. Clears all global variables from the workspace. Removes the Java packages import list. It can only be issued from the Command Window prompt. It cannot be used in a function. Clears all variables from the workspace. classes functions global import variables clear('name1','name2','name3',...) is the function form of the syntax. Use this form when the variable name or function name is stored in a string. 2-265 clear Remarks When you use clear in a function, it has the following effect on items in your function and base workspaces: clear name - If name is the name of a function, the function is cleared in both the function workspace and in your base workspace. clear functions - All functions are cleared in both the function workspace and in your base workspace. clear global - All global variables are cleared in both the function workspace and in your base workspace. clear all - All functions, global variables, and classes are cleared in both the function workspace and in your base workspace. Limitations Examples clear does not affect the amount of memory allocated to the MATLAB process under UNIX. Given a workspace containing the following variables Name c frame gbl1 gbl2 xint Size 3x4 1x1 1x1 1x1 1x1 Bytes 1200 8 8 1 Class cell array java.awt.Frame double array (global) double array (global) int8 array You can clear a single variable, xint, by typing clear xint To clear all global variables, type clear global whos Name Size c frame 3x4 1x1 Bytes 1200 Class cell array java.awt.Frame 2-266 clear To clear all compiled M- and MEX-functions from memory, type clear functions. In the case shown below, clear functions was unable to clear one M-file function, testfun, from memory because the function is locked. clear functions inmem ans = 'testfun' mislocked testfun ans = 1 % Attempt to clear all functions. % One M-file function remains in memory. % This function is locked in memory. Once you unlock the function from memory, you can clear it. munlock testfun clear functions inmem ans = Empty cell array: 0-by-1 See Also clc, close, import, mlock, munlock, pack, persistent, who, whos 2-267 clear (serial) Purpose Syntax Arguments Description Remarks 2clear (serial) Remove a serial port object from the MATLAB workspace clear obj obj A serial port object or an array of serial port objects. clear obj removes obj from the MATLAB workspace. If obj is connected to the device and it is cleared from the workspace, then obj remains connected to the device. You can restore obj to the workspace with the instrfind function. A serial port object connected to the device has a Status property value of open. To disconnect obj from the device, use the fclose function. To remove obj from memory, use the delete function. You should remove invalid serial port objects from the workspace with clear. If you use the help command to display help for clear, then you need to supply the pathname shown below. help serial/private/clear Example This example creates the serial port object s, copies s to a new variable scopy, and clears s from the MATLAB workspace. s is then restored to the workspace with instrfind and is shown to be identical to scopy. s = serial('COM1'); scopy = s; clear s s = instrfind; isequal(scopy,s) ans = 1 See Also Functions delete, fclose, instrfind, isvalid Properties Status 2-268 clf Purpose Syntax Description 2clf Clear current figure window clf clf reset clf deletes from the current figure all graphics objects whose handles are not hidden (i.e., their HandleVisibility property is set to on). clf reset deletes from the current figure all graphics objects regardless of the setting of their HandleVisibility property and resets all figure properties, except Position, Units, PaperPosition, and PaperUnits to their default values. Remarks The clf command behaves the same way when issued on the command line as it does in callback routines it does not recognize the HandleVisibility setting of callback. This means that when issued from within a callback routine, clf deletes only those objects whose HandleVisibility property is set to on. cla, clc, hold, reset See Also 2-269 clipboard Purpose Graphical Interface Syntax 2clipboard Copy and paste strings to and from the system clipboard. As an alternative to clipboard, use the Import Wizard. To use the Import Wizard to copy data from the clipboard, select Paste Special from the Edit menu. clipboard('copy',data) str = clipboard('paste') data = clipboard('pastespecial') clipboard('copy', data) sets the clipboard contents to data. If data is not a character array, clipboard uses mat2str to convert it to a string. str = clipboard('paste') returns the current contents of the clipboard as a string or as an empty string (' '), if the current clipboard content cannot be converted to a string. data = clipboard('pastespecial') returns the current contents of the clipboard as an array using uiimport. Description Note Requires an active X display on Unix and Java elsewhere. See Also load, uiimport 2-270 clock Purpose Syntax Description 2clock Current time as a date vector c = clock c = clock returns a 6-element date vector containing the current date and time in decimal form: c = [year month day hour minute seconds] The first five elements are integers. The seconds element is accurate to several digits beyond the decimal point. The statement fix(clock) rounds to integer display format. See Also cputime, datenum, datevec, etime, tic, toc 2-271 close Purpose Syntax 2close Delete specified figure close close(h) close name close all close all hidden status = close(...) close deletes the current figure or the specified figure(s). It optionally returns Description the status of the close operation. close deletes the current figure (equivalent to close(gcf)). close(h) deletes the figure identified by h. If h is a vector or matrix, close deletes all figures identified by h. close name deletes the figure with the specified name. close all deletes all figures whose handles are not hidden. close all hidden deletes all figures including those with hidden handles. status = close(...) returns 1 if the specified windows have been deleted and 0 otherwise. Remarks The close function works by evaluating the specified figure s CloseRequestFcn property with the statement: eval(get(h,'CloseRequestFcn')) The default CloseRequestFcn, closereq, deletes the current figure using delete(get(0,'CurrentFigure')). If you specify multiple figure handles, close executes each figure s CloseRequestFcn in turn. If MATLAB encounters an error that terminates the execution of a CloseRequestFcn, the figure is not deleted. Note that using your computer s window manager (i.e., the Close menu item) also calls the figure s CloseRequestFcn. If a figure s handle is hidden (i.e., the figure s HandleVisibility property is set to callback or off and the root ShowHiddenHandles property is set on), you 2-272 close must specify the hidden option when trying to access a figure using the all option. To delete all figures unconditionally, use the statements: set(0,'ShowHiddenHandles','on') delete(get(0,'Children')) The delete function does not execute the figure s CloseRequestFcn; it simply deletes the specified figure. The figure CloseRequestFcn allows you to either delay or abort the closing of a figure once the close function has been issued. For example, you can display a dialog box to see if the user really wants to delete the figure or save and clean up before closing. See Also delete, figure, gcf The figure HandleVisibility property The root ShowHiddenHandles property 2-273 close (avifile) Purpose Syntax Description See Also 2close (avifile) Close Audio Video Interleaved (AVI) file aviobj = close(aviobj) aviobj = close(aviobj) finishes writing and closes the AVI file associated with aviobj, which is an AVI file object, created using the avifile function. avifile, addframe, movie2avi 2-274 closereq Purpose Syntax Description See Also 2closereq Default figure close request function closereq closereq delete the current figure. The figure CloseRequestFcn property 2-275 cmopts Purpose Graphical Interface Syntax Description 2cmopts Get name of source control system As an alternative to cmopts, use preferences. Select File -> Preferences in the MATLAB desktop, and then select General -> Source Control. cmopts cmopts returns the name of the source control system you selected using preferences, which is one of the following: clearcase customverctrl pvcs rcs sourcesafe If you have not selected a source control system, cmopts returns none Specifying a Source Control System To specify the source control system: 1 From the MATLAB Editor window or from a Simulink or Stateflow model window, select File -> Source Control -> Preferences. The Preferences dialog box opens. 2 In the left pane, click the + for General, and then select Source Control. The currently selected system is shown. 3 Select the system you want to use from the Source control system list. 4 Click OK. For more information, see source control preferences. Examples See Also Type cmopts and MATLAB returns rcs, meaning the source control system specified in preferences is RCS. checkin, checkout, customverctrl 2-276 colamd Purpose Syntax 2colamd Column approximate minimum degree permutation p = colamd(S) p = colamd(S,knobs) [p,stats] = colamd(S) [p,stats] = colamd(S,knobs) p = colamd(S) returns the column approximate minimum degree permutation vector for the sparse matrix S. For a non-symmetric matrix S, S(:,p) tends to have sparser LU factors than S. The Cholesky factorization of S(:,p)' * S(:,p) also tends to be sparser than that of S'*S. knobs is a two-element vector. If S is m-by-n, then rows with more than (knobs(1))*n entries are ignored. Columns with more than (knobs(2))*m Description entries are removed prior to ordering, and ordered last in the output permutation p. If the knobs parameter is not present, then knobs(1) = knobs(2) = spparms('wh_frac'). stats is an optional vector that provides data about the ordering and the validity of the matrix S. stats(1) stats(2) stats(3) Number of dense or empty rows ignored by colamd Number of dense or empty columns ignored by colamd Number of garbage collections performed on the internal data structure used by colamd (roughly of size 2.2*nnz(S) + 4*m + 7*n integers) 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 Although, MATLAB built-in functions generate valid sparse matrices, a user may construct an invalid sparse matrix using the MATLAB C or Fortran APIs and pass it to colamd. For this reason, colamd verifies that S is valid: 2-277 colamd If a row index appears two or more times in the same column, colamd ignores the duplicate entries, continues processing, and provides information about the duplicate entries in stats(4:7). If row indices in a column are out of order, colamd sorts each column of its internal copy of the matrix S (but does not repair the input matrix S), continues processing, and provides information about the out-of-order entries in stats(4:7). If S is invalid in any other way, colamd cannot continue. It prints an error message, and returns no output arguments (p or stats) . The ordering is followed by a column elimination tree post-ordering. Note colamd tends to be faster than colmmd and tends to return a better ordering. See Also References colmmd, colperm, spparms, symamd, symmmd, symrcm [1] The authors of the code for colamd 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-278 colmmd Purpose Syntax Description 2colmmd Sparse column minimum degree permutation p = colmmd(S) p = colmmd(S) returns the column minimum degree permutation vector for the sparse matrix S. For a nonsymmetric matrix S, this is a column permutation p such that S(:,p) tends to have sparser LU factors than S. The colmmd permutation is automatically used by \ and / for the solution of nonsymmetric and symmetric indefinite sparse linear systems. Use spparms to change some options and parameters associated with heuristics in the algorithm. Algorithm The minimum degree algorithm for symmetric matrices is described in the review paper by George and Liu [1]. For nonsymmetric matrices, MATLAB s minimum degree algorithm is new and is described in the paper by Gilbert, Moler, and Schreiber [2]. It is roughly like symmetric minimum degree for A'*A, but does not actually form A'*A. Each stage of the algorithm chooses a vertex in the graph of A'*A of lowest degree (that is, a column of A having nonzero elements in common with the fewest other columns), eliminates that vertex, and updates the remainder of the graph by adding fill (that is, merging rows). If the input matrix S is of size m-by-n, the columns are all eliminated and the permutation is complete after n stages. To speed up the process, several heuristics are used to carry out multiple stages simultaneously. Examples The Harwell-Boeing collection of sparse matrices and the MATLAB demos directory include a test matrix WEST0479. It is a matrix of order 479 resulting from a model due to Westerberg of an eight-stage chemical distillation column. The spy plot shows evidence of the eight stages. The colmmd ordering scrambles this structure. load west0479 A = west0479; p = colmmd(A); spy(A) spy(A(:,p)) 2-279 colmmd A 0 100 200 300 400 0 100 200 300 nz = 1887 400 0 100 200 300 400 0 100 A(:,p) 200 300 nz = 1887 400 Comparing the spy plot of the LU factorization of the original matrix with that of the reordered matrix shows that minimum degree reduces the time and storage requirements by better than a factor of 2.8. The nonzero counts are 16777 and 5904, respectively. spy(lu(A)) spy(lu(A(:,p))) lu(A) 0 100 200 300 400 0 100 200 300 nz = 16777 400 0 100 200 300 400 0 100 lu(A(:,p)) 200 300 nz = 5904 400 2-280 colmmd See Also colamd, colperm, lu, spparms, symamd, symmmd, symrcm The arithmetic operator \ References [1] George, Alan and Liu, Joseph, The Evolution of the Minimum Degree Ordering Algorithm, SIAM Review, 1989, 31:1-19. [2] Gilbert, John R., Cleve Moler, and Robert Schreiber, Sparse Matrices in MATLAB: Design and Implementation, SIAM Journal on Matrix Analysis and Applications 13, 1992, pp. 333-356. 2-281 colorbar Purpose Syntax 2colorbar Display colorbar showing the color scale colorbar colorbar('vert') colorbar('horiz') colorbar(h) h = colorbar(...) colorbar(...,'peer',axes_handle) Description The colorbar function displays the current colormap in the current figure and resizes the current axes to accommodate the colorbar. colorbar updates the most recently created colorbar or, when the current axes does not have a colorbar, colorbar adds a new vertical colorbar. colorbar('vert') adds a vertical colorbar to the current axes. colorbar('horiz') adds a horizontal colorbar to the current axes. colorbar(h) uses the axes h to create the colorbar. The colorbar is horizontal if the width of the axes is greater than its height, as determined by the axes Position property. h = colorbar(...) returns a handle to the colorbar, which is an axes graphics object. colorbar(...,'peer',axes_handle) creates a colorbar associated with the axes axes_handle instead of the current axes. Remarks Examples colorbar works with two-dimensional and three-dimensional plots. Display a colorbar beside the axes. surf(peaks(30)) colormap cool 2-282 colorbar colorbar 8 6 10 8 4 6 4 2 0 2 4 6 8 30 25 20 15 10 5 0 0 5 15 10 6 20 25 30 4 2 0 2 See Also colormap 2-283 colordef Purpose Syntax 2colordef Sets default property values to display different color schemes colordef white colordef black colordef none colordef(fig,color_option) h = colordef('new',color_option) colordef enables you to select either a white or black background for graphics Description display. It sets axis lines and labels to show up against the background color. colordef white sets the axis background color to white, the axis lines and labels to black, and the figure background color to light gray. colordef black sets the axis background color to black, the axis lines and labels to white, and the figure background color to dark gray. colordef none sets the figure coloring to that used by MATLAB Version 4 (essentially a black background). colordef(fig,color_option) sets the color scheme of the figure identified by the handle fig to the color option 'white', 'black', or 'none'. h = colordef('new',color_option) returns the handle to a new figure created with the specified color options (i.e., 'white', 'black', or 'none'). Remarks colordef affects only subsequently drawn figures, not those currently on the display. This is because colordef works by setting default property values (on the root or figure level). You can list the currently set default values on the root level with the statement: get(0,'defaults') You can remove all default values using the reset command: reset(0) See the get and reset references pages for more information. See Also whitebg 2-284 colormap Purpose Syntax 2colormap Set and get the current colormap colormap(map) colormap('default') cmap = colormap Description A colormap is an m-by-3 matrix of real numbers between 0.0 and 1.0. Each row is an RGB vector that defines one color. The kth row of the colormap defines the k-th color, where map(k,:) = [r(k) g(k) b(k)]) specifies the intensity of red, green, and blue. colormap(map) sets the colormap to the matrix map. If any values in map are outside the interval [0 1], MATLAB returns the error: Colormap must have values in [0,1]. colormap('default') sets the current colormap to the default colormap. cmap = colormap; retrieves the current colormap. The values returned are in the interval [0 1]. Specifying Colormaps M-files in the color directory generate a number of colormaps. Each M-file accepts the colormap size as an argument. For example, colormap(hsv(128)) creates an hsv colormap with 128 colors. If you do not specify a size, MATLAB creates a colormap the same size as the current colormap. Supported Colormaps MATLAB supports a number of colormaps. autumn varies smoothly from red, through orange, to yellow. bone is a grayscale colormap with a higher value for the blue component. This colormap is useful for adding an electronic look to grayscale images. colorcube contains as many regularly spaced colors in RGB colorspace as possible, while attempting to provide more steps of gray, pure red, pure green, and pure blue. 2-285 colormap cool consists of colors that are shades of cyan and magenta. It varies smoothly from cyan to magenta. copper varies smoothly from black to bright copper. flag consists of the colors red, white, blue, and black. This colormap completely changes color with each index increment. gray returns a linear grayscale colormap. hot varies smoothly from black, through shades of red, orange, and yellow, to white. hsv varies the hue component of the hue-saturation-value color model. The colors begin with red, pass through yellow, green, cyan, blue, magenta, and return to red. The colormap is particularly appropriate for displaying periodic functions. hsv(m) is the same as hsv2rgb([h ones(m,2)]) where h is the linear ramp, h = (0:m 1)'/m. jet ranges from blue to red, and passes through the colors cyan, yellow, and orange. It is a variation of the hsv colormap. The jet colormap is associated with an astrophysical fluid jet simulation from the National Center for Supercomputer Applications. See the Examples section. lines produces a colormap of colors specified by the axes ColorOrder property and a shade of gray. pink contains pastel shades of pink. The pink colormap provides sepia tone colorization of grayscale photographs. prism repeats the six colors red, orange, yellow, green, blue, and violet. spring consists of colors that are shades of magenta and yellow. summer consists of colors that are shades of green and yellow. white is an all white monochrome colormap. winter consists of colors that are shades of blue and green. Examples The images and colormaps demo, imagedemo, provides an introduction to colormaps. Select Color Spiral from the menu. This uses the pcolor function to display a 16-by-16 matrix whose elements vary from 0 to 255 in a rectilinear spiral. The hsv colormap starts with red in the center, then passes through yellow, green, cyan, blue, and magenta before returning to red at the outside end of the spiral. Selecting Colormap Menu gives access to a number of other colormaps. 2-286 colormap The rgbplot function plots colormap values. Try rgbplot(hsv), rgbplot(gray), and rgbplot(hot). The following commands display the flujet data using the jet colormap. load flujet image(X) colormap(jet) The demos directory contains a CAT scan image of a human spine. To view the image, type the following commands: load spine image(X) 2-287 colormap colormap bone 50 100 150 200 250 300 350 50 100 150 200 250 300 350 400 450 Algorithm See Also Each figure has its own Colormap property. colormap is an M-file that sets and gets this property. brighten, caxis, contrast, hsv2rgb, pcolor, rgb2hsv, rgbplot The Colormap property of figure graphics objects. 2-288 ColorSpec Purpose Description 2ColorSpec Color specification ColorSpec is not a command; it refers to the three ways in which you specify color in MATLAB: RGB triple Short name Long name The short names and long names are MATLAB strings that specify one of eight predefined colors. The RGB triple is a three-element row vector whose elements specify the intensities of the red, green, and blue components of the color; the intensities must be in the range [0 1]. The following table lists the predefined colors and their RGB equivalents. RGB Value [1 1 0] [1 0 1] [0 1 1] [1 0 0] [0 1 0] [0 0 1] [1 1 1] [0 0 0] Short Name y m c r g b w k Long Name yellow magenta cyan red green blue white black Remarks The eight predefined colors and any colors you specify as RGB values are not part of a figure s colormap, nor are they affected by changes to the figure s colormap. They are referred to as fixed colors, as opposed to colormap colors. To change the background color of a figure to green, specify the color with a short name, a long name, or an RGB triple. These statements generate equivalent results: whitebg('g') Examples 2-289 ColorSpec whitebg('green') whitebg([0 1 0]); You can use ColorSpec anywhere you need to define a color. For example, this statement changes the figure background color to pink: set(gcf,'Color',[1,0.4,0.6]) See Also bar, bar3, colordef, colormap, fill, fill3, whitebg 2-290 colperm Purpose Syntax Description 2colperm Sparse column permutation based on nonzero count j = colperm(S) j = colperm(S) generates a permutation vector j such that the columns of S(:,j) are ordered according to increasing count of nonzero entries. This is sometimes useful as a preordering for LU factorization; in this case use lu(S(:,j)). If S is symmetric, then j = colperm(S) generates a permutation j so that both the rows and columns of S(j,j) are ordered according to increasing count of nonzero entries. If S is positive definite, this is sometimes useful as a preordering for Cholesky factorization; in this case use chol(S(j,j)). Algorithm Examples The algorithm involves a sort on the counts of nonzeros in each column. The n-by-n arrowhead matrix A = [ones(1,n); ones(n-1,1) speye(n-1,n-1)] has a full first row and column. Its LU factorization, lu(A), is almost completely full. The statement j = colperm(A) returns j = [2:n 1]. So A(j,j) sends the full row and column to the bottom and the rear, and lu(A(j,j)) has the same nonzero structure as A itself. On the other hand, the Bucky ball example, B = bucky has exactly three nonzero elements in each row and column, so j = colperm(B) is the identity permutation and is no help at all for reducing fill-in with subsequent factorizations. See Also chol, colamd, colmmd, lu, spparms, symamd, symmmd, symrcm 2-291 comet Purpose Syntax 2comet Two-dimensional comet plot comet(y) comet(x,y) comet(x,y,p) Description A comet plot is an animated graph in which a circle (the comet head) traces the data points on the screen. The comet body is a trailing segment that follows the head. The tail is a solid line that traces the entire function. comet(y) displays a comet plot of the vector y. comet(x,y) displays a comet plot of vector y versus vector x. comet(x,y,p) specifies a comet body of length p*length(y). p defaults to 0.1. Remarks Note that the trace left by comet is created by using an EraseMode of none, which means you cannot print the plot (you get only the comet head) and it disappears if you cause a redraw (e.g., by resizing the window). Create a simple comet plot: t = 0:.01:2*pi; x = cos(2 t).*(cos(t).^2); y = sin(2 t).*(sin(t).^2); comet(x,y); Examples See Also comet3 2-292 comet3 Purpose Syntax 2comet3 Three-dimensional comet plot comet3(z) comet3(x,y,z) comet3(x,y,z,p) Description A comet plot is an animated graph in which a circle (the comet head) traces the data points on the screen. The comet body is a trailing segment that follows the head. The tail is a solid line that traces the entire function. comet3(z) displays a three-dimensional comet plot of the vector z. comet3(x,y,z) displays a comet plot of the curve through the points [x(i),y(i),z(i)]. comet3(x,y,z,p) specifies a comet body of length p length(y). Remarks Note that the trace left by comet3 is created by using an EraseMode of none, which means you cannot print the plot (you get only the comet head) and it disappears if you cause a redraw (e.g., by resizing the window). Create a three-dimensional comet plot. t = -10*pi:pi/250:10*pi; comet3((cos(2*t).^2).*sin(t),(sin(2*t).^2).*cos(t),t); Examples See Also comet 2-293 compan Purpose Syntax Description 2compan Companion matrix A = compan(u) A = compan(u) returns the corresponding companion matrix whose first row is -u(2:n)/u(1), where u is a vector of polynomial coefficients. The eigenvalues of compan(u) are the roots of the polynomial. Examples The polynomial ( x 1 ) ( x 2 ) ( x + 3 ) = x 3 7x + 6 has a companion matrix given by u = [1 0 -7 6] A = compan(u) A = 0 7 -6 1 0 0 0 1 0 The eigenvalues are the polynomial roots: eig(compan(u)) ans = -3.0000 2.0000 1.0000 This is also roots(u). See Also eig, poly, polyval, roots 2-294 compass Purpose Syntax 2compass Plot arrows emanating from the origin compass(X,Y) compass(Z) compass(...,LineSpec) h = compass(...) Description A compass plot displays direction or velocity vectors as arrows emanating from the origin. X, Y, and Z are in Cartesian coordinates and plotted on a circular grid. compass(X,Y) displays a compass plot having n arrows, where n is the number of elements in X or Y. The location of the base of each arrow is the origin. The location of the tip of each arrow is a point relative to the base and determined by [X(i),Y(i)]. compass(Z) displays a compass plot having n arrows, where n is the number of elements in Z. The location of the base of each arrow is the origin. The location of the tip of each arrow is relative to the base as determined by the real and imaginary components of Z. This syntax is equivalent to compass(real(Z),imag(Z)). compass(...,LineSpec) draws a compass plot using the line type, marker symbol, and color specified by LineSpec. h = compass(...) returns handles to line objects. Examples Draw a compass plot of the eigenvalues of a matrix. Z = eig(randn(20,20)); compass(Z) 2-295 compass 90 5.2689 120 4.2151 60 3.1613 150 2.1076 30 1.0538 180 0 210 330 240 270 300 See Also feather, LineSpec, rose 2-296 complex Purpose Syntax Description 2complex Construct complex data from real and imaginary components c = complex(a,b) c = complex(a) c = complex(a,b) creates a complex output, c, from the two real inputs. c = a + bi The output is the same size as the inputs, which must be scalars or equally sized vectors, matrices, or multi-dimensional arrays of the same data type. Note If b is all zeros, c is complex and the value of all its imaginary components is 0. In contrast, the result of the addition a+0i returns a strictly real result. c = complex(a) for real a returns the complex result c with real part a and 0 as the value of all imaginary components. Even though the value of all imaginary components is 0, c is complex and isreal(c) returns false. The complex function provides a useful substitute for expressions such as a + i*b or a + j*b in cases when the names i and j may be used for other variables (and do not equal 1 ), when a and b are not double-precision, or when b is all zero. Example Create complex uint8 vector from two real uint8 vectors. a = uint8([1;2;3;4]) b = uint8([2;2;7;7]) c = complex(a,b) c = 1.0000 2.0000 3.0000 4.0000 + + + + 2.0000i 2.0000i 7.0000i 7.0000i 2-297 complex See Also abs, angle, conj, i, imag, isreal, j, real 2-298 computer Purpose Syntax 2computer Identify information about computer on which MATLAB is running str = computer [str,maxsize] = computer [str,maxsize,endian] = computer str = computer returns the string str with the computer type on which Description MATLAB is running. [str,maxsize] = computer returns the integer maxsize, which contains the maximum number of elements allowed in an array with this version of MATLAB. [str,maxsize,endian] = computer also returns either 'L' for little endian byte ordering or 'B' for big endian byte ordering. The list of supported computers changes as new computers are added and others become obsolete. A typical list follows. str ALPHA HP700 HPUX IBM_RS GLNX86 PCWIN SGI SOL2 Computer Compaq Alpha (OSF1) HP 9000/700 (HP-UX 10.20) HP PA-RISC (HP-UX 11.00) IBM RS6000 workstation (AIX) Linux on PC Microsoft Windows Silicon Graphics (IRIX/IRIX64) Sun Solaris 2 SPARC workstation Remarks See Also SGI64 users prior to R12 must migrate to SGI with R12. LNX86 users prior to R12 must migrate to GLNX86 with R12. ispc, isunix 2-299 computer 2-300 cond Purpose Syntax Description 2cond Condition number with respect to inversion c = cond(X) c = cond(X,p) The condition number of a matrix measures the sensitivity of the solution of a system of linear equations to errors in the data. It gives an indication of the accuracy of the results from matrix inversion and the linear equation solution. Values of cond(X) and cond(X,p) near 1 indicate a well-conditioned matrix. c = cond(X) returns the 2-norm condition number, the ratio of the largest singular value of X to the smallest. c = cond(X,p) returns the matrix condition number in p-norm: norm(X,p) * norm(inv(X),p If p is... 1 2 'fro' inf Then cond(X,p) returns the... 1-norm condition number 2-norm condition number Frobenius norm condition number In nity norm condition number Algorithm See Also References The algorithm for cond (when p = 2) uses the singular value decomposition, svd. condeig, condest, norm, normest, rank, rcond, 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-301 condeig Purpose Syntax Description 2condeig Condition number with respect to eigenvalues c = condeig(A) [V,D,s] = condeig(A) c = condeig(A) returns a vector of condition numbers for the eigenvalues of A. These condition numbers are the reciprocals of the cosines of the angles between the left and right eigenvectors. [V,D,s] = condeig(A) is equivalent to [V,D] = eig(A); s = condeig(A); Large condition numbers imply that A is near a matrix with multiple eigenvalues. See Also balance, cond, eig 2-302 condest Purpose Syntax Description 2condest 1-norm condition number estimate c = condest(A) [c,v] = condest(A) c = condest(A) computes a lower bound C for the 1-norm condition number of a square matrix A. c = condest(A,t) changes t, a positive integer parameter equal to the number of columns in an underlying iteration matrix. Increasing the number of columns usually gives a better condition estimate but increases the cost. The default is t = 2, which almost always gives an estimate correct to within a factor 2. [c,v] = condest(A) also computes a vector v which is an approximate null vector if c is large. v satisfies norm(A*v,1) = norm(A,1)*norm(v,1)/c. Note condest invokes rand. If repeatable results are required then invoke rand('state',j), for some j, before calling this function. This function is particularly useful for sparse matrices. condest uses block 1-norm power method of Higham and Tisseur [1]. See Also Reference cond, norm, normest [1] Higham, N. J. and F. Tisseur, A Block Algorithm for Matrix 1-Norm Estimation, with an Application to 1-Norm Pseudospectra, SIAM Journal Matrix Anal. Appl., Vol. 21, No. 4, 2000, pp.1185-1201. 2-303 coneplot Purpose Syntax 2coneplot Plot velocity vectors as cones in a 3-D vector field coneplot(X,Y,Z,U,V,W,Cx,Cy,Cz) coneplot(U,V,W,Cx,Cy,Cz) coneplot(...,s) coneplot(...,color) coneplot(...,'quiver') coneplot(...,'method') coneplot(X,Y,Z,U,V,W,'nointerp') h = coneplot(...) coneplot(X,Y,Z,U,V,W,Cx,Cy,Cz) plots velocity vectors as cones pointing in Description the direction of the velocity vector and having a length proportional to the magnitude of the velocity vector. X, Y, Z define the coordinates for the vector field. U, V, W define the vector field. These arrays must be the same size, monotonic, and 3-D plaid (such as the data produced by meshgrid). Cx, Cy, Cz define the location of the cones in vector field. The section "Starting Points for Stream Plots" in Visualization Techniques provides more information on defining starting points. coneplot(U,V,W,Cx,Cy,Cz) (omitting the X, Y, and Z arguments) assumes [X,Y,Z] = meshgrid(1:n,1:m,1:p) where [m,n,p]= size(U). coneplot(...,s) MATLAB automatically scales the cones to fit the graph and then stretches them by the scale factor s. If you do not specify a value for s, MATLAB uses a value of 1. Use s = 0 to plot the cones without automatic scaling. coneplot(...,color) interpolates the array color onto the vector field and then colors the cones according to the interpolated values. The size of the color array must be the same size as the U, V, W arrays. This option works only with cones (i.e., not with the quiver option). coneplot(...,'quiver') draws arrows instead of cones (see quiver3 for an illustration of a quiver plot). 2-304 coneplot coneplot(...,'method') specifies the interpolation method to use. method can be: linear, cubic, nearest. linear is the default (see interp3 for a discussion of these interpolation methods) coneplot(X,Y,Z,U,V,W,'nointerp') does not interpolate the positions of the cones into the volume. The cones are drawn at positions defined by X, Y, Z and are oriented according to U, V, W. Arrays X, Y, Z, U, V, W must all be the same size. h = coneplot(...) returns the handle to the patch object used to draw the cones. You can use the set command to change the properties of the cones. Remarks coneplot automatically scales the cones to fit the graph, while keeping them in proportion to the respective velocity vectors. It is usually best to set the data aspect ratio of the axes before calling coneplot. You can set the ratio using the daspect command, daspect([1,1,1]) Examples This example plots the velocity vector cones for vector volume data representing the motion of air through a rectangular region of space. The final graph employs a number of enhancements to visualize the data more effectively. These include: Cone plots indicate the magnitude and direction of the wind velocity. Slice planes placed at the limits of the data range provide a visual context for the cone plots within the volume. Directional lighting provides visual queues as to the orientation of the cones. View adjustments compose the scene to best reveal the information content of the data by selecting the view point, projection type, and magnification. 1. Load and Inspect Data The winds data set contains six 3-D arrays: u, v, and w specify the vector components at each of the coordinate specified in x, y, and z. The coordinates define a lattice grid structure where the data is sampled within the volume. 2-305 coneplot It is useful to establish the range of the data to place the slice planes and to specify where you want the cone plots (min, max). load xmin xmax ymin ymax zmin wind = min(x(:)); = max(x(:)); = min(y(:)); = max(y(:)); = min(z(:)); 2. Create the Cone Plot Decide where in data space you want to plot cones. This example selects the full range of x and y in eight steps and the range 3 to 15 in four steps in z (linspace, meshgrid). Use daspect to set the data aspect ratio of the axes before calling coneplot so MATLAB can determine the proper size of the cones. Draw the cones, setting the scale factor to 5 to make the cones larger than the default size. Set the coloring of each cone (FaceColor, EdgeColor). daspect([2,2,1]) xrange = linspace(xmin,xmax,8); yrange = linspace(ymin,ymax,8); zrange = 3:4:15; [cx cy cz] = meshgrid(xrange,yrange,zrange); hcones = coneplot(x,y,z,u,v,w,cx,cy,cz,5); set(hcones,'FaceColor','red','EdgeColor','none') 2-306 coneplot 3. Add the Slice Planes Calculate the magnitude of the vector field (which represents wind speed) to generate scalar data for the slice command. Create slice planes along the x-axis at xmin and xmax, along the y-axis at ymax, and along the z-axis at zmin. Specify interpolated face color so the slice coloring indicates wind speed and do not draw edges (hold, slice, FaceColor, EdgeColor). hold on wind_speed = sqrt(u.^2 + v.^2 + w.^2); hsurfaces = slice(x,y,z,wind_speed,[xmin,xmax],ymax,zmin); set(hsurfaces,'FaceColor','interp','EdgeColor','none') hold off 4. Define the View Use the axis command to set the axis limits equal to the range of the data. Orient the view to azimuth = 30 and elevation = 40 (rotate3d is a useful command for selecting the best view). Select perspective projection to provide a more realistic looking volume (camproj). Zoom in on the scene a little to make the plot as large as possible (camzoom). axis tight; view(30,40); axis off camproj perspective; camzoom(1.5) 5. Add Lighting to the Scene The light source affects both the slice planes (surfaces) and the cone plots (patches). However, you can set the lighting characteristics of each independently. Add a light source to the right of the camera and use Phong lighting give the cones and slice planes a smooth, three-dimensional appearance (camlight, lighting). Increase the value of the AmbientStrength property for each slice plane to improve the visibility of the dark blue colors. (Note that you can also specify a different colormap to change to coloring of the slice planes.) 2-307 coneplot Increase the value of the DiffuseStrength property of the cones to brighten particularly those cones not showing specular reflections. camlight right; lighting phong set(hsurfaces,'AmbientStrength',.6) set(hcones,'DiffuseStrength',.8) See Also isosurface, patch, reducevolume, smooth3, streamline, stream2, stream3, subvolume 2-308 conj Purpose Syntax Description Algorithm 2conj Complex conjugate ZC = conj(Z) ZC = conj(Z) returns the complex conjugate of the elements of Z. If Z is a complex array: conj(Z) = real(Z) - i*imag(Z) See Also i, j, imag, real 2-309 continue Purpose Syntax Description 2continue Pass control to the next iteration of for or while loop continue continue passes control to the next iteration of the for or while loop in which it appears, skipping any remaining statements in the body of the loop. In nested loops, continue passes control to the next iteration of the for or while loop enclosing it. Examples The example below shows a continue loop that counts the lines of code in the file, magic.m, skipping all blank lines and comments. A continue statement is used to advance to the next line in magic.m without incrementing the count whenever a blank line or comment line is encountered. fid = fopen('magic.m','r'); count = 0; while ~feof(fid) line = fgetl(fid); if isempty(line) | strncmp(line,'%',1) continue end count = count + 1; end disp(sprintf('%d lines',count)); See Also for, while, end, break, return 2-310 contour Purpose Syntax 2contour Two-dimensional contour plot contour(Z) contour(Z,n) contour(Z,v) contour(X,Y,Z) contour(X,Y,Z,n) contour(X,Y,Z,v) contour(...,LineSpec) [C,h] = contour(...) Description A contour plot displays isolines of matrix Z. Label the contour lines using clabel. contour(Z) draws a contour plot of matrix Z, where Z is interpreted as heights with respect to the x-y plane. Z must be at least a 2-by-2 matrix. The number of contour levels and the values of the contour levels are chosen automatically based on the minimum and maximum values of Z. The ranges of the x- and y-axis are [1:n] and [1:m], where [m,n] = size(Z). contour(Z,n) draws a contour plot of matrix Z with n contour levels. contour(Z,v) draws a contour plot of matrix Z with contour lines at the data values specified in vector v. The number of contour levels is equal to length(v). To draw a single contour of level i, use contour(Z,[i i]). contour(X,Y,Z), contour(X,Y,Z,n), and contour(X,Y,Z,v) draw contour plots of Z. X and Y specify the x- and y-axis limits. When X and Y are matrices, they must be the same size as Z, in which case they specify a surface as surf does. contour(...,LineSpec) draws the contours using the line type and color specified by LineSpec. contour ignores marker symbols. [C,h] = contour(...) returns the contour matrix C (see contourc) and a vector of handles to graphics objects. clabel uses the contour matrix C to create the labels. contour creates patch graphics objects unless you specify LineSpec, in which case contour creates line graphics objects. 2-311 contour Remarks If you do not specify LineSpec, colormap and caxis control the color. If X or Y is irregularly spaced, contour calculates contours using a regularly spaced contour grid, then transforms the data to X or Y. Examples To view a contour plot of the function z = xe ( x 2 y2 ) over the range 2 x 2, 2 y 3, create matrix Z using the statements [X,Y] = meshgrid( 2:.2:2, 2:.2:3); Z = X. exp( X.^2 Y.^2); Then, generate a contour plot of Z. [C,h] = contour(X,Y,Z); clabel(C,h) colormap cool 3 2.5 2 1.5 0. 1 1 0.1 0 0.1 2 0. 0.5 0.2 0.4 0 0.3 0.5 0 .3 0.1 0.2 0.2 1 0.1 0.1 0 1.5 2 2 1.5 1 0.5 0 0.5 1 1.5 2 View the same function over the same range with 20 evenly spaced contour lines and colored with the default colormap jet. 2-312 contour contour(X,Y,Z,20) 3 2.5 2 1.5 1 0.5 0 0.5 1 1.5 2 2 1.5 1 0.5 0 0.5 1 1.5 2 Use interp2 and contour to create smoother contours. Z = magic(4); [C,h] = contour(interp2(Z,4)); clabel(C,h) 2-313 contour 12 40 10 35 8 8 8 25 20 10 15 10 8 8 8 10 6 5 4 5 10 15 20 25 30 35 40 45 See Also clabel, contour3, contourc, contourf, interp2, quiver 2-314 8 30 10 45 10 contour3 Purpose Syntax 2contour3 Three-dimensional contour plot contour3(Z) contour3(Z,n) contour3(Z,v) contour3(X,Y,Z) contour3(X,Y,Z,n) contour3(X,Y,Z,v) contour3(...,LineSpec) [C,h] = contour3(...) contour3 creates a three-dimensional contour plot of a surface defined on a Description rectangular grid. contour3(Z) draws a contour plot of matrix Z in a three-dimensional view. Z is interpreted as heights with respect to the x-y plane. Z must be at least a 2-by-2 matrix. The number of contour levels and the values of contour levels are chosen automatically. The ranges of the x- and y-axis are [1:n] and [1:m], where [m,n] = size(Z). contour3(Z,n) draws a contour plot of matrix Z with n contour levels in a three-dimensional view. contour3(Z,v) draws a contour plot of matrix Z with contour lines at the values specified in vector v. The number of contour levels is equal to length(v). To draw a single contour of level i, use contour(Z,[i i]). contour3(X,Y,Z), contour3(X,Y,Z,n), and contour3(X,Y,Z,v) use X and Y to define the x- and y-axis limits. If X is a matrix, X(1,:) defines the x-axis. If Y is a matrix, Y(:,1) defines the y-axis. When X and Y are matrices, they must be the same size as Z, in which case they specify a surface as surf does. contour3(...,LineSpec) draws the contours using the line type and color specified by LineSpec. [C,h] = contour3(...) returns the contour matrix C as described in the function contourc and a column vector containing handles to graphics objects. contour3 creates patch graphics objects unless you specify LineSpec, in which case contour3 creates line graphics objects. 2-315 contour3 Remarks If you do not specify LineSpec, colormap and caxis control the color. If X or Y is irregularly spaced, contour3 calculates contours using a regularly spaced contour grid, then transforms the data to X or Y. Examples Plot the three-dimensional contour of a function and superimpose a surface plot to enhance visualization of the function. [X,Y] = meshgrid([-2:.25:2]); Z = X.*exp(-X.^2-Y.^2); contour3(X,Y,Z,30) surface(X,Y,Z, EdgeColor ,[.8 .8 .8], FaceColor , none ) grid off view(-15,25) colormap cool 0.5 0 0.5 2 1 0 1 2 2 1.5 1 0.5 0 0.5 1 1.5 2 See Also contour, contourc, meshc, meshgrid, surfc 2-316 contourc Purpose Syntax 2contourc Low-level contour plot computation C C C C C C = = = = = = contourc(Z) contourc(Z,n) contourc(Z,v) contourc(x,y,Z) contourc(x,y,Z,n) contourc(x,y,Z,v) Description contourc calculates the contour matrix C used by contour, contour3, and contourf. The values in Z determine the heights of the contour lines with respect to a plane. The contour calculations use a regularly spaced grid determined by the dimensions of Z. C = contourc(Z) computes the contour matrix from data in matrix Z, where Z must be at least a 2-by-2 matrix. The contours are isolines in the units of Z. The number of contour lines and the corresponding values of the contour lines are chosen automatically. C = contourc(Z,n) computes contours of matrix Z with n contour levels. C = contourc(Z,v) computes contours of matrix Z with contour lines at the values specified in vector v. The length of v determines the number of contour levels. To compute a single contour of level i, use contourc(Z,[i i]). C = contourc(x,y,Z), C = contourc(x,y,Z,n), and C = contourc(x,y,Z,v) compute contours of Z using vectors x and y to determine the x- and y-axis limits. x and y must be monotonically increasing. Remarks C is a two-row matrix specifying all the contour lines. Each contour line defined in matrix C begins with a column that contains the value of the contour (specified by v and used by clabel), and the number of (x,y) vertices in the contour line. The remaining columns contain the data for the (x,y)pairs. C = [ value1 xdata(1) xdata(2)...value2 xdata(1) xdata(2)...; dim1 ydata(1) ydata(2)...dim2 ydata(1) ydata(2)...] Specifying irregularly spaced x and y vectors is not the same as contouring irregularly spaced data. If x or y is irregularly spaced, contourc calculates 2-317 contourc contours using a regularly spaced contour grid, then transforms the data to x or y. See Also clabel, contour, contour3, contourf 2-318 contourf Purpose Syntax 2contourf Filled two-dimensional contour plot contourf(Z) contourf(Z,n) contourf(Z,v) contourf(X,Y,Z) contourf(X,Y,Z,n) contourf(X,Y,Z,v) [C,h,CF] = contourf(...) Description A filled contour plot displays isolines calculated from matrix Z and fills the areas between the isolines using constant colors. The color of the filled areas depends on the current figure s colormap. contourf(Z) draws a contour plot of matrix Z, where Z is interpreted as heights with respect to a plane. Z must be at least a 2-by-2 matrix. The number of contour lines and the values of the contour lines are chosen automatically. contourf(Z,n) draws a contour plot of matrix Z with n contour levels. contourf(Z,v) draws a contour plot of matrix Z with contour levels at the values specified in vector v. contourf(X,Y,Z), contourf(X,Y,Z,n), and contourf(X,Y,Z,v) produce contour plots of Z using X and Y to determine the x- and y-axis limits. When X and Y are matrices, they must be the same size as Z, in which case they specify a surface as surf does. [C,h,CF] = contourf(...) returns the contour matrix C as calculated by the function contourc and used by clabel, a vector of handles h to patch graphics objects, and a contour matrix CF for the filled areas. Remarks Examples If X or Y is irregularly spaced, contourf calculates contours using a regularly spaced contour grid, then transforms the data to X or Y. Create a filled contour plot of the peaks function. [C,h] = contourf(peaks(20),10); 2-319 contourf colormap autumn 20 18 16 14 12 10 8 6 4 2 2 4 6 8 10 12 14 16 18 20 See Also clabel, contour, contour3, contourc, quiver 2-320 contourslice Purpose Syntax 2contourslice Draw contours in volume slice planes contourslice(X,Y,Z,V,Sx,Sy,Sz) contourslice(X,Y,Z,V,Xi,Yi,Zi) contourslice(V,Sx,Sy,Sz), contourslice(V,Xi,Yi,Zi) contourslice(...,n) contourslice(...,cvals) contourslice(...,[cv cv]) contourslice(...,'method') h = contourslice(...) contourslice(X,Y,Z,V,Sx,Sy,Sz) draws contours in the x-, y-, and z-axis aligned planes at the points in the vectors Sx, Sy, Sz. The arrays X, Y, and Z define the coordinates for the volume V and must be monotonic and 3-D plaid (such as the data produced by meshgrid). The color at each contour is determined by the volume V, which must be an m-by-n-by-p volume array. contourslice(X,Y,Z,V,Xi,Yi,Zi) draws contours through the volume V along the surface defined by the arrays Xi,Yi,Zi. contourslice(V,Sx,Sy,Sz) and contourslice(V,Xi,Yi,Zi) (omitting the X, Y, and Z arguments) assumes [X,Y,Z] = meshgrid(1:n,1:m,1:p) where [m,n,p]= size(v). contourslice(...,n) draws n contour lines per plane, overriding the Description automatic value. contourslice(...,cvals) draws length(cval) contour lines per plane at the values specified in vector cvals. contourslice(...,[cv cv]) computes a single contour per plane at the level cv. contourslice(...,'method') specifies the interpolation method to use. method can be: linear, cubic, nearest. nearest is the default except when the contours are being drawn along the surface defined by Xi, Yi, Zi, in which case linear is the default (see interp3 for a discussion of these interpolation methods). h = contourslice(...) returns a vector of handles to patch objects that are used to implement the contour lines. 2-321 contourslice Examples This example uses the flow data set to illustrate the use of contoured slice planes (type help flow for more information on this data set). Notice that this example: Specifies a vector of length = 9 for Sx, an empty vector for the Sy, and a scalar value (0) for Sz. This creates nine contour plots along the x direction in the y-z plane, and one in the x-y plane at z = 0. Uses linspace to define a ten-element linearly spaced vector of values from -8 to 2 that specifies the number of contour lines to draw at each interval. Defines the view and projection type (camva, camproj, campos) Sets figure (gcf) and axes (gca) characteristics. [x y z v] = flow; h = contourslice(x,y,z,v,[1:9],[],[0],linspace(-8,2,10)); axis([0,10,-3,3,-3,3]); daspect([1,1,1]) camva(24); camproj perspective; campos([-3,-15,5]) set(gcf,'Color',[.5,.5,.5],'Renderer','zbuffer') set(gca,'Color','black','XColor','white', ... 'YColor','white','ZColor','white') box on 2-322 contourslice 3 2 1 0 1 2 3 3 2 1 0 1 2 1 3 2 5 4 7 6 8 9 10 See Also isosurface, smooth3, subvolume, reducevolume 2-323 contrast Purpose Syntax Description 2contrast Grayscale colormap for contrast enhancement cmap = contrast(X) cmap = contrast(X,m) The contrast function enhances the contrast of an image. It creates a new gray colormap, cmap, that has an approximately equal intensity distribution. All three elements in each row are identical. cmap = contrast(X) returns a gray colormap that is the same length as the current colormap. cmap = contrast(X,m) returns an m-by-3 gray colormap. Examples Add contrast to the clown image defined by X. load clown; cmap = contrast(X); image(X); colormap(cmap); See Also brighten, colormap, image 2-324 conv Purpose Syntax Description 2conv Convolution and polynomial multiplication w = conv(u,v) w = conv(u,v) convolves vectors u and v. Algebraically, convolution is the same operation as multiplying the polynomials whose coefficients are the elements of u and v. De nition Let m = length(u) and n = length(v). Then w is the vector of length m+n-1 whose kth element is w(k) = u ( j )v ( k + 1 j ) j The sum is over all the values of j which lead to legal subscripts for u(j) and v(k+1-j), specifically j = max(1,k+1-n): min(k,m). When m = n, this gives w(1) = u(1)*v(1) w(2) = u(1)*v(2)+u(2)*v(1) w(3) = u(1)*v(3)+u(2)*v(2)+u(3)*v(1) ... w(n) = u(1)*v(n)+u(2)*v(n-1)+ ... +u(n)*v(1) ... w(2*n-1) = u(n)*v(n) Algorithm The convolution theorem says, roughly, that convolving two sequences is the same as multiplying their Fourier transforms. In order to make this precise, it is necessary to pad the two vectors with zeros and ignore roundoff error. Thus, if X = fft([x zeros(1,length(y)-1)]) and Y = fft([y zeros(1,length(x)-1)]) then conv(x,y) = ifft(X.*Y) See Also conv2, convn, deconv, filter convmtx and xcorr in the Signal Processing Toolbox 2-325 conv2 Purpose Syntax 2conv2 Two-dimensional convolution C = conv2(A,B) C = conv2(hcol,hrow,A) C = conv2(...,'shape') C = conv2(A,B) computes the two-dimensional convolution of matrices A and B. If one of these matrices describes a two-dimensional finite impulse response Description (FIR) filter, the other matrix is filtered in two dimensions. The size of C in each dimension is equal to the sum of the corresponding dimensions of the input matrices, minus one. That is, if the size of A is [ma,na] and the size of B is [mb,nb], then the size of C is [ma+mb-1,na+nb-1]. C = conv2(hcol,hrow,A) convolves A separably with hcol in the column direction and hrow in the row direction. hcol and hrow are both vectors. If hcol is a column vector and hrow is a row vector, this case is the same as C = conv2(hcol*hrow,A). C = conv2(...,'shape') returns a subsection of the two-dimensional convolution, as specified by the shape parameter: full same valid Returns the full two-dimensional convolution (default). Returns the central part of the convolution of the same size as A. Returns only those parts of the convolution that are computed without the zero-padded edges. Using this option, C has size [ma-mb+1,na-nb+1] when all(size(A) >= size(B)). Otherwise conv2 returns []. Algorithm conv2 uses a straightforward formal implementation of the two-dimensional convolution equation in spatial form. If a and b are functions of two discrete variables, n 1 and n 2 , then the formula for the two-dimensional convolution of a and b is c ( n 1, n 2 ) = k1 = k2 = a ( k 1, k 2 ) b ( n 1 k 1, n 2 k 2 ) 2-326 conv2 In practice however, conv2 computes the convolution for finite intervals. Note that matrix indices in MATLAB always start at 1 rather than 0. Therefore, matrix elements A(1,1), B(1,1), and C(1,1) correspond to mathematical quantities a(0,0), b(0,0), and c(0,0). Examples Example 1. For the 'same' case, conv2 returns the central part of the convolution. If there are an odd number of rows or columns, the "center" leaves one more at the beginning than the end. This example first computes the convolution of A using the default ('full') shape, then computes the convolution using the 'same' shape. Note that the array returned using 'same' corresponds to the underlined elements of the array returned using the default shape. A = rand(3); B = rand(4); C = conv2(A,B) C = 0.1838 0.6929 0.5627 0.9986 0.3089 0.3287 0.2374 1.2019 1.5150 2.3811 1.1419 0.9347 0.9727 1.5499 2.3576 3.4302 1.8229 1.6464 1.2644 2.1733 3.1553 3.5128 2.1561 1.7928 0.7890 1.3325 2.5373 2.4489 1.6364 1.2422 0.3750 0.3096 1.0602 0.8462 0.6841 0.5423 % C is 6-by-6 Cs = conv2(A,B,'same') Cs = 2.3576 3.4302 1.8229 % Cs is the same size as A: 3-by-3 3.1553 3.5128 2.1561 2.5373 2.4489 1.6364 Example 2. In image processing, the Sobel edge finding operation is a two-dimensional convolution of an input array with the special matrix s = [1 2 1; 0 0 0; -1 -2 -1]; These commands extract the horizontal edges from a raised pedestal. A = zeros(10); 2-327 conv2 A(3:7,3:7) = ones(5); H = conv2(A,s); mesh(H) 4 2 0 2 4 15 10 10 5 0 0 5 15 Transposing the filter s extracts the vertical edges of A. V = conv2(A,s'); figure, mesh(V) 2-328 conv2 4 2 0 2 4 15 10 10 5 0 0 5 15 This figure combines both horizontal and vertical edges. figure mesh(sqrt(H.^2 + V.^2)) 5 4 3 2 1 0 15 10 10 5 0 0 5 15 2-329 conv2 See Also conv, convn, filter2 xcorr2 in the Signal Processing Toolbox 2-330 convhull Purpose Syntax Description 2convhull Convex hull K = convhull(x,y) [K,a] = convhull(x,y) K = convhull(x,y) returns indices into the x and y vectors of the points on the convex hull. [K,a] = convhull(x,y) also returns the area of the convex hull. Note convhull is based on qhull [2]. For information about qhull, see http://www.geom.umn.edu/software/qhull/. For copyright information, see http://www.geom.umn.edu/software/download/COPYING.html. Visualization Examples Use plot to plot the output of convhull. xx = -1:.05:1; yy = abs(sqrt(xx)); [x,y] = pol2cart(xx,yy); k = convhull(x,y); plot(x(k),y(k),'r-',x,y,'b+') 1 0.8 0.6 0.4 0.2 0 0.2 0.4 0.6 0.8 1 0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 2-331 convhull See Also Reference convhulln, delaunay, plot, polyarea, voronoi [1] Barber, C. B., D.P. Dobkin, and H.T. Huhdanpaa, "The Quickhull Algorithm for Convex Hulls," ACM Transactions on Mathematical Software, Vol. 22, No. 4, Dec. 1996, p. 469-483. Available in HTML format at http://www.acm.org/ pubs/citations/journals/toms/1996-22-4/p469-barber/ and in PostScript format at ftp://geom.umn.edu/pub/software/qhull-96.ps. [2] National Science and Technology Research Center for Computation and Visualization of Geometric Structures (The Geometry Center), University of Minnesota. 1993. 2-332 convhulln Purpose Syntax Description 2convhulln n-D convex hull K = convhulln(X) [K,v] = convhulln(X) K = convhulln(X) returns the indices K of the points in X that comprise the facets of the convex hull of X. X is an m-by-n array representing m points in n-D space. If the convex hull has p facets then K is p-by-n. [K,v] = convhulln(X) also returns the volume v of the convex hull. Note convhulln is based on qhull [2]. For information about qhull, see http://www.geom.umn.edu/software/qhull/. For copyright information, see http://www.geom.umn.edu/software/download/COPYING.html. Visualization Plotting the output of convhulln depends on the value of n: For n = 2, use plot as you would for convhull. For n = 3, you can use trisurf to plot the output. The calling sequence is K = convhull(X); trisurf(K,(X(:,1),X(:,2),X(:,3)) For more control over the color of the facets, use patch to plot the output. For an example, see Tessellation and Interpolation of Scattered Data in Higher Dimensions in the MATLAB documentation. You cannot plot convhulln output for n > 3. See Also Reference convhull, delaunayn, dsearchn, tsearchn, voronoin [1] Barber, C. B., D.P. Dobkin, and H.T. Huhdanpaa, "The Quickhull Algorithm for Convex Hulls," ACM Transactions on Mathematical Software, Vol. 22, No. 4, Dec. 1996, p. 469-483. Available in HTML format at http://www.acm.org/ pubs/citations/journals/toms/1996-22-4/p469-barber/ and in PostScript format at ftp://geom.umn.edu/pub/software/qhull-96.ps. 2-333 convhulln [2] National Science and Technology Research Center for Computation and Visualization of Geometric Structures (The Geometry Center), University of Minnesota. 1993. 2-334 convn Purpose Syntax Description 2convn N-dimensional convolution C = convn(A,B) C = convn(A,B,'shape') C = convn(A,B) computes the N-dimensional convolution of the arrays A and B. The size of the result is size(A)+size(B)-1. C = convn(A,B,'shape') returns a subsection of the N-dimensional convolution, as specified by the shape parameter: 'full' 'same' 'valid' Returns the full N-dimensional convolution (default). Returns the central part of the result that is the same size as A. Returns only those parts of the convolution that can be computed without assuming that the array A is zero-padded. The size of the result is max(size(A)-size(B) + 1, 0) See Also conv, conv2 2-335 copyfile Purpose Graphical Interface Syntax 2copyfile Copy file As an alternative to the copyfile function, you can copy files using the Current Directory browser. To open it, select Current Directory from the View menu in the MATLAB desktop. copyfile source dest copyfile source dest writable status = copyfile('source','dest',...) [status,msg] = copyfile('source','dest',...) copyfile source dest copies the file, source, to directory or file, dest. The source and dest arguments may be absolute pathnames or pathnames relative to the current directory. The pathname to dest must exist, but dest cannot be Description an existing filename in the current directory. copyfile source dest writable makes the destination file writable following the file copy. status = copyfile('source','dest',...) returns a status of 1 if the file is copied successfully and 0 otherwise. [status,msg] = copyfile('source','dest',...) returns status and a nonempty error message string when an error occurs. Example To make a copy of a file in the same directory, copyfile myfun.m myfun2.m To copy a file to another directory, keeping the same filename, file_copied = copyfile('myfun.m','../testfun/private') file_copied = 1 See Also delete, mkdir 2-336 copyobj Purpose Syntax Description 2copyobj Copy graphics objects and their descendants new_handle = copyobj(h,p) copyobj creates copies of graphics objects. The copies are identical to the original objects except the copies have different values for their Parent property and a new handle. The new parent must be appropriate for the copied object (e.g., you can copy a line object only to another axes object). new_handle = copyobj(h,p) copies one or more graphics objects identified by h and returns the handle of the new object or a vector of handles to new objects. The new graphics objects are children of the graphics objects specified by p. Remarks h and p can be scalars or vectors. When both are vectors, they must be the same length and the output argument, new_handle, is a vector of the same length. In this case, new_handle(i) is a copy of h(i) with its Parent property set to p(i). When h is a scalar and p is a vector, h is copied once to each of the parents in p. Each new_handle(i) is a copy of h with its Parent property set to p(i), and length(new_handle) equals length(p). When h is a vector and p is a scalar, each new_handle(i) is a copy of h(i) with its Parent property set to p. The length of new_handle equals length(h). Graphics objects are arranged as a hierarchy. Here, each graphics object is shown connected below its appropriate parent object. Root Figure Axes Uicontrol Uimenu Uicontextmenu Image Light Line Patch Rectangle Surface Text 2-337 copyobj Examples Copy a surface to a new axes within a different figure. h = surf(peaks); colormap hot figure % Create a new figure axes % Create an axes object in the figure new_handle = copyobj(h,gca); colormap hot view(3) grid on Note that while the surface is copied, the colormap (figure property), view, and grid (axes properties) are not copies. See Also findobj, gcf, gca, gco, get, set Parent property for all graphics objects 2-338 corrcoef Purpose Syntax Description 2corrcoef Correlation coefficients S = corrcoef(X) S = corrcoef(x,y) S = corrcoef(X) returns a matrix of correlation coefficients calculated from an input matrix whose rows are observations and whose columns are variables. The matrix S = corrcoef(X) is related to the covariance matrix C = cov(X) by C ( i, j ) S ( i, j ) = -------------------------------------C ( i, i )C ( j, j ) corrcoef(X) is the zeroth lag of the covariance function, that is, the zeroth lag of xcov(x,'coeff') packed into a square array. S = corrcoef(x,y) where x and y are column vectors is the same as corrcoef([x y]). See Also cov, mean, std xcorr, xcov in the Signal Processing Toolbox 2-339 cos, cosh Purpose Syntax Description 2cos, cosh Cosine and hyperbolic cosine Y = cos(X) Y = cosh(X) The cos and cosh functions operate element-wise on arrays. The functions domains and ranges include complex values. All angles are in radians. Y = cos(X) returns the circular cosine for each element of X. Y = cosh(X) returns the hyperbolic cosine for each element of X. Examples Graph the cosine function over the domain x , and the hyperbolic cosine function over the domain 5 x 5. x = -pi:0.01:pi; plot(x,cos(x)) x = -5:0.01:5; plot(x,cosh(x)) 1 0.8 0.6 60 0.4 0.2 0 -0.2 -0.4 20 -0.6 -0.8 -1 -4 10 y=cosh(x) -3 -2 -1 0 x 1 2 3 4 y=cos(x) 80 70 50 40 30 0 -5 -4 -3 -2 -1 0 x 1 2 3 4 5 The expression cos(pi/2) is not exactly zero but a value the size of the floating-point accuracy, eps, because pi is only a floating-point approximation to the exact value of . 2-340 cos, cosh Algorithm cos and cosh use these algorithms. cos ( x + iy ) = cos ( x ) cosh ( y ) i sin ( x ) sin ( y ) e iz + e iz cos ( z ) = ---------------------2 e z + e z cosh ( z ) = -----------------2 See Also acos, acosh 2-341 cot, coth Purpose Syntax Description 2cot, coth Cotangent and hyperbolic cotangent Y = cot(X) Y = coth(X) The cot and coth functions operate element-wise on arrays. The functions domains and ranges include complex values. All angles are in radians. Y = cot(X) returns the cotangent for each element of X. Y = coth(X) returns the hyperbolic cotangent for each element of X. Examples Graph the cotangent and hyperbolic cotangent over the domains < x < 0 and 0 < x < . x1 = -pi+0.01:0.01:-0.01; x2 = 0.01:0.01:pi-0.01; plot(x1,cot(x1),x2,cot(x2)) plot(x1,coth(x1),x2,coth(x2)) 100 80 60 40 20 0 -20 -40 -60 -80 -100 -4 y=coth(x) y=cot(x) 150 100 50 0 -50 -3 -2 -1 0 x1,x2 1 2 3 4 -100 -4 -3 -2 -1 0 x1,x2 1 2 3 4 2-342 cot, coth Algorithm cot and coth use these algorithms. 1 cot ( z ) = ----------------tan ( z ) 1 coth ( z ) = -------------------tanh ( z ) See Also acot, acoth 2-343 cov Purpose Syntax Description 2cov Covariance matrix C = cov(X) C = cov(x,y) C = cov(x) where x is a vector returns the variance of the vector elements. For matrices where each row is an observation and each column a variable, cov(x) is the covariance matrix. diag(cov(x)) is a vector of variances for each column, and sqrt(diag(cov(x))) is a vector of standard deviations. C = cov(x,y), where x and y are column vectors of equal length, is equivalent to cov([x y]). Remarks cov removes the mean from each column before calculating the result. The covariance function is defined as cov ( x 1 ,x 2 ) = E [ ( x 1 1 ) ( x 2 2 ) ] where E is the mathematical expectation and i = Ex i . Examples Consider A = [-1 1 2 ; -2 3 1 ; 4 0 3]. To obtain a vector of variances for each column of A: v = diag(cov(A))' v = 10.3333 2.3333 1.0000 Compare vector v with covariance matrix C: C = 10.3333 -4.1667 3.0000 -4.1667 2.3333 -1.5000 3.0000 -1.5000 1.0000 The diagonal elements C(i,i) represent the variances for the columns of A. The off-diagonal elements C(i,j) represent the covariances of columns i and j. See Also corrcoef, mean, std xcorr, xcov in the Signal Processing Toolbox 2-344 cplxpair Purpose Syntax 2cplxpair Sort complex numbers into complex conjugate pairs B B B B = = = = cplxpair(A) cplxpair(A,tol) cplxpair(A,[],dim) cplxpair(A,tol,dim) Description B = cplxpair(A) sorts the elements along different dimensions of a complex array, grouping together complex conjugate pairs. The conjugate pairs are ordered by increasing real part. Within a pair, the element with negative imaginary part comes first. The purely real values are returned following all the complex pairs. The complex conjugate pairs are forced to be exact complex conjugates. A default tolerance of 100*eps relative to abs(A(i)) determines which numbers are real and which elements are paired complex conjugates. If A is a vector, cplxpair(A) returns A with complex conjugate pairs grouped together. If A is a matrix, cplxpair(A) returns A with its columns sorted and complex conjugates paired. If A is a multidimensional array, cplxpair(A) treats the values along the first non-singleton dimension as vectors, returning an array of sorted elements. B = cplxpair(A,tol) overrides the default tolerance. B = cplxpair(A,[],dim) sorts A along the dimension specified by scalar dim. B = cplxpair(A,tol,dim) sorts A along the specified dimension and overrides the default tolerance. Diagnostics If there are an odd number of complex numbers, or if the complex numbers cannot be grouped into complex conjugate pairs within the tolerance, cplxpair generates the error message Complex numbers can't be paired. 2-345 cputime Purpose Syntax Description 2cputime Elapsed CPU time cputime cputime returns the total CPU time (in seconds) used by MATLAB from the time it was started. This number can overflow the internal representation and wrap around. Examples The following code returns the CPU time used to run surf(peaks(40)). t = cputime; surf(peaks(40)); e = cputime-t e = 0.4667 See Also clock, etime, tic, toc 2-346 cross Purpose Syntax Description 2cross Vector cross product C = cross(A,B) C = cross(A,B,dim) C = cross(A,B) returns the cross product of the vectors A and B. That is, C = A x B. A and B must be 3-element vectors. If A and B are multidimensional arrays, cross returns the cross product of A and B along the first dimension of length 3. C = cross(A,B,dim) where A and B are multidimensional arrays, returns the cross product of A and B in dimension dim . A and B must have the same size, and both size(A,dim) and size(B,dim) must be 3. Remarks Examples To perform a dot (scalar) product of two vectors of the same size, use c = dot(a,b). The cross and dot products of two vectors are calculated as shown: a = [1 2 3]; b = [4 5 6]; c = cross(a,b) c = -3 d = dot(a,b) d = 32 6 -3 See Also dot 2-347 csc, csch Purpose Syntax Description 2csc, csch Cosecant and hyperbolic cosecant Y = csc(x) Y = csch(x) The csc and csch functions operate element-wise on arrays. The functions domains and ranges include complex values. All angles are in radians. Y = csc(x) returns the cosecant for each element of x. Y = csch(x) returns the hyperbolic cosecant for each element of x. Examples Graph the cosecant and hyperbolic cosecant over the domains < x < 0 and 0< x< . x1 = -pi+0.01:0.01:-0.01; x2 = 0.01:0.01:pi-0.01; plot(x1,csc(x1),x2,csc(x2)) plot(x1,csch(x1),x2,csch(x2)) 150 100 80 100 60 40 50 20 y=csch(x) y=csc(x) 0 0 -20 -50 -40 -60 -100 -80 -150 -4 -100 -4 -3 -2 -1 0 x1,x2 1 2 3 4 -3 -2 -1 0 x1,x2 1 2 3 4 2-348 csc, csch Algorithm csc and csch use these algorithms. 1 csc ( z ) = ---------------sin ( z ) 1 csch ( z ) = ------------------sinh ( z ) See Also acsc, acsch 2-349 csvread Purpose Syntax 2csvread Read a comma-separated value file M = csvread('filename') M = csvread('filename',row,col) M = csvread('filename',row,col,range) M = csvread('filename') reads a comma-separated value formatted file, filename. The result is returned in M. The file can only contain numeric values. M = csvread('filename',row,col) reads data from the comma-separated Description value formatted file starting at the specified row and column. The row and column arguments are zero-based, so that row=0 and col=0 specifies the first value in the file. M = csvread('filename',row,col,range) reads only the range specified. Specify the range using the notation, [R1 C1 R2 C2] where (R1,C1) is the upper-left corner of the data to be read and (R2,C2) is the lower-right corner. The range can also be specified using spreadsheet notation as in range = 'A1..B7'. Remarks csvread fills empty delimited fields with zero. Data files having lines that end with a nonspace delimiter, such as a semicolon, produce a result that has an additional last column of zeros. Examples Given the file, csvlist.dat that contains the comma-separated values 02, 03, 05, 07, 11, 04, 06, 10, 14, 22, 06, 09, 15, 21, 33, 08, 12, 20, 28, 44, 10, 15, 25, 35, 55, 12 18 30 42 66 To read the entire file, use csvread('csvlist.dat') ans = 2 3 4 6 6 9 8 12 10 15 12 18 2-350 csvread 5 7 11 10 14 22 15 21 33 20 28 44 25 35 55 30 42 66 To read the matrix starting with zero-based row 2, column 0 and assign it to the variable, m, m = csvread('csvlist.dat', 2, 0) m = 5 7 11 10 14 22 15 21 33 20 28 44 25 35 55 30 42 66 To read the matrix bounded by zero-based (2,0) and (3,3) and assign it to m, m = csvread('csvlist.dat', 2, 0, [2,0,3,3]) m = 5 7 10 14 15 21 20 28 See Also csvwrite, dlmread, textread, wk1read, file formats, importdata, uiimport 2-351 csvwrite Purpose Syntax Description 2csvwrite Write a comma-separated value file csvwrite('filename',M) csvwrite('filename',M,row,col) csvwrite('filename',M) writes matrix M into filename as comma-separated values. csvwrite('filename',M,row,col) writes matrix M into filename starting at the specified row and column offset. The row and column arguments are zero-based, so that row=0 and C=0 specifies the first value in the file. Examples The following example creates a comma-separated value file from the matrix, m. m = [3 6 9 12 15; 5 10 15 20 25; 7 14 21 28 35; 11 22 33 44 55]; csvwrite('csvlist.dat',m) type csvlist.dat 3,6,9,12,15 5,10,15,20,25 7,14,21,28,35 11,22,33,44,55 The next example writes the matrix to the file, starting at a column offset of 2. csvwrite('csvlist.dat',m,0,2) type csvlist.dat ,,3,6,9,12,15 ,,5,10,15,20,25 ,,7,14,21,28,35 ,,11,22,33,44,55 See Also csvread, dlmwrite, textread, wk1write, file formats, importdata, uiimport 2-352 cumprod Purpose Syntax Description 2cumprod Cumulative product B = cumprod(A) B = cumprod(A,dim) B = cumprod(A) returns the cumulative product along different dimensions of an array. If A is a vector, cumprod(A) returns a vector containing the cumulative product of the elements of A. If A is a matrix, cumprod(A) returns a matrix the same size as A containing the cumulative products for each column of A. If A is a multidimensional array, cumprod(A) works on the first nonsingleton dimension. B = cumprod(A,dim) returns the cumulative product of the elements along the dimension of A specified by scalar dim. For example, cumprod(A,1) increments the first (row) index, thus working along the rows of A. Examples cumprod(1:5) ans = 1 2 6 24 120 A = [1 2 3; 4 5 6]; cumprod(A) ans = 1 2 4 10 cumprod(A,2) ans = 1 2 4 20 3 18 6 120 See Also cumsum, prod, sum 2-353 cumsum Purpose Syntax Description 2cumsum Cumulative sum B = cumsum(A) B = cumsum(A,dim) B = cumsum(A) returns the cumulative sum along different dimensions of an array. If A is a vector, cumsum(A) returns a vector containing the cumulative sum of the elements of A. If A is a matrix, cumsum(A) returns a matrix the same size as A containing the cumulative sums for each column of A. If A is a multidimensional array, cumsum(A) works on the first nonsingleton dimension. B = cumsum(A,dim) returns the cumulative sum of the elements along the dimension of A specified by scalar dim. For example, cumsum(A,1) works across the first dimension (the rows). Examples cumsum(1:5) ans = [1 3 6 10 15] A = [1 2 3; 4 5 6]; cumsum(A) ans = 1 5 cumsum(A,2) ans = 1 4 2 7 3 9 3 9 6 15 See Also cumprod, prod, sum 2-354 cumtrapz Purpose Syntax 2cumtrapz Cumulative trapezoidal numerical integration Z = cumtrapz(Y) Z = cumtrapz(X,Y) Z = cumtrapz(... dim) Z = cumtrapz(Y) computes an approximation of the cumulative integral of Y Description via the trapezoidal method with unit spacing. To compute the integral with other than unit spacing, multiply Z by the spacing increment. For vectors, cumtrapz(Y) is a vector containing the cumulative integral of Y. For matrices, cumtrapz(Y) is a matrix the same size as Y with the cumulative integral over each column. For multidimensional arrays, cumtrapz(Y) works across the first nonsingleton dimension. Z = cumtrapz(X,Y) computes the cumulative integral of Y with respect to X using trapezoidal integration. X and Y must be vectors of the same length, or X must be a column vector and Y an array whose first nonsingleton dimension is length(X). cumtrapz operates across this dimension. If X is a column vector and Y an array whose first nonsingleton dimension is length(X), cumtrapz(X,Y) operates across this dimension. Z = cumtrapz(X,Y,dim) or cumtrapz(Y,DIM) integrates across the dimension of Y specified by scalar dim. The length of X must be the same as size(Y,dim). Example Y = [0 1 2; 3 4 5]; cumtrapz(Y,1) ans = 0 0 1.5000 2.5000 cumtrapz(Y,2) ans = 0 0.5000 0 3.5000 0 3.5000 2.0000 8.0000 2-355 cumtrapz See Also cumsum, trapz 2-356 curl Purpose Syntax 2curl Computes the curl and angular velocity of a vector field [curlx,curly,curlz,cav] = curl(X,Y,Z,U,V,W) [curlx,curly,curlz,cav] = curl(U,V,W) [curlz,cav]= curl(X,Y,U,V) [curlz,cav]= curl(U,V) [curlx,curly,curlz] = curl(...), [curlx,curly] = curl(...) cav = curl(...) [curlx,curly,curlz,cav] = curl(X,Y,Z,U,V,W) computes the curl and angular velocity perpendicular to the flow (in radians per time unit) of a 3-D vector field U, V, W. The arrays X, Y, Z define the coordinates for U, V, W and must be monotonic and 3-D plaid (as if produced by meshgrid). [curlx,curly,curlz,cav] = curl(U,V,W) assumes X, Y, and Z are Description determined by the expression: [X Y Z] = meshgrid(1:n,1:m,1:p) where [m,n,p] = size(U). [curlz,cav]= curl(X,Y,U,V) computes the curl z-component and the angular velocity perpendicular to z (in radians per time unit) of a 2-D vector field U, V. The arrays X, Y define the coordinates for U, V and must be monotonic and 2-D plaid (as if produced by meshgrid). [curlz,cav]= curl(U,V) assumes X and Y are determined by the expression: [X Y] = meshgrid(1:n,1:m) where [m,n] = size(U). [curlx,curly,curlz] = curl(...), curlx,curly] = curl(...) returns only the curl. cav = curl(...) returns only the curl angular velocity. Examples This example uses colored slice planes to display the curl angular velocity at specified locations in the vector field. 2-357 curl load wind cav = curl(x,y,z,u,v,w); slice(x,y,z,cav,[90 134],[59],[0]); shading interp daspect([1 1 1]); axis tight colormap hot(16) camlight This example views the curl angular velocity in one plane of the volume and plots the velocity vectors (quiver) in the same plane. load wind k = 4; x = x(:,:,k); y = y(:,:,k); u = u(:,:,k); v = v(:,:,k); cav = curl(x,y,u,v); pcolor(x,y,cav); shading interp hold on; quiver(x,y,u,v,'y') hold off colormap copper 2-358 curl See Also streamribbon, divergence 2-359 customverctrl Purpose Syntax Description 2customverctrl Allow custom source control system customverctrl(filename, arguments) This function is supplied for customers who want to integrate a version control system that is not supported with MATLAB. This function must conform to the structure of one of the supported version control systems, for example RCS. See the files clearcase.m, pvcs.m, rcs.m, and sourcesafe.m in $matlabroot\toolbox\matlab\verctrl as examples. checkin, checkout, cmopts, undocheckout See Also 2-360 cylinder Purpose Syntax 2cylinder Generate cylinder [X,Y,Z] = cylinder [X,Y,Z] = cylinder(r) [X,Y,Z] = cylinder(r,n) cylinder(...) cylinder generates x, y, and z coordinates of a unit cylinder. You can draw the cylindrical object using surf or mesh, or draw it immediately by not providing Description output arguments. [X,Y,Z] = cylinder returns the x, y, and z coordinates of a cylinder with a radius equal to 1. The cylinder has 20 equally spaced points around its circumference. [X,Y,Z] = cylinder(r) returns the x, y, and z coordinates of a cylinder using r to define a profile curve. cylinder treats each element in r as a radius at equally spaced heights along the unit height of the cylinder. The cylinder has 20 equally spaced points around its circumference. [X,Y,Z] = cylinder(r,n) returns the x, y, and z coordinates of a cylinder based on the profile curve defined by vector r. The cylinder has n equally spaced points around its circumference. cylinder(...), with no output arguments, plots the cylinder using surf. Remarks cylinder treats its first argument as a profile curve. The resulting surface graphics object is generated by rotating the curve about the x-axis, and then aligning it with the z-axis. Examples Create a cylinder with randomly colored faces. cylinder axis square h = findobj('Type','surface'); 2-361 cylinder set(h,'CData',rand(size(get(h,'CData')))) 1 0.8 0.6 0.4 0.2 0 1 0.5 0 0 0.5 1 1 0.5 0.5 1 Generate a cylinder defined by the profile function 2+sin(t). t = 0:pi/10:2*pi; [X,Y,Z] = cylinder(2+cos(t)); surf(X,Y,Z) axis square 2-362 cylinder 1 0.8 0.6 0.4 0.2 0 4 2 0 0 2 4 4 2 2 4 See Also sphere, surf 2-363 daspect Purpose Syntax 2daspect Set or query the axes data aspect ratio daspect daspect([aspect_ratio]) daspect('mode') daspect('auto') daspect('manual') daspect(axes_handle,...) Description The data aspect ratio determines the relative scaling of the data units along the x-, y-, and z-axes. daspect with no arguments returns the data aspect ratio of the current axes. daspect([aspect_ratio]) sets the data aspect ratio in the current axes to the specified value. Specify the aspect ratio as three relative values representing the ratio of the x-, y-, and z-axis scaling (e.g., [1 1 3] means one unit in x is equal in length to one unit in y and three unit in z). daspect('mode') returns the current value of the data aspect ratio mode, which can be either auto (the default) or manual. See Remarks. daspect('auto') sets the data aspect ratio mode to auto. daspect('manual') sets the data aspect ratio mode to manual. daspect(axes_handle,...) performs the set or query on the axes identified by the first argument, axes_handle. When you do not specify an axes handle, daspect operates on the current axes. Remarks daspect sets or queries values of the axes object DataAspectRatio and DataAspectRatioMode properties. When the data aspect ratio mode is auto, MATLAB adjusts the data aspect ratio so that each axis spans the space available in the figure window. If you are displaying a representation of a real-life object, you should set the data aspect ratio to [1 1 1] to produce the correct proportions. Setting a value for data aspect ratio or setting the data aspect ratio mode to manual disables MATLAB s stretch-to-fill feature (stretching of the axes to fit 2-364 daspect the window). This means setting the data aspect ratio to a value, including its current value, daspect(daspect) can cause a change in the way the graphs look. See the Remarks section of the axes description for more information. Examples The following surface plot of the function z = xe ( x y ) is useful to illustrate the data aspect ratio. First plot the function over the range 2 x 2, 2 y 2, 2 2 [x,y] = meshgrid([-2:.2:2]); z = x.*exp(-x.^2 - y.^2); surf(x,y,z) 0.5 0 0.5 2 1 0 1 2 2 0 1 1 2 Querying the data aspect ratio shows how MATLAB has drawn the surface. daspect ans = 4 4 1 Setting the data aspect ratio to [1 1 1] produces a surface plot with equal scaling along each axis. 2-365 daspect 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 See Also axis, pbaspect, xlim, ylim, zlim The axes properties DataAspectRatio, PlotBoxAspectRatio, XLim, YLim, ZLim The discussion of axes aspect ratio in Visualization Techniques. 2-366 date Purpose Syntax Description See Also 2date Current date string str = date str = date returns a string containing the date in dd-mmm-yyyy format. clock, datenum, now 2-367 datenum Purpose Syntax 2datenum Serial date number N N N N = = = = datenum(DT) datenum(DT,P) datenum(Y,M,D) datenum(Y,M,D,H,MI,S) Description The datenum function converts date strings and date vectors (defined by datevec) into serial date numbers. Date numbers are serial days elapsed from some reference date. By default, the serial day 1 corresponds to 1-Jan-0000. N = datenum(DT) converts the date string or date vector DT into a serial date number. Date strings with two-character years, e.g., 12-june-12, are assumed to lie within the 100-year period centered about the current year. Note If DT is a string, it must be in one of the date formats 0, 1, 2, 6, 13, 14, 15, or 16 as de ned by datestr. N = datenum(DT,P) uses the specified pivot year as the starting year of the 100-year range in which a two-character year resides. The default pivot year is the current year minus 50 years. N = datenum(Y,M,D) returns the serial date number for corresponding elements of the Y, M, and D (year, month, day) arrays. Y, M, and D must be arrays of the same size (or any can be a scalar). Values outside the normal range of each array are automatically carried to the next unit. N = datenum(Y,M,D,H,MI,S) returns the serial date number for corresponding elements of the Y, M, D, H, MI, and S (year, month, hour, minute, and second) array values. Y, M, D, H, MI, and S must be arrays of the same size (or any can be a scalar). 2-368 datenum Examples Convert a date string to a serial date number. n = datenum('19-May-1995') n = 728798 Specifying year, month, and day, convert a date to a serial date number. n = datenum(1994,12,19) n = 728647 Convert a date string to a serial date number using the default pivot year n = datenum('12-june-12') n = 735032 Convert the same date string to a serial date number using 1900 as the pivot year. n = datenum('12-june-12', 1900) n = 698507 See Also datestr, datevec, now 2-369 datestr Purpose Syntax Description 2datestr Date string format str = datestr(DT,dateform) str = datestr(DT,dateform,P) The datestr function converts serial date numbers (defined by datenum) and date vectors (defined by datevec) into date strings. str = datestr(DT,dateform) converts a single date vector, or each element of an array of serial date numbers to a date string. Date strings with two-character years, e.g., 12-june-12, are assumed to lie within the 100-year period centered about the current year. str = datestr(DT,dateform,P) uses the specified pivot year as the starting year of the 100-year range in which a two-character year resides. The default pivot year is the current year minus 50 years. The optional argument dateform specifies the date format of the result. dateform can be either a number or a string: dateform (number) 0 1 2 3 4 5 6 7 8 9 10 dateform (string) 'dd-mmm-yyyy HH:MM:SS' 'dd-mmm-yyyy' 'mm/dd/yy' 'mmm' 'm' 'mm' 'mm/dd' 'dd' 'ddd' 'd' 'yyyy' Example 01-Mar-2000 15:45:17 01-Mar-2000 03/01/00 Mar M 03 03/01 01 Wed W 2000 2-370 datestr dateform (number) 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 (ISO 8601) 30 (ISO 8601) 31 dateform (string) 'yy' 'mmmyy' 'HH:MM:SS' 'HH:MM:SS PM' 'HH:MM' 'HH:MM PM' 'QQ-YY' 'QQ' 'dd/mm' 'dd/mm/yy' 'mmm.dd.yyyy HH:MM:SS' 'mmm.dd.yyyy' 'mm/dd/yyyy' 'dd/mm/yyyy' 'yy/mm/dd' 'yyyy/mm/dd' 'QQ-YYYY 'mmmyyyy' 'yyyy-mm-dd' 'yyyymmddTHHMMSS' 'yyyy-mm-dd HH:MM:SS' Example 00 Mar00 15:45:17 3:45:17 PM 15:45 3:45 PM Q1-01 Q1 01/03 01/03/00 Mar.01,2000 15:45:17 Mar.01.2000 03/01/2000 01/03/2000 00/03/01 2000/03/01 Q1-2001 Mar2000 2000-03-01 20000301T154517 2000-03-01 15:45:17 2-371 datestr NOTE dateform numbers 0, 1, 2, 6, 13, 14, 15, 16, and 23 produce a string suitable for input to datenum or datevec. Other date string formats will not work with these functions. Time formats like 'h:m:s', 'h:m:s.s', 'h:m pm', ... may also be part of the input array DT. If you do not specify dateform, or if you specify dateform as -1, the date string format defaults to 1 16 0 if DT contains date information only (01-Mar-1995) if DT contains time information only (03:45 PM) if DT is a date vector, or a string that contains both date and time information (01-Mar-1995 03:45) See Also date, datetick, datenum, datevec 2-372 datetick Purpose Syntax Description 2datetick Label tick lines using dates datetick(tickaxis) datetick(tickaxis,dateform) datetick(tickaxis) labels the tick lines of an axis using dates, replacing the default numeric labels. tickaxis is the string 'x', 'y', or 'z'. The default is 'x'. datetick selects a label format based on the minimum and maximum limits of the specified axis. datetick(tickaxis,dateform) formats the labels according to the integer dateform (see table). To produce correct results, the data for the specified axis must be serial date numbers (as produced by datenum). dateform (number) 0 1 2 3 4 5 6 7 8 9 10 11 12 13 dateform (string) 'dd-mmm-yyyy HH:MM:SS' 'dd-mmm-yyyy' 'mm/dd/yy' 'mmm' 'm' 'mm' 'mm/dd' 'dd' 'ddd' 'd' 'yyyy' 'yy' 'mmmyy' 'HH:MM:SS' Example 01-Mar-2000 15:45:17 01-Mar-2000 03/01/00 Mar M 03 03/01 01 Wed W 2000 00 Mar00 15:45:17 2-373 datetick dateform (number) 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 dateform (string) 'HH:MM:SS PM' 'HH:MM' 'HH:MM PM' 'QQ-YY' 'QQ' 'dd/mm' 'dd/mm/yy' 'mmm.dd.yyyy HH:MM:SS' 'mmm.dd.yyyy' 'mm/dd/yyyy' 'dd/mm/yyyy' 'yy/mm/dd' 'yyyy/mm/dd' 'QQ-YYYY 'mmmyyyy' Example 3:45:17 PM 15:45 3:45 PM Q1 01 Q1 01/03 01/03/00 Mar.01,2000 15:45:17 Mar.01.2000 03/01/2000 01/03/2000 00/03/01 2000/03/01 Q1-2001 Mar2000 Remarks datetick calls datestr to convert date numbers to date strings. To change the tick spacing and locations, set the appropriate axes property (i.e., XTick, YTick, or ZTick) before calling datetick. Example Consider graphing population data based on the 1990 U.S. census: t = (1900:10:1990)'; % Time interval p = [75.995 91.972 105.711 123.203 131.669 ... 150.697 179.323 203.212 226.505 249.633]'; % Population plot(datenum(t,1,1),p) % Convert years to date numbers and plot grid on 2-374 datetick datetick('x',11) 260 % Replace x-axis ticks with 2-digit year labels 240 220 200 180 160 140 120 100 80 60 00 20 40 60 80 00 See Also The axes properties XTick, YTick, and ZTick. datenum, datestr 2-375 datevec Purpose 2datevec Date components C = datevec(A) C = datevec(A,P) [Y,M,D,H,MI,S] = datevec(A) Description C = datevec(A) splits its input into an n-by-6 array with each row containing the vector [Y,M,D,H,MI,S]. The first five date vector elements are integers. Input A can either consist of strings of the sort produced by the datestr function, or scalars of the sort produced by the datenum and now functions. Date strings with two-character years, e.g., 12-june-12, are assumed to lie within the 100-year period centered about the current year. C = datevec(A,P) uses the specified pivot year as the starting year of the 100-year range in which a two-character year resides. The default pivot year is the current year minus 50 years. [Y,M,D,H,MI,S] = datevec(A) returns the components of the date vector as individual variables. When creating your own date vector, you need not make the components integers. Any components that lie outside their conventional ranges affect the next higher component (so that, for instance, the anomalous June 31 becomes July 1). A zeroth month, with zero days, is allowed. Examples An example of using a string as input: datevec('12/24/1984') ans = 1984 12 24 0 0 0 An example of using a serial date number as input: t = datenum('12/24/1984') t = 725000 datevec(t) 2-376 datevec ans = 1984 12 24 0 0 0 See Also clock, datenum, datestr, now 2-377 dbclear Purpose Graphical Interface Syntax 2dbclear Clear breakpoints As an alternative to the dbclear function, there are various ways to clear breakpoints using the Editor/Debugger. dbclear dbclear dbclear dbclear dbclear dbclear dbclear dbclear dbclear all all in mfile in mfile in mfile at lineno in mfile at subfun if error if warning if naninf if infnan Description dbclear all removes all breakpoints in all M-files, as well as pauses set for error, warning, and naninf/infnan using dbstop. dbclear all in mfile removes breakpoints in mfile. dbclear in mfile removes the breakpoint set at the first executable line in mfile. dbclear in mfile at lineno removes the breakpoint set at the line number lineno in mfile. dbclear in mfile at subfun removes the breakpoint set at the subfunction subfun in mfile. dbclear if error removes the pause set using dbstop if error. dbclear if warning removes the pause set using dbstop if warning. dbclear if naninf removes the pause set using dbstop if naninf. dbclear if infnan removes the pause set using dbstop if infnan. Remarks The at, in, and if keywords, familiar to users of the UNIX debugger dbx, are optional. 2-378 dbclear See Also dbcont, dbdown, dbquit, dbstack, dbstatus, dbstep, dbstop, dbtype, dbup, partialpath 2-379 dbcont Purpose Graphical Interface Syntax Description 2dbcont Resume execution As an alternative to the dbcont function, you can select Continue from the Debug menu in the Editor/Debugger. dbcont dbcont resumes execution of an M-file from a breakpoint. Execution continues until either another breakpoint is encountered, an error occurs, or MATLAB returns to the base workspace prompt. See Also dbclear, dbdown, dbquit, dbstack, dbstatus, dbstep, dbstop, dbtype, dbup 2-380 dbdown Purpose Graphical Interface Syntax Description 2dbdown Change local workspace context As an alternative to the dbdown function, you can select Step In from the Debug menu in the Editor/Debugger. dbdown dbdown changes the current workspace context to the workspace of the called M-file when a breakpoint is encountered. You must have issued the dbup function at least once before you issue this function. dbdown is the opposite of dbup. Multiple dbdown functions change the workspace context to each successively executed M-file on the stack until the current workspace context is the current breakpoint. It is not necessary, however, to move back to the current breakpoint to continue execution or to step to the next line. See Also dbclear, dbcont, dbquit, dbstack, dbstatus, dbstep, dbstop, dbtype, dbup 2-381 dblquad Purpose Syntax 2dblquad Numerically evaluate double integral q q q q = = = = dblquad(fun,xmin,xmax,ymin,ymax) dblquad(fun,xmin,xmax,ymin,ymax,tol) dblquad(fun,xmin,xmax,ymin,ymax,tol,method) dblquad(fun,xmin,xmax,ymin,ymax,tol,method,p1,p2,...) Description q = dblquad(fun,xmin,xmax,ymin,ymax) calls the quad function to evaluate the double integral fun(x,y) over the rectangle xmin <= x <= xmax, ymin <= y <= ymax. fun(x,y) must accept a vector x and a scalar y and return a vector of values of the integrand. q = dblquad(fun,xmin,xmax,ymin,ymax,tol) uses a tolerance tol instead of the default, which is 1.0e-6. q = dblquad(fun,xmin,xmax,ymin,ymax,tol,method) uses the specified quadrature function instead of the default quad. Valid values for method are @quadl or a function handle of a user-defined quadrature method that has the same calling sequence as quad and quadl. dblquad(fun,xmin,xmax,ymin,ymax,tol,method,p1,p2,...) passes the additional parameters p1,p2,... to fun(x,y,p1,p2,...). Use [] as a placeholder if you do not specify tol or method. dblquad(fun,xmin,xmax,ymin,ymax,[],[],p1,p2,...) is the same as dblquad(fun,xmin,xmax,ymin,ymax,1.e-6,@quad,p1,p2,...) Example fun can be an inline object Q = dblquad(inline('y*sin(x)+x*cos(y)'), pi, 2*pi, 0, pi) or a function handle Q = dblquad(@integrnd, pi, 2*pi, 0, pi) where integrnd.m is an M-file. function z = integrnd(x, y) z = y*sin(x)+x*cos(y); 2-382 dblquad The integrnd function integrates y*sin(x)+x*cos(y) over the square pi <= x <= 2*pi, 0 <= y <= pi. Note that the integrand can be evaluated with a vector x and a scalar y . Nonsquare regions can be handled by setting the integrand to zero outside of the region. For example, the volume of a hemisphere is dblquad(inline('sqrt(max(1-(x.^2+y.^2),0))'),-1,1,-1,1) or dblquad(inline('sqrt(1-(x.^2+y.^2)).*(x.^2+y.^2<=1)'),-1,1,-1,1 ) See Also inline, quad, quadl, @ (function handle) 2-383 dbmex Purpose Syntax 2dbmex Enable MEX-file debugging dbmex dbmex dbmex dbmex on off stop print Description dbmex on enables MEX-file debugging for UNIX platforms. It is not supported on the Sun Solaris platform. To use this option, first start MATLAB from within a debugger by typing: matlab -Ddebugger, where debugger is the name of the debugger. dbmex off disables MEX-file debugging. dbmex stop returns to the debugger prompt. dbmex print displays MEX-file debugging information. Remarks On Sun Solaris platforms, dbmex is not supported. See the Technical Support solution 23388 at http://www.mathworks.com/support/solutions/data/ 23388.shtml for an alternative method of debugging. dbclear, dbcont, dbdown, dbquit, dbstack, dbstatus, dbstep, dbstop, dbtype, dbup See Also 2-384 dbquit Purpose Graphical Interface Syntax Description 2dbquit Quit debug mode As an alternative to the dbquit function, you can select Exit Debug Mode from the Debug menu in the Editor/Debugger. dbquit dbquit immediately terminates the debugger and returns control to the base workspace prompt. The M-file being processed is not completed and no results are returned. All breakpoints remain in effect. See Also dbclear, dbcont, dbdown, dbstack, dbstatus, dbstep, dbstop, dbtype, dbup 2-385 dbstack Purpose Graphical Interface Syntax Description 2dbstack Display function call stack As an alternative to the dbstack function, you can use the Stack field in the Editor/Debugger toolbar. dbstack [ST,I] = dbstack dbstack displays the line numbers and M-file names of the function calls that led to the current breakpoint, listed in the order in which they were executed. The line number of the most recently executed function call (at which the current breakpoint occurred) is listed first, followed by its calling function, which is followed by its calling function, and so on, until the topmost M-file function is reached. [ST,I] = dbstack returns the stack trace information in an m-by-1 structure ST with the fields: name line Function name Function line number The current workspace index is returned in I. Examples dbstack In /usr/local/matlab/toolbox/matlab/cond.m at line 13 In test1.m at line 2 In test.m at line 3 See Also dbclear, dbcont, dbdown, dbquit, dbstatus, dbstep, dbstop, dbtype, dbup 2-386 dbstatus Purpose Graphical Interface Syntax 2dbstatus List all breakpoints As an alternative to the dbstatus function, you can see breakpoint icons for a file that is open in the Editor/Debugger. dbstatus dbstatus function s = dbstatus(...) dbstatus lists all breakpoints in effect including error, warning, and naninf. dbstatus function displays a list of the line numbers for which breakpoints Description are set in the specified M-file. s = dbstatus(...) returns the breakpoint information in an m-by-1 structure with the fields: name line cond Function name Function line number Condition string (error, warning, or naninf) Use dbstatus class/function or dbstatus private/function or dbstatus class/private/function to determine the status for methods, private functions, or private methods (for a class named class). In all of these forms you can further qualify the function name with a subfunction name as in dbstatus function/subfunction. See Also dbclear, dbcont, dbdown, dbquit, dbstack, dbstep, dbstop, dbtype, dbup 2-387 dbstep Purpose Graphical Interface Syntax 2dbstep Execute one or more lines from current breakpoint As an alternative to the dbstep function, you can select Step from the Debug menu in the Editor/Debugger. dbstep dbstep nlines dbstep in Description This function allows you to debug an M-file by following its execution from the current breakpoint. At a breakpoint, the dbstep function steps through execution of the current M-file one line at a time or at the rate specified by nlines. dbstep, by itself, executes the next executable line of the current M-file. dbstep steps over the current line, skipping any breakpoints set in functions called by that line. dbstep nlines executes the specified number of executable lines. dbstep in steps to the next executable line. If that line contains a call to another M-file, execution resumes with the first executable line of the called file. If there is no call to an M-file on that line, dbstep in is the same as dbstep. See Also dbclear, dbcont, dbdown, dbquit, dbstack, dbstatus, dbstop, dbtype, dbup 2-388 dbstop Purpose Graphical Interface Syntax 2dbstop Set breakpoints in M-file function As an alternative to the dbstop function, you can use the Breakpoints menu or the breakpoint alley in the Editor/Debugger. dbstop dbstop dbstop dbstop dbstop dbstop dbstop dbstop in in in if if if if if mfile mfile at lineno mfile at subfun error all error warning naninf infnan Description dbstop in mfile temporarily stops execution of mfile when you run it, at the first executable line, putting MATLAB in debug mode. mfile must be in a directory that is on the search path or in the current directory. If you have graphical debugging enabled, the MATLAB Debugger opens with a breakpoint at the first executable line of mfile. You can then use the debugging utilities, review the workspace, or issue any valid MATLAB function. Use dbcont or dbstep to resume execution of mfile. Use dbquit to exit from the Debugger. dbstop in mfile at lineno temporarily stops execution of mfile when you run it, just prior to execution of the line whose number is lineno, putting MATLAB in debug mode. mfile must be in a directory that is on the search path or in the current directory. If you have graphical debugging enabled, the MATLAB Debugger opens mfile with a breakpoint at line lineno. If that line is not executable, execution stops and the breakpoint is set at the next executable line following lineno. When execution stops, you can use the debugging utilities, review the workspace, or issue any valid MATLAB function. Use dbcont or dbstep to resume execution of mfile. Use dbquit to exit from the Debugger. dbstop in mfile at subfun temporarily stops execution of mfile when you run it, just prior to execution of the subfunction subfun, putting MATLAB in debug mode. mfile must be in a directory that is on the search path or in the current directory. If you have graphical debugging enabled, the MATLAB Debugger opens mfile with a breakpoint at the subfunction specified by 2-389 dbstop subfun. You can then use the debugging utilities, review the workspace, or issue any valid MATLAB function. Use dbcont or dbstep to resume execution of mfile. Use dbquit to exit from the Debugger. dbstop if error stops execution when any M-file you subsequently run produces a run-time error, putting MATLAB in debug mode, paused at the line that generated the error. The M-file must be in a directory that is on the search path or in the current directory. It does not include run-time errors that are detected within a try...catch block. You cannot resume execution after an error. Use dbquit to exit from the Debugger. dbstop if all error is the same as dbstop if error, except that it stops execution on any type of run-time error, including errors that are detected within a try...catch block. dbstop if warning stops execution when any M-file you subsequently run produces a run-time warning, putting MATLAB in debug mode, paused at the line that generated the warning. The M-file must be in a directory that is on the search path or in the current directory. Use dbcont or dbstep to resume execution. dbstop if naninf stops execution when any M-file you subsequently run encounters an infinite value (Inf), putting MATLAB in debug mode, paused at the line where Inf was encountered. The M-file must be in a directory that is on the search path or in the current directory. Use dbcont or dbstep to resume execution. Use dbquit to exit from the Debugger. dbstop if infnan stops execution when any M-file you subsequently run encounters a value that is not a number (NaN), putting MATLAB in debug mode, paused at the line where NaN was encountered. The M-file must be in a directory that is on the search path or in the current directory. Use dbcont or dbstep to resume execution. Use dbquit to exit from the Debugger. Remarks The at, in, and if keywords, familiar to users of the UNIX debugger dbx, are optional. 2-390 dbstop Examples The file buggy, used in these examples, consists of three lines. function z = buggy(x) n = length(x); z = (1:n)./x; Example 1 Stop at First Executable Line The statements dbstop in buggy buggy(2:5) stop execution at the first executable line in buggy n = length(x); The function dbstep advances to the next line, at which point, you can examine the value of n. Example 2 Stop if Error Because buggy only works on vectors, it produces an error if the input x is a full matrix. The statements dbstop if error buggy(magic(3)) produce ??? Error using ==> ./ Matrix dimensions must agree. Error in ==> c:\buggy.m On line 3 ==> z = (1:n)./x; K and put MATLAB in debug mode. 2-391 dbstop Example 3 Stop if Inf In buggy, if any of the elements of the input x are zero, a division by zero occurs. The statements dbstop if naninf buggy(0:2) produce Warning: Divide by zero. > In c:\buggy.m at line 3 K and put MATLAB in debug mode. See Also dbclear, dbcont, dbdown, dbquit, dbstack, dbstatus, dbstep, dbtype, dbup, partialpath 2-392 dbtype Purpose Graphical Interface Syntax Description 2dbtype List M-file with line numbers As an alternative to the dbtype function, you can see an M-file with line numbers by opening it in the Editor/Debugger. dbtype function dbtype function start:end dbtype function displays the contents of the specified M-file function with line numbers preceding each line. function must be the name of an M-file function or a MATLABPATH relative partial pathname. dbtype function start:end displays the portion of the file specified by a range of line numbers. See Also dbclear, dbcont, dbdown, dbquit, dbstack, dbstatus, dbstep, dbstop, dbup, partialpath 2-393 dbup Purpose Graphical Interface Syntax Description 2dbup Change local workspace context As an alternative to the dbup function, you can select Step In from the Debug menu in the Editor/Debugger. dbup This function allows you to examine the calling M-file by using any other MATLAB function. In this way, you determine what led to the arguments being passed to the called function. dbup changes the current workspace context (at a breakpoint) to the workspace of the calling M-file. Multiple dbup functions change the workspace context to each previous calling M-file on the stack until the base workspace context is reached. (It is not necessary, however, to move back to the current breakpoint to continue execution or to step to the next line.) See Also dbclear, dbcont, dbdown, dbquit, dbstack, dbstatus, dbstep, dbstop, dbtype 2-394 ddeadv Purpose Syntax 2ddeadv Set up advisory link rc rc rc rc = = = = ddeadv(channel,'item','callback') ddeadv(channel,'item','callback','upmtx') ddeadv(channel,'item','callback','upmtx',format) ddeadv(channel,'item','callback','upmtx',format,timeout) Description ddeadv sets up an advisory link between MATLAB and a server application. When the data identified by the item argument changes, the string specified by the callback argument is passed to the eval function and evaluated. If the advisory link is a hot link, DDE modifies upmtx, the update matrix, to reflect the data in item. If you omit optional arguments that are not at the end of the argument list, you must substitute the empty matrix for the missing argument(s). If successful, ddeadv returns 1 in variable, rc. Otherwise it returns 0. Arguments channel item Conversation channel from ddeinit. String specifying the DDE item name for the advisory link. Changing the data identi ed by item at the server triggers the advisory link. String specifying the callback that is evaluated on update noti cation. Changing the data identi ed by item at the server causes callback to get passed to the eval function to be evaluated. String specifying the name of a matrix that holds data sent with an update noti cation. If upmtx is included, changing item at the server causes upmtx to be updated with the revised data. Specifying upmtx creates a hot link. Omitting upmtx or specifying it as an empty string creates a warm link. If upmtx exists in the workspace, its contents are overwritten. If upmtx does not exist, it is created. callback upmtx (optional) 2-395 ddeadv format (optional) Two-element array specifying the format of the data to be sent on update. The rst element speci es the Windows clipboard format to use for the data. The only currently supported format is cf_text, which corresponds to a value of 1. The second element speci es the type of the resultant matrix. Valid types are numeric (the default, which corresponds to a value of 0) and string (which corresponds to a value of 1). The default format array is [1 0]. Scalar specifying the time-out limit for this operation. timeout is speci ed in milliseconds. (1000 milliseconds = 1 second). If advisory link is not established within timeout milliseconds, the function fails. The default value of timeout is three seconds. timeout (optional) Examples Set up a hot link between a range of cells in Excel (Row 1, Column 1 through Row 5, Column 5) and the matrix x. If successful, display the matrix: rc = ddeadv(channel, 'r1c1:r5c5', 'disp(x)', 'x'); Communication with Excel must have been established previously with a ddeinit command. See Also ddeexec, ddeinit, ddepoke, ddereq, ddeterm, ddeunadv 2-396 ddeexec Purpose Syntax 2ddeexec Send string for execution rc = ddeexec(channel,'command') rc = ddeexec(channel,'command','item') rc = ddeexec(channel,'command','item',timeout) ddeexec sends a string for execution to another application via an established DDE conversation. Specify the string as the command argument. Description If you omit optional arguments that are not at the end of the argument list, you must substitute the empty matrix for the missing argument(s). If successful, ddeexec returns 1 in variable, rc. Otherwise it returns 0. Arguments channel command item Conversation channel from ddeinit. String specifying the command to be executed. String specifying the DDE item name for execution. This argument is not used for many applications. If your application requires this argument, it provides additional information for command. Consult your server documentation for more information. Scalar specifying the time-out limit for this operation. timeout is speci ed in milliseconds. (1000 milliseconds = 1 second). The default value of timeout is three seconds. (optional) timeout (optional) Examples Given the channel assigned to a conversation, send a command to Excel: rc = ddeexec(channel,'[formula.goto("r1c1")]') Communication with Excel must have been established previously with a ddeinit command. See Also ddeadv, ddeinit, ddepoke, ddereq, ddeterm, ddeunadv 2-397 ddeinit Purpose Syntax Description 2ddeinit Initiate DDE conversation channel = ddeinit('service','topic') channel = ddeinit('service','topic') returns a channel handle assigned to the conversation, which is used with other MATLAB DDE functions. 'service' is a string specifying the service or application name for the conversation. 'topic' is a string specifying the topic for the conversation. Examples To initiate a conversation with Excel for the spreadsheet 'stocks.xls': channel = ddeinit('excel','stocks.xls') channel = 0.00 See Also ddeadv, ddeexec, ddepoke, ddereq, ddeterm, ddeunadv 2-398 ddepoke Purpose Syntax 2ddepoke Send data to application rc = ddepoke(channel,'item',data) rc = ddepoke(channel,'item',data,format) rc = ddepoke(channel,'item',data,format,timeout) ddepoke sends data to an application via an established DDE conversation. ddepoke formats the data matrix as follows before sending it to the server Description application: String matrices are converted, element by element, to characters and the resulting character buffer is sent. Numeric matrices are sent as tab-delimited columns and carriage-return, line-feed delimited rows of numbers. Only the real part of nonsparse matrices are sent. If you omit optional arguments that are not at the end of the argument list, you must substitute the empty matrix for the missing argument(s). If successful, ddepoke returns 1 in variable, rc. Otherwise it returns 0. Arguments channel item Conversation channel from ddeinit. String specifying the DDE item for the data sent. Item is the server data entity that is to contain the data sent in the data argument. Matrix containing the data to send. Scalar specifying the format of the data requested. The value indicates the Windows clipboard format to use for the data transfer. The only format currently supported is cf_text, which corresponds to a value of 1. Scalar specifying the time-out limit for this operation. timeout is speci ed in milliseconds. (1000 milliseconds = 1 second). The default value of timeout is three seconds. data format (optional) timeout (optional) Examples Assume that a conversation channel with Excel has previously been established with ddeinit. To send a 5-by-5 identity matrix to Excel, placing the data in Row 1, Column 1 through Row 5, Column 5: 2-399 ddepoke rc = ddepoke(channel, 'r1c1:r5c5', eye(5)); See Also ddeadv, ddeexec, ddeinit, ddereq, ddeterm, ddeunadv 2-400 ddereq Purpose Syntax 2ddereq Request data from application data = ddereq(channel,'item') data = ddereq(channel,'item',format) data = ddereq(channel,'item',format,timeout) ddereq requests data from a server application via an established DDE conversation. ddereq returns a matrix containing the requested data or an Description empty matrix if the function is unsuccessful. If you omit optional arguments that are not at the end of the argument list, you must substitute the empty matrix for the missing argument(s). If successful, ddereq returns a matrix containing the requested data in variable, data. Otherwise, it returns an empty matrix. Arguments channel item format Conversation channel from ddeinit. String specifying the server application's DDE item name for the data requested. Two-element array specifying the format of the data requested. The rst element speci es the Windows clipboard format to use. The only currently supported format is cf_text, which corresponds to a value of 1. The second element speci es the type of the resultant matrix. Valid types are numeric (the default, which corresponds to 0) and string (which corresponds to a value of 1). The default format array is [1 0]. Scalar specifying the time-out limit for this operation. timeout is speci ed in milliseconds. (1000 milliseconds = 1 second). The default value of timeout is three seconds. (optional) timeout (optional) Examples Assume that we have an Excel spreadsheet stocks.xls. This spreadsheet contains the prices of three stocks in row 3 (columns 1 through 3) and the number of shares of these stocks in rows 6 through 8 (column 2). Initiate conversation with Excel with the command: channel = ddeinit('excel','stocks.xls') 2-401 ddereq DDE functions require the rxcy reference style for Excel worksheets. In Excel terminology the prices are in r3c1:r3c3 and the shares in r6c2:r8c2. To request the prices from Excel: prices = ddereq(channel,'r3c1:r3c3') prices = 42.50 15.00 78.88 To request the number of shares of each stock: shares = ddereq(channel, 'r6c2:r8c2') shares = 100.00 500.00 300.00 See Also ddeadv, ddeexec, ddeinit, ddepoke, ddeterm, ddeunadv 2-402 ddeterm Purpose Syntax Description 2ddeterm Terminate DDE conversation rc = ddeterm(channel) rc = ddeterm(channel) accepts a channel handle returned by a previous call to ddeinit that established the DDE conversation. ddeterm terminates this conversation. rc is a return code where 0 indicates failure and 1 indicates success. Examples To close a conversation channel previously opened with ddeinit: rc = ddeterm(channel) rc = 1.00 See Also ddeadv, ddeexec, ddeinit, ddepoke, ddereq, ddeunadv 2-403 ddeunadv Purpose Syntax 2ddeunadv Release advisory link rc = ddeunadv(channel,'item') rc = ddeunadv(channel,'item',format) rc = ddeunadv(channel,'item',format,timeout) ddeunadv releases the advisory link between MATLAB and the server application established by an earlier ddeadv call. The channel, item, and format must be the same as those specified in the call to ddeadv that initiated the link. If you include the timeout argument but accept the default format, you must specify format as an empty matrix. Description If successful, ddeunadv returns 1 in variable, rc. Otherwise it returns 0. Arguments channel item Conversation channel from ddeinit. String specifying the DDE item name for the advisory link. Changing the data identi ed by item at the server triggers the advisory link. Two-element array. This must be the same as the format argument for the corresponding ddeadv call. Scalar specifying the time-out limit for this operation. timeout is speci ed in milliseconds. (1000 milliseconds = 1 second). The default value of timeout is three seconds. format (optional) timeout (optional) Example To release an advisory link established previously with ddeadv: rc = ddeunadv(channel, 'r1c1:r5c5') rc = 1.00 See Also ddeadv, ddeexec, ddeinit, ddepoke, ddereq, ddeterm 2-404 deal Purpose Syntax Description 2deal Deal inputs to outputs [Y1,Y2,Y3,...] = deal(X) [Y1,Y2,Y3,...] = deal(X1,X2,X3,...) [Y1,Y2,Y3,...] = deal(X) copies the single input to all the requested outputs. It is the same as Y1 = X, Y2 = X, Y3 = X, ... [Y1,Y2,Y3,...] = deal(X1,X2,X3,...) is the same as Y1 = X1; Y2 = X2; Y3 = X3; ... Remarks deal is most useful when used with cell arrays and structures via comma separated list expansion. Here are some useful constructions: [S.field] = deal(X) sets all the fields with the name field in the structure array S to the value X. If S doesn't exist, use [S(1:m).field] = deal(X). [X{:}] = deal(A.field) copies the values of the field with name field to the cell array X. If X doesn't exist, use [X{1:m}] = deal(A.field). [Y1,Y2,Y3,...] = deal(X{:}) copies the contents of the cell array X to the separate variables Y1,Y2,Y3,... [Y1,Y2,Y3,...] = deal(S.field) copies the contents of the fields with the name field to separate variables Y1,Y2,Y3,... Examples Use deal to copy the contents of a 4-element cell array into four separate output variables. C = {rand(3) ones(3,1) eye(3) zeros(3,1)}; [a,b,c,d] = deal(C{:}) a = 0.9501 0.2311 0.6068 b = 0.4860 0.8913 0.7621 0.4565 0.0185 0.8214 2-405 deal 1 1 1 c = 1 0 0 d = 0 0 0 Use deal to obtain the contents of all the name fields in a structure array: A.name = 'Pat'; A.number = 176554; A(2).name = 'Tony'; A(2).number = 901325; [name1,name2] = deal(A(:).name) name1 = Pat name2 = Tony 0 1 0 0 0 1 2-406 deblank Purpose Syntax Description 2deblank Strip trailing blanks from the end of a string str = deblank(str) c = deblank(c) str = deblank(str) removes the trailing blanks from the end of a character string str. c = deblank(c), when c is a cell array of strings, applies deblank to each element of c. The deblank function is useful for cleaning up the rows of a character array. Examples A{1,1} A{1,2} A{2,1} A{2,2} A = = = = = 'MATLAB '; 'SIMULINK '; 'Toolboxes '; 'The MathWorks '; 'MATLAB ' 'Toolboxes ' 'SIMULINK ' 'The MathWorks ' deblank(A) ans = 'MATLAB' 'Toolboxes' 'SIMULINK' 'The MathWorks' 2-407 dec2base Purpose Syntax Description 2dec2base Decimal number to base conversion str = dec2base(d,base) str = dec2base(d,base,n) str = dec2base(d,base) converts the nonnegative integer d to the specified base.d must be a nonnegative integer smaller than 2^52, and base must be an integer between 2 and 36. The returned argument str is a string. str = dec2base(d,base,n) produces a representation with at least n digits. Examples See Also The expression dec2base(23,2) converts 2310 to base 2, returning the string '10111'. base2dec 2-408 dec2bin Purpose Syntax Description 2dec2bin Decimal to binary number conversion str = dec2bin(d) str = dec2bin(d,n) str = dec2bin(d) returns the binary representation of d as a string. d must 52 be a nonnegative integer smaller than 2 . str = dec2bin(d,n) produces a binary representation with at least n bits. Examples ans = 10111 See Also bin2dec, dec2hex 2-409 dec2hex Purpose Syntax Description 2dec2hex Decimal to hexadecimal number conversion str = dec2hex(d) str = dec2hex(d,n) str = dec2hex(d) converts the decimal integer d to its hexadecimal representation stored in a MATLAB string. d must be a nonnegative integer 52 smaller than 2 . str = dec2hex(d,n) produces a hexadecimal representation with at least n digits. Examples To convert decimal 1023 to hexadecimal, dec2hex(1023) ans = 3FF See Also dec2bin, format, hex2dec, hex2num 2-410 deconv Purpose Syntax Description 2deconv Deconvolution and polynomial division [q,r] = deconv(v,u) [q,r] = deconv(v,u) deconvolves vector u out of vector v, using long division. The quotient is returned in vector q and the remainder in vector r such that v = conv(u,q)+r. If u and v are vectors of polynomial coefficients, convolving them is equivalent to multiplying the two polynomials, and deconvolution is polynomial division. The result of dividing v by u is quotient q and remainder r. Examples If u = [1 v = [10 2 20 3 4] 30] the convolution is c = conv(u,v) c = 10 40 100 160 170 120 Use deconvolution to recover u: [q,r] = deconv(c,u) q = 10 20 30 r = 0 0 0 0 0 0 This gives a quotient equal to v and a zero remainder. Algorithm See Also deconv uses the filter primitive. conv, residue 2-411 default4 Purpose Syntax Description 2default4 MATLAB Version 4.0 figure and axes defaults default4 default4(h) default4 sets figure and axes defaults to match MATLAB Version 4.0 defaults. default4(h) only affects the figure with handle h. See Also colordef 2-412 del2 Purpose Syntax 2del2 Discrete Laplacian L L L L = = = = del2(U) del2(U,h) del2(U,hx,hy) del2(U,hx,hy,hz,...) De nition If the matrix U is regarded as a function u ( x, y ) evaluated at the point on a square grid, then 4*del2(U) is a finite difference approximation of Laplace s differential operator applied to u , that is: 2 2 2 u 1 d u d u - l = ---------- = -- --------- + --------- 4 4 dx 2 d y 2 where: 1 l ij = -- ( u i + 1, j + u i 1, j + u i, 4 j+1 + u i, j 1 ) u i, in the interior. On the edges, the same formula is applied to a cubic extrapolation. For functions of more variables u ( x, y, z, ) , del2(U) is an approximation, 2 2 2 2 u 1 d u d u d u l = ---------- = -------- --------- + --------- + --------- + 2 N 2 N dx 2 d y 2 dz 2 where N is the number of variables in u . Description L = del2(U) where U is a rectangular array is a discrete approximation of 2 2 2 u 1 d u d u - l = ---------- = -- --------- + --------- 4 4 dx 2 d y 2 The matrix L is the same size as U with each element equal to the difference between an element of U and the average of its four neighbors. 2-413 del2 -L = del2(U) when U is an multidimensional array, returns an approximation of u ---------2N where N is ndims(u). L = del2(U,h) where H is a scalar uses H as the spacing between points in each direction (h=1 by default). L = del2(U,hx,hy) when U is a rectangular array, uses the spacing specified by hx and hy. If hx is a scalar, it gives the spacing between points in the x-direction. If hx is a vector, it must be of length size(u,2) and specifies the x-coordinates of the points. Similarly, if hy is a scalar, it gives the spacing between points in the y-direction. If hy is a vector, it must be of length size(u,1) and specifies the y-coordinates of the points. L = del2(U,hx,hy,hz,...) where U is multidimensional uses the spacing given by hx, hy, hz, ... 2 Examples The function u ( x, y ) = x 2 + y 2 has 2u = 4 For this function, 4*del2(U) is also 4. [x,y] = meshgrid(-4:4,-3:3); U = x.*x+y.*y U = 25 18 13 10 20 13 8 5 17 10 5 2 16 9 4 1 17 10 5 2 20 13 8 5 25 18 13 10 9 4 1 0 1 4 9 10 5 2 1 2 5 10 13 8 5 4 5 8 13 18 13 10 9 10 13 18 25 20 17 16 17 20 25 2-414 del2 V = 4*del2(U) V = 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 See Also diff, gradient 2-415 delaunay Purpose Syntax De nition 2delaunay Delaunay triangulation TRI = delaunay(x,y) Given a set of data points, the Delaunay triangulation is a set of lines connecting each point to its natural neighbors. The Delaunay triangulation is related to the Voronoi diagram the circle circumscribed about a Delaunay triangle has its center at the vertex of a Voronoi polygon. x Delaunay triangle Voronoi polygon Description TRI = delaunay(x,y) for the data points defined by vectors x and y, returns a set of triangles such that no data points are contained in any triangle's circumscribed circle. Each row of the m-by-3 matrix TRI defines one such triangle and contains indices into x and y. If the original data points are collinear or x is empty, the triangles cannot be computed and delaunay returns an empty matrix. Remarks The Delaunay triangulation is used by: griddata (to interpolate scattered data), voronoi (to compute the voronoi diagram), and is useful by itself to create a triangular grid for scattered data points. The functions dsearch and tsearch search the triangulation to find nearest neighbor points or enclosing triangles, respectively. Note delaunay is based on qhull [2]. For information about qhull, see http://www.geom.umn.edu/software/qhull/. For copyright information, see http://www.geom.umn.edu/software/download/COPYING.html. 2-416 delaunay Visualization Use one of these functions to plot the output of delaunay: triplot trisurf Displays the triangles de ned in the m-by-3 matrix TRI. See Example 1. Displays each triangle de ned in the m-by-3 matrix TRI as a surface in 3-D space. To see a 2-D surface, you can supply a vector of some constant value for the third dimension. For example trisurf(TRI,x,y,zeros(size(x))) See Example 2. trimesh Displays each triangle de ned in the m-by-3 matrix TRI as a mesh in 3-D space. To see a 2-D surface, you can supply a vector of some constant value for the third dimension. For example, trimesh(TRI,x,y,zeros(size(x))) produces almost the same result as triplot, except in 3-D space. See Example 2. Examples Example 1. Plot the Delaunay triangulation for 10 randomly generated points. rand('state',0); x = rand(1,10); y = rand(1,10); TRI = delaunay(x,y); subplot(1,2,1),... triplot(TRI,x,y) axis([0 1 0 1]); hold on; plot(x,y,'or'); hold off Compare the Voronoi diagram of the same points: [vx, vy] = voronoi(x,y,TRI); subplot(1,2,2),... plot(x,y,'r+',vx,vy,'b-'),... axis([0 1 0 1]) 2-417 delaunay 1 1 0.9 0.9 0.8 0.8 Delaunay triangulation 0.7 0.7 0.6 0.6 Voronoi diagram 0.5 0.5 0.4 0.4 0.3 0.3 0.2 0.2 0.1 0.1 0 0 0.2 0.4 0.6 0.8 1 0 0 0.2 0.4 0.6 0.8 1 Example 2. Create a 2-D grid then use trisurf to plot its Delaunay triangulation in 3-D space by using 0s for the third dimension. [x,y] = meshgrid(1:15,1:15); tri = delaunay(x,y); trisurf(tri,x,y,zeros(size(x))) 2-418 delaunay 1 0.5 0 0.5 1 15 10 10 5 0 0 5 15 Next, generate peaks data as a 15-by-15 matrix, and use that data with the Delaunay triangulation to produce a surface in 3-D space. z = peaks(15); trisurf(tri,x,y,z) 10 5 0 5 10 15 10 10 5 0 0 5 15 2-419 delaunay You can use the same data with trimesh to produce a mesh in 3-D space. trimesh(tri,x,y,z) 10 5 0 5 10 15 10 10 5 0 0 5 15 See Also References delaunay3, delaunayn, dsearch, griddata, plot, triplot, trimesh, trisurf, tsearch, voronoi [1] Barber, C. B., D.P. Dobkin, and H.T. Huhdanpaa, "The Quickhull Algorithm for Convex Hulls," ACM Transactions on Mathematical Software, Vol. 22, No. 4, Dec. 1996, p. 469-483. Available in HTML format at http://www.acm.org/ pubs/citations/journals/toms/1996-22-4/p469-barber/ and in PostScript format at ftp://geom.umn.edu/pub/software/qhull-96.ps. [2] National Science and Technology Research Center for Computation and Visualization of Geometric Structures (The Geometry Center), University of Minnesota. 1993. 2-420 delaunay3 Purpose Syntax Description 2delaunay3 3-D Delaunay tessellation TES = delaunay3(x,y,z) TES = delaunay3(x,y,z) returns an array TES, each row of which contains the indices of the points in (x,y,z) that make up a tetrahedron in the tessellation of (x,y,z). TES is a numtes-by-4 array where numtes is the number of facets in the tessellation. x, y, and z are vectors of equal length. If the original data points are collinear or x, y, and z define an insufficient number of points, the triangles cannot be computed and delaunay3 returns an empty matrix. Note delaunay3 is based on qhull [2]. For information about qhull, see http://www.geom.umn.edu/software/qhull/. For copyright information, see http://www.geom.umn.edu/software/download/COPYING.html. Visualization Use tetramesh to plot delaunay3 output. tetramesh displays the tetrahedrons defined in TES as mesh. tetramesh uses the default tranparency parameter value 'FaceAlpha' = 0.9. This example generates a 3-D Delaunay tessellation, then uses tetramesh to plot the tetrahedrons that form the corresponding simplex. camorbit rotates the camera position to provide a meaningful view of the figure. d = [-1 1]; [x,y,z] = meshgrid(d,d,d); % A cube x = [x(:);0]; y = [y(:);0]; z = [z(:);0]; % [x,y,z] are corners of a cube plus the center. Tes = delaunay3(x,y,z) Tes = 9 1 1 4 7 9 2 9 3 3 9 7 5 5 5 3 Example 2-421 delaunay3 4 4 4 6 6 6 6 6 9 1 1 2 9 9 4 4 7 9 2 9 7 7 9 2 8 3 9 5 5 8 8 9 X = [x(:) y(:) z(:)]; tetramesh(Tes,X);camorbit(20,0) See Also Reference delaunay, delaunayn [1] Barber, C. B., D.P. Dobkin, and H.T. Huhdanpaa, "The Quickhull Algorithm for Convex Hulls," ACM Transactions on Mathematical Software, Vol. 22, No. 4, Dec. 1996, p. 469-483. Available in HTML format at http://www.acm.org/ pubs/citations/journals/toms/1996-22-4/p469-barber/ and in PostScript format at ftp://geom.umn.edu/pub/software/qhull-96.ps. 2-422 delaunay3 [2] National Science and Technology Research Center for Computation and Visualization of Geometric Structures (The Geometry Center), University of Minnesota. 1993. 2-423 delaunayn Purpose Syntax Description 2delaunayn n-D Delaunay tessellation T = delaunayn(X) T = delaunayn(X) computes a set of simplices such that no data points of X are contained in any circumspheres of the simplices. The set of simplices forms the Delaunay tessellation. X is an m-by-n array representing m points in n-D space. T is a numt-by-(n+1) array where each row contains the indices into X of the vertices of the corresponding simplex. Note delaunayn is based on qhull [2]. For information about qhull, see http://www.geom.umn.edu/software/qhull/. For copyright information, see http://www.geom.umn.edu/software/download/COPYING.html. Visualization Plotting the output of delaunayn depends of the value of n: For n = 2, use triplot, trisurf, or trimesh as you would for delaunay. For n = 3, use tetramesh as you would for delaunay3. For more control over the color of the facets, use patch to plot the output. For an example, see Tessellation and Interpolation of Scattered Data in Higher Dimensions in the MATLAB documentation. You cannot plot delaunayn output for n > 3. Example This example generates an n-D Delaunay tessellation, where n = 3. d = [-1 1]; [x,y,z] = meshgrid(d,d,d); % A cube x = [x(:);0]; y = [y(:);0]; z = [z(:);0]; % [x,y,z] are corners of a cube plus the center. X = [x(:) y(:) z(:)]; Tes = delaunayn(X) Tes = 9 1 5 6 2-424 delaunayn 3 2 2 2 7 7 8 8 8 8 8 9 9 3 3 9 3 7 2 2 3 7 1 1 9 9 5 9 9 9 9 9 3 5 6 4 1 6 5 6 6 4 4 9 You can use tetramesh to visualize the tetrahedrons that form the corresponding simplex. camorbit rotates the camera position to provide a meaningful view of the figure. tetramesh(Tes,X);camorbit(20,0) See Also convhulln, delaunayn, delaunay3, tetramesh, voronoin 2-425 delaunayn Reference [1] Barber, C. B., D.P. Dobkin, and H.T. Huhdanpaa, "The Quickhull Algorithm for Convex Hulls," ACM Transactions on Mathematical Software, Vol. 22, No. 4, Dec. 1996, p. 469-483. Available in HTML format at http://www.acm.org/ pubs/citations/journals/toms/1996-22-4/p469-barber/ and in PostScript format at ftp://geom.umn.edu/pub/software/qhull-96.ps. [2] National Science and Technology Research Center for Computation and Visualization of Geometric Structures (The Geometry Center), University of Minnesota. 1993. 2-426 delete Purpose Graphical Interface Syntax 2delete Delete files or graphics objects As an alternative to the delete function, you can delete files using the Current Directory browser. To open it, select Current Directory from the View menu in the MATLAB desktop. delete filename delete(h) delete('filename') delete filename deletes the named file from the disk. The filename may Description include an absolute pathname or a pathname relative to the current directory. The filename may also include wildcards, (*). delete(h) deletes the graphics object with handle h. The function deletes the object without requesting verification even if the object is a window. delete('filename') is the function form of delete. Use this form when the filename is stored in a string. Note MATLAB does not ask for con rmation when you enter the delete command. To avoid accidentally losing les or graphics objects that you need, make sure that you have accurately speci ed the items you want deleted. Examples To delete all files with a .mat extension in the ../mytests/ directory, delete('../mytests/*.mat') To delete a directory, use !rmdir rather than delete. !rmdir mydirectory See Also dir, type 2-427 delete (activex) Purpose Syntax Arguments 2delete (activex) Delete an ActiveX control or server. delete (a) a An activex object previously returned from actxcontrol, actxserver, get, or invoke. Description Delete an ActiveX control or server. This is different than releasing an interface, which releases and invalidates only that interface. delete releases all outstanding interfaces and deletes the ActiveX server or control itself. delete (a) Example 2-428 delete (serial) Purpose Syntax Arguments Description Remarks 2delete (serial) Remove a serial port object from memory delete(obj) obj A serial port object or an array of serial port objects. delete(obj) removes obj from memory. When you delete obj, it becomes an invalid object. Since you cannot connect an invalid serial port object to the device, you should remove it from the workspace with the clear command. If multiple references to obj exist in the workspace, then deleting one reference invalidates the remaining references. If you attempt to delete obj while it is connected to the device, then an error is returned. A connected serial port object has a Status property value of open. You can disconnect obj from the device with the fclose function. If you use the help command to display help for delete, then you need to supply the pathname shown below. help serial/delete Example This example creates the serial port object s, connects s to the device, writes and reads text data, disconnects s from the device, removes s from memory using delete, and then removes s from the workspace using clear. s = serial('COM1'); fopen(s) fprintf(s,'*IDN?') idn = fscanf(s); fclose(s) delete(s) clear s See Also Functions clear, fclose, isvalid Properties Status 2-429 depdir Purpose Syntax 2depdir List the dependent directories of an M-file or P-file list = depdir('file_name'); [list,prob_files,prob_sym,prob_strings] = depdir('file_name'); [...] = depdir('file_name1','file_name2',...); Description The depdir function lists the directories of all of the functions that a specified M-file or P-file needs to operate. This function is useful for finding all of the directories that need to be included with a runtime application and for determining the runtime path. list = depdir('file_name') creates a cell array of strings containing the directories of all the M-files and P-files that file_name.m or file_name.p uses. This includes the second-level files that are called directly by file_name, as well as the third-level files that are called by the second-level files, and so on. [list,prob_files,prob_sym,prob_strings] = depdir('file_name') creates three additional cell arrays containing information about any problems with the depdir search. prob_files contains filenames that depdir was unable to parse. prob_sym contains symbols that depdir was unable to find. prob_strings contains callback strings that depdir was unable to parse. [...] = depdir('file_name1','file_name2',...) performs the same operation for multiple files. The dependent directories of all files are listed together in the output cell arrays. Example See Also list = depdir('mesh') depfun 2-430 depfun Purpose Syntax 2depfun List the dependent functions of an M-file or P-file list = depfun('file_name'); [list,builtins,classes] = depfun('file_name'); [list,builtins,classes,prob_files,prob_sym,eval_strings,... called_from,java_classes] = depfun('file_name'); [...] = depfun('file_name1','file_name2',...); [...] = depfun('fig_file_name'); [...] = depfun(...,'-toponly'); Description The depfun function lists all of the functions and scripts, as well as built-in functions, that a specified M-file needs to operate. This is useful for finding all of the M-files that you need to compile for a MATLAB runtime application. list = depfun('file_name') creates a cell array of strings containing the paths of all the files that file_name.m uses. This includes the second-level files that are called directly by file_name.m, as well as the third-level files that are called by the second-level files, and so on. Note If depfun reports that These files could not be parsed: or if the prob_files output below is nonempty, then the rest of the output of depfun might be incomplete. You should correct the problematic les and invoke depfun again. [list,builtins,classes] = depfun('file_name') creates three cell arrays containing information about dependent functions. list contains the paths of all the files that file_name and its subordinates use. builtins contains the built-in functions that file_name and its subordinates use. classes contains the MATLAB classes that file_name and its subordinates use. [list,builtins,classes,prob_files,prob_sym,eval_strings,... called_from,java_classes] = depfun('file_name') creates additional cell arrays or structure arrays containing information about any problems with the depfun search and about where the functions in list are invoked. The additional outputs are: 2-431 depfun prob_files, which indicates which files depfun was unable to parse, find, or access. Parsing problems can arise from MATLAB syntax errors. prob_files is a structure array whose fields are: - name, which gives the names of the files - listindex, which tells where the files appeared in list - errmsg, which describes the problems prob_sym, which indicates which symbols depfun was unable to resolve as functions or variables. It is a structure array whose fields are: - fcn_id, which tells where the files appeared in list - name, which gives the names of the problematic symbols eval_strings, which indicates usage of these evaluation functions: eval, evalc, evalin, feval. When preparing a runtime application, you should examine this output to determine whether an evaluation function invokes a function that does not appear in list. The output eval_strings is a structure array whose fields are: - fcn_name, which give the names of the files that use evaluation functions - lineno, which gives the line numbers in the files where the evaluation functions appear called_from, a cell array of the same length as list. This cell array is arranged so that list(called_from{i}) returns all functions in file_name that invoke the function list{i}. java_classes, a cell array of Java class names that file_name and its subordinates use [...] = depfun('file_name1','file_name2',...) performs the same operation for multiple files. The dependent functions of all files are listed together in the output arrays. [...] = depfun('fig_file_name') looks for dependent functions among the callback strings of the GUI elements that are defined in the .fig or .mat file named fig_file_name. [...] = depfun(...,'-toponly') differs from the other syntaxes of depfun in that it examines only the files listed explicitly as input arguments. It does 2-432 depfun not examine the files on which they depend. In this syntax, the flag '-toponly' must be the last input argument. Notes 1 If depfun does not find a file called hginfo.mat on the path, then it creates one. This file contains information about Handle Graphics callbacks. 2 If your application uses toolbar items from MATLAB s default figure window, then you must include 'FigureToolBar.fig' in your input to depfun. 3 If your application uses menu items from MATLAB s default figure window, then you must include 'FigureMenuBar.fig' in your input to depfun. 4 Because many built-in Handle Graphics functions invoke newplot, the list produced by depfun always includes the functions on which newplot is dependent: - 'matlabroot\toolbox\matlab\graphics\newplot.m' - 'matlabroot\toolbox\matlab\graphics\closereq.m' - 'matlabroot\toolbox\matlab\graphics\gcf.m' - 'matlabroot\toolbox\matlab\graphics\gca.m' - 'matlabroot\toolbox\matlab\graphics\private\clo.m' - 'matlabroot\toolbox\matlab\general\@char\delete.m' - 'matlabroot\toolbox\matlab\lang\nargchk.m' - 'matlabroot\toolbox\matlab\uitools\allchild.m' - 'matlabroot\toolbox\matlab\ops\setdiff.m' - 'matlabroot\toolbox\matlab\ops\@cell\setdiff.m' - 'matlabroot\toolbox\matlab\iofun\filesep.m' - 'matlabroot\toolbox\matlab\ops\unique.m' - 'matlabroot\toolbox\matlab\elmat\repmat.m' - 'matlabroot\toolbox\matlab\datafun\sortrows.m' - 'matlabroot\toolbox\matlab\strfun\deblank.m' - 'matlabroot\toolbox\matlab\ops\@cell\unique.m' - 'matlabroot\toolbox\matlab\strfun\@cell\deblank.m' - 'matlabroot\toolbox\matlab\datafun\@cell\sort.m' - 'matlabroot\toolbox\matlab\strfun\cellstr.m' - 'matlabroot\toolbox\matlab\datatypes\iscell.m' - 'matlabroot\toolbox\matlab\strfun\iscellstr.m' - 'matlabroot\toolbox\matlab\datatypes\cellfun.dll' 2-433 depfun Examples list = depfun('mesh'); % Files mesh.m depends on list = depfun('mesh','-toponly') % Files mesh.m depends on directly [list,builtins,classes] = depfun('gca'); depdir See Also 2-434 det Purpose Syntax Description Remarks 2det Matrix determinant d = det(X) d = det(X) returns the determinant of the square matrix X. If X contains only integer entries, the result d is also an integer. Using det(X) == 0 as a test for matrix singularity is appropriate only for matrices of modest order with small integer entries. Testing singularity using abs(det(X)) <= tolerance is not recommended as it is difficult to choose the correct tolerance. The function cond(X) can check for singular and nearly singular matrices. The determinant is computed from the triangular factors obtained by Gaussian elimination [L,U] = lu(A) s = det(L) % This is always +1 or -1 det(A) = s*prod(diag(U)) Algorithm Examples The statement A = [1 produces A = 1 4 7 2 5 8 2 3; 4 5 6; 7 8 9] 3 6 9 This happens to be a singular matrix, so d = det(A) produces d = 0. Changing A(3,3) with A(3,3) = 0 turns A into a nonsingular matrix. Now d = det(A) produces d = 27. See Also cond, condest, inv, lu, rref The arithmetic operators \, / 2-435 detrend Purpose Syntax 2detrend Remove linear trends. y = detrend(x) y = detrend(x,'constant') y = detrend(x,'linear',bp) detrend removes the mean value or linear trend from a vector or matrix, Description usually for FFT processing. y = detrend(x) removes the best straight-line fit from vector x and returns it in y. If x is a matrix, detrend removes the trend from each column. y = detrend(x,'constant') removes the mean value from vector x or, if x is a matrix, from each column of the matrix. y = detrend(x,'linear',bp) removes a continuous, piecewise linear trend from vector x or, if x is a matrix, from each column of the matrix. Vector bp contains the indices of the breakpoints between adjacent linear segments. The breakpoint between two segments is defined as the data point that the two segments share. breakpoints detrend(x,'linear'), with no breakpoint vector specified, is the same as detrend(x). Example sig = [0 1 -2 1 0 1 -2 1 0]; trend = [0 1 2 3 4 3 2 1 0]; x = sig+trend; y = detrend(x,'linear',5) % % % % signal with no linear trend two-segment linear trend signal with added trend breakpoint at 5th element 2-436 detrend y = -0.0000 1.0000 -2.0000 1.0000 0.0000 1.0000 -2.0000 1.0000 -0.0000 Note that the breakpoint is specified to be the fifth element, which is the data point shared by the two segments. Algorithm detrend computes the least-squares fit of a straight line (or composite line for piecewise linear trends) to the data and subtracts the resulting function from the data. To obtain the equation of the straight-line fit, use polyfit. See Also polyfit 2-437 deval Purpose Syntax Description 2deval Evaluate the solution of a differential equation problem sxint = deval(sol,xint) sxint = deval(sol,xint) evaluates the solution of a differential equation problem at each element of the vector xint. For each i, sxint(:,i) is the solution corresponding to xint(i). The input argument sol is a structure returned by an initial value problem solver (ode45, ode23, ode113, ode15s, ode23s, ode23t, ode23tb) or the boundary value problem solver (bvp4c). The ordered row vector sol.x contains the independent variable. For each i, the column sol.y(:,i) contains the solution at sol.x(i). The structure sol also contains data needed for interpolating the solution in (x(i),x(i+1)). The form of this data depends on the solver that creates sol. The field sol.solver contains the name of that solver. Elements of xint must be in the interval [sol.x(1),sol.x(end)]. See Also ODE solvers: ode45, ode23, ode113, ode15s, ode23s, ode23t, ode23tb BVP solver: bvp4c 2-438 diag Purpose Syntax 2diag Diagonal matrices and diagonals of a matrix X X v v = = = = diag(v,k) diag(v) diag(X,k) diag(X) Description X = diag(v,k) when v is a vector of n components, returns a square matrix X of order n+abs(k), with the elements of v on the kth diagonal. k = 0 represents the main diagonal, k > 0 above the main diagonal, and k < 0 below the main diagonal. k=0 k>0 k<0 X = diag(v) puts v on the main diagonal, same as above with k = 0. v = diag(X,k) for matrix X, returns a column vector v formed from the elements of the kth diagonal of X. v = diag(X) returns the main diagonal of X, same as above with k = 0. Examples diag(diag(X)) is a diagonal matrix. sum(diag(X)) is the trace of X. The statement diag(-m:m)+diag(ones(2*m,1),1)+diag(ones(2*m,1),-1) produces a tridiagonal matrix of order 2*m+1. 2-439 diag See Also spdiags, tril, triu 2-440 dialog Purpose Syntax Description 2dialog Create and display dialog box h = dialog('PropertyName',PropertyValue,...) h = dialog('PropertyName',PropertyValue,...) returns a handle to a dialog box. This function creates a figure graphics object and sets the figure properties recommended for dialog boxes. You can specify any valid figure property value. errordlg, figure, helpdlg, inputdlg, pagedlg, printdlg, questdlg, uiwait, uiresume, warndlg See Also 2-441 diary Purpose Syntax 2diary Save session to a file diary diary('filename') diary off diary on diary filename Description The diary function creates a log of keyboard input and the resulting output (except it does not include graphics). The output of diary is an ASCII file, suitable for printing or for inclusion in reports and other documents. If you do not specify filename, MATLAB creates a file named diary in the current directory. diary toggles diary mode on and off. To see the status of diary, type get(0,'Diary'). MATLAB returns either on or off indicating the diary status. diary('filename') writes a copy of all subsequent keyboard input and the resulting output (except it does not include graphics) to the named file. If the file already exists, output is appended to the end of the file. You cannot use a filename called off or on. To see the name of the diary file, use get(0,'DiaryFile'). Type get(0,'DiaryName'), and MATLAB returns filename. diary off suspends the diary. diary on resumes diary mode using the current filename, or the default filename diary if none has yet been specified. diary filename is the unquoted form of the syntax. See Also Command History window 2-442 diff Purpose Syntax 2diff Differences and approximate derivatives Y = diff(X) Y = diff(X,n) Y = diff(X,n,dim) Y = diff(X) calculates differences between adjacent elements of X. Description If X is a vector, then diff(X) returns a vector, one element shorter than X, of differences between adjacent elements: [X(2)-X(1) X(3)-X(2) ... X(n)-X(n-1)] If X is a matrix, then diff(X) returns a matrix of row differences: [X(2:m,:)-X(1:m-1,:)] In general, diff(X) returns the differences calculated along the first non-singleton (size(X,dim) > 1) dimension of X. Y = diff(X,n) applies diff recursively n times, resulting in the nth difference. Thus, diff(X,2) is the same as diff(diff(X)). Y = diff(X,n,dim) is the nth difference function calculated along the dimension specified by scalar dim. If order n equals or exceeds the length of dimension dim, diff returns an empty array. Remarks Since each iteration of diff reduces the length of X along dimension dim, it is possible to specify an order n sufficiently high to reduce dim to a singleton (size(X,dim) = 1) dimension. When this happens, diff continues calculating along the next nonsingleton dimension. The quantity diff(y)./diff(x) is an approximate derivative. x = [1 2 3 4 5]; y = diff(x) y = 1 1 1 z = diff(x,2) z = Examples 1 2-443 diff 0 0 0 Given, A = rand(1,3,2,4); diff(A) is the first-order difference along dimension 2. diff(A,3,4) is the third-order difference along dimension 4. See Also gradient, prod, sum 2-444 dir Purpose Graphical Interface Syntax 2dir Display directory listing As an alternative to the dir function, use the Current Directory browser. To open it, select Current Directory from the View menu in the MATLAB desktop. dir dir name files = dir('name') dir lists the files in the current working directory. dir name lists the specified files. The name argument can be a pathname, Description filename, or can include both. You can use absolute and relative pathnames and wildcards. files = dir('directory') returns the list of files in the specified directory (or the current directory, if dirname is not specified) to an m-by-1 structure with the fields: name date bytes isdir Filename Modi cation date Number of bytes allocated to the le 1 if name is a directory; 0 if not Examples To view the MAT files in your current working directory, dir *java*.mat java_array.mat javafrmobj.mat testjava.mat To view the M-files in the MATLAB audio directory, type dir(fullfile(matlabroot,'toolbox/matlab/audio/*.m')) Contents.m auread.m auwrite.m lin2mu.m mu2lin.m saxis.m sound.m soundsc.m wavplay.m wavread.m wavrecord.m wavwrite.m To return the list of files to the variable audio_files, type 2-445 dir audio_files=dir(fullfile(matlabroot,'toolbox/matlab/audio/ *.m')) MATLAB returns the information in a structure array. audio_files = 12x1 struct array with fields: name date bytes isdir Index into the structure to access a particular item. For example, audio_files(3).name ans = auwrite.m See Also cd, delete, filebrowser, ls, type, what 2-446 disp Purpose Syntax Description 2disp Display text or array disp(X) disp(X) displays an array, without printing the array name. If X contains a text string, the string is displayed. Another way to display an array on the screen is to type its name, but this prints a leading X =, which is not always desirable. Note that disp does not display empty arrays. Examples One use of disp in an M-file is to display a matrix with column labels: disp(' Corn disp(rand(5,3)) Oats Hay') which results in Corn 0.2113 0.0820 0.7599 0.0087 0.8096 Oats 0.8474 0.4524 0.8075 0.4832 0.6135 Hay 0.2749 0.8807 0.6538 0.4899 0.7741 See Also format, int2str, num2str, rats, sprintf 2-447 disp (serial) Purpose Syntax Arguments Description Remarks 2disp (serial) Display serial port object summary information obj disp(obj) obj A serial port object or an array of serial port objects. obj or disp(obj) displays summary information for obj. In addition to the syntax shown above, you can display summary information for obj by excluding the semicolon when: Creating a serial port object Configuring property values using the dot notation Use the display summary to quickly view the communication settings, communication state information, and information associated with read and write operations. Example The following commands display summary information for the serial port object s. s = serial('COM1') s.BaudRate = 300 s 2-448 display Purpose Syntax Description 2display Overloaded method to display an object display(X) display(X) prints the value of a variable or expression, X. MATLAB calls display(X) when it interprets a variable or expression, X, that is not terminated by a semicolon. For example, sin(A) calls display, while sin(A); does not. If X is an instance of a MATLAB class, then MATLAB calls the display method of that class, if such a method exists. If the class has no display method or if X is not an instance of a MATLAB class, then the MATLAB builtin display function is called. Examples A typical implementation of display calls disp to do most of the work and looks like this. function display(X) if isequal(get(0,'FormatSpacing'),'compact') disp([inputname(1) ' =']); disp(X) else disp(' ') disp([inputname(1) ' =']); disp(' '); disp(X) end The expression magic(3), with no terminating semicolon, calls this function as display(magic(3)). magic(3) ans = 8 3 4 1 5 9 6 7 2 As an example of a class display method, the function below implements the display method for objects of the MATLAB class, polynom. 2-449 display function display(p) % POLYNOM/DISPLAY Command window display of a polynom disp(' '); disp([inputname(1),' = ']) disp(' '); disp([' ' char(p)]) disp(' '); The statement p = polynom([1 0 -2 -5]) creates a polynom object. Since the statement is not terminated with a semicolon, the MATLAB interpreter calls display(p), resulting in the output p = x^3 - 2*x - 5 See Also disp, ans, sprintf, special characters 2-450 divergence Purpose Syntax 2divergence Computes the divergence of a vector field div div div div = = = = divergence(X,Y,Z,U,V,W) divergence(U,V,W) divergence(X,Y,U,V) divergence(U,V) Description div = divergence(X,Y,Z,U,V,W) computes the divergence of a 3-D vector field U, V, W. The arrays X, Y, Z define the coordinates for U, V, W and must be monotonic and 3-D plaid (as if produced by meshgrid). div = divergence(U,V,W) assumes X, Y, and Z are determined by the expression: [X Y Z] = meshgrid(1:n,1:m,1:p) where [m,n,p] = size(U). div = divergence(X,Y,U,V) computes the divergence of a 2-D vector field U, V. The arrays X, Y define the coordinates for U, V and must be monotonic and 2-D plaid (as if produced by meshgrid). div = divergence(U,V) assumes X and Y are determined by the expression: [X Y] = meshgrid(1:n,1:m) where [m,n] = size(U). Examples This example displays the divergence of vector volume data as slice planes using color to indicate divergence. load wind div = divergence(x,y,z,u,v,w); slice(x,y,z,div,[90 134],[59],[0]); shading interp daspect([1 1 1]) camlight 2-451 divergence See Also streamtube, curl, isosurface 2-452 dlmread Purpose Graphical Interface Syntax 2dlmread Read an ASCII delimited file into a matrix As an alternative to dlmread, use the Import Wizard. To activate the Import Wizard, select Import data from the File menu. M = dlmread(filename,delimiter) M = dlmread(filename,delimiter,R,C) M = dlmread(filename,delimiter,range) M = dlmread(filename,delimiter) reads numeric data from the ASCII delimited file filename, using the specified delimiter. A comma (,) is the default delimiter. Use '\t' to specify a tab delimiter. M = dlmread(filename,delimiter,R,C) reads numeric data from the ASCII delimited file filename, using the specified delimiter. The values R and C Description specify the row and column where the upper-left corner of the data lies in the file. R and C are zero based so that R=0, C=0 specifies the first value in the file, which is the upper left corner. M = dlmread(filename,delimiter,range) reads the range specified by range = [R1 C1 R2 C2] where (R1,C1) is the upper-left corner of the data to be read and (R2,C2) is the lower-right corner. range can also be specified using spreadsheet notation as in range = 'A1..B7'. Remarks dlmread fills empty delimited fields with zero. Data files having lines that end with a non-space delimiter, such as a semi-colon, produce a result that has an additional last column of zeros. See Also dlmwrite, textread, csvread, csvwrite, wk1read, wk1write 2-453 dlmwrite Purpose Syntax Description 2dlmwrite Write a matrix to an ASCII delimited file dlmwrite(filename,M,delimiter) dlmwrite(filename,M,delimiter,R,C) dlmwrite(filename,M,delimiter) writes matrix M into an ASCII-format file, using delimiter to separate matrix elements. The data is written to the upper left-most cell of the spreadsheet filename. A comma (,) is the default delimiter. Use '\t' to produce tab-delimited files. dlmwrite(filename,M,delimiter,R,C) writes matrix A into an ASCII-format file, using delimiter to separate matrix elements. The data is written to the spreadsheet filename, starting at spreadsheet cell R and C, where R is the row offset and C is the column offset. R and C are zero based so that R=0, C=0 specifies the first value in the file, which is the upper left corner. Remarks See Also The resulting file is readable by spreadsheet programs. dlmread, csvwrite, csvread, wk1write, wk1read 2-454 dmperm Purpose Syntax 2dmperm Dulmage-Mendelsohn decomposition p = dmperm(A) [p,q,r] = dmperm(A) [p,q,r,s] = dmperm(A) Description If A is a reducible matrix, the linear system Ax = b can be solved by permuting A to a block upper triangular form, with irreducible diagonal blocks, and then performing block backsubstitution. Only the diagonal blocks of the permuted matrix need to be factored, saving fill and arithmetic in the blocks above the diagonal. p = dmperm(A) returns a row permutation p so that if A has full column rank, A(p,:) is square with nonzero diagonal. This is also called a maximum matching. [p,q,r] = dmperm(A) where A is a square matrix, finds a row permutation p and a column permutation q so that A(p,q) is in block upper triangular form. The third output argument r is an integer vector describing the boundaries of the blocks: The kth block of A(p,q) has indices r(k):r(k+1)-1. [p,q,r,s] = dmperm(A), where A is not square, finds permutations p and q and index vectors r and s so that A(p,q) is block upper triangular. The blocks have indices (r(i):r(i+1)-1, s(i):s(i+1)-1). If A is not square, the first block may have more columns and the last block may have more rows. All other blocks are square. dmperm permutes nonzeros to the diagonals of square blocks, but does not do this for non-square blocks. In graph theoretic terms, the diagonal blocks correspond to strong Hall components of the adjacency graph of A. See Also sprank 2-455 doc Purpose Graphical Interface Syntax 2doc Display online documentation in MATLAB Help browser As an alternative to the doc function, use the Help browser Search tab. Set the Search type to Function Name, type the function name, and click Go. doc doc function doc toolbox/ doc toolbox/function doc opens the Help browser, if it is not already running. doc function displays the reference page for the MATLAB function function in the Help browser. If function is overloaded, doc displays the reference page for the first function on the search path and lists the overloaded functions in Description the MATLAB Command Window. If a reference page for the function does not exist, doc displays M-file help in the Help browser. doc toolbox/ displays the Roadmap page, a summary of the most pertinent documentation for toolbox, in the Help browser. doc toolbox/function displays the reference page for function that belongs to the specified toolbox, in the Help browser. See Also help, helpbrowser, lookfor, type, web 2-456 docopt Purpose Syntax Description 2docopt Display location of help file directory for UNIX platforms docopt [doccmd,options,docpath] = docopt docopt displays the location of the online help files directory (online documentation location) for UNIX platforms if the web function is used with the -browser option. It is also used for UNIX platforms that do not support Java GUIs see the R12 Release Notes for more information about these platforms. You specify where the online help directory will be located when you install MATLAB. It can be on a disk or CD-ROM drive in your local system. If you relocate your online help file directory, edit the docopt.m file, changing the location in it. (For Windows and the UNIX platforms that support Java GUIs, select File -> Preferences -> Help to view or change the documentation location.) [doccmd,options,docpath] = docopt displays three strings: doccmd, options, and docpath. doccmd options docpath The function that doc uses to display MATLAB documentation. The default is netscape. Additional con guration options for use with doccmd. The path to the MATLAB online help les. If docpath is empty, the doc function assumes the help les are in the default location. Remarks To globally replace the online help file directory location, update $matlabroot/ toolbox/local/docopt.m. To override the global setting, copy $matlabroot/toolbox/local/docopt.m to $HOME/matlab/docopt.m and make changes there. For the changes to take effect in the current MATLAB session, $HOME/matlab must be on your MATLAB path. See Also doc, help, helpbrowser, helpdesk, lookfor, type 2-457 dos Purpose Syntax 2dos Execute a DOS command and return result dos command status = dos('command') [status,result] = dos('command') [status,result] = dos('command','-echo') dos command calls upon the shell to execute the given command for Windows Description systems. status = dos('command') returns completion status to the status variable. [status,result] = dos('command') in addition to completion status, returns the result of the command to the result variable. [status,result] = dos('command','-echo') forces the output to the Command Window, even though it is also being assigned into a variable. Both console (DOS) programs and Windows programs may be executed, but the syntax causes different results based on the type of programs. Console programs have stdout and their output is returned to the result variable. They are always run in an iconified DOS or Command Prompt Window except as noted below. Console programs never execute in the background. Also, MATLAB will always wait for the stdout pipe to close before continuing execution. Windows programs may be executed in the background as they have no stdout. The ampersand, &, character has special meaning. For console programs this causes the console to open. Omitting this character will cause console programs to run iconically. For Windows programs, appending this character will cause the application to run in the background. MATLAB will continue processing. Examples The following example performs a directory listing, returning a zero (success) in s and the string containing the listing in w. [s, w] = dos('dir'); To open the DOS 5.0 editor in a DOS window dos('edit &') 2-458 dos To open the notepad editor and return control immediately to MATLAB dos('notepad file.m &') The next example returns a one in s and an error message in w because foo is not a valid shell command. [s, w] = dos('foo') This example echoes the results of the dir command to the Command Window as it executes as well as assigning the results to w. [s, w] = dos('dir', '-echo'); See Also Special Characters (!), unix 2-459 dot Purpose Syntax Description 2dot Vector dot product C = dot(A,B) C = dot(A,B,dim) C = dot(A,B) returns the scalar product of the vectors A and B. A and B must be vectors of the same length. When A and B are both column vectors, dot(A,B) is the same as A'*B. For multidimensional arrays A and B, dot returns the scalar product along the first non-singleton dimension of A and B. A and B must have the same size. C = dot(A,B,dim) returns the scalar product of A and B in the dimension dim. Examples The dot product of two vectors is calculated as shown: a = [1 2 3]; b = [4 5 6]; c = dot(a,b) c = 32 See Also cross 2-460 double Purpose Syntax Description Remarks 2double Convert to double-precision double(X) double(x) returns the double-precision value for X. If X is already a double-precision array, double has no effect. double is called for the expressions in for, if, and while loops if the expression isn't already double-precision. double should be overloaded for any object when it makes sense to convert it to a double-precision value. 2-461 dragrect Purpose Syntax Description 2dragrect Drag rectangles with mouse [finalrect] = dragrect(initialrect) [finalrect] = dragrect(initialrect,stepsize) [finalrect] = dragrect(initialrect) tracks one or more rectangles anywhere on the screen. The n-by-4 matrix, initialrect, defines the rectangles. Each row of initialrect must contain the initial rectangle position as [left bottom width height] values. dragrect returns the final position of the rectangles in finalrect. [finalrect] = dragrect(initialrect,stepsize) moves the rectangles in increments of stepsize. The lower-left corner of the first rectangle is constrained to a grid of size equal to stepsize starting at the lower-left corner of the figure, and all other rectangles maintain their original offset from the first rectangle. [finalrect] = dragrect(...) returns the final positions of the rectangles when the mouse button is released. The default stepsize is 1. Remarks dragrect returns immediately if a mouse button is not currently pressed. Use dragrect in a ButtonDownFcn, or from the command line in conjunction with waitforbuttonpress to ensure that the mouse button is down when dragrect is called. dragrect returns when you release the mouse button. If the drag ends over a figure window, the positions of the rectangles are returned in that figure's coordinate system. If the drag ends over a part of the screen not contained within a figure window, the rectangles are returned in the coordinate system of the figure over which the drag began Example Drag a rectangle that is 50 pixels wide and 100 pixels in height. waitforbuttonpress point1 = get(gcf,'CurrentPoint') % button down detected rect = [point1(1,1) point1(1,2) 50 100] [r2] = dragrect(rect) See Also rbbox, waitforbuttonpress 2-462 drawnow Purpose Syntax Description Remarks 2drawnow Complete pending drawing events drawnow drawnow flushes the event queue and updates the figure window. Other events that cause MATLAB to flush the event queue and draw the figure windows include: Returning to the MATLAB prompt A pause statement A waitforbuttonpress statement A waitfor statement A getframe statement A figure statement Examples Executing the statements, x = pi:pi/20:pi; plot(x,cos(x)) drawnow title('A Short Title') grid on as an M-file updates the current figure after executing the drawnow function and after executing the final statement. See Also waitfor, pause, waitforbuttonpress 2-463 dsearch Purpose Syntax Description 2dsearch Search for nearest point K = dsearch(x,y,TRI,xi,yi) K = dsearch(x,y,TRI,xi,yi,S) K = dsearch(x,y,TRI,xi,yi) returns the index into x and y of the nearest point to the point (xi,yi). dsearch requires a triangulation TRI of the points x,y obtained using delaunay. If xi and yi are vectors, K is a vector of the same size. K = dsearch(x,y,TRI,xi,yi,S) uses the sparse matrix S instead of computing it each time: S = sparse(TRI(:,[1 1 2 2 3 3]),TRI(:,[2 3 1 3 1 2]),1,nxy,nxy) where nxy = prod(size(x)). See Also delaunay, tsearch, voronoi 2-464 dsearchn Purpose Syntax 2dsearchn n-D nearest point search k = dsearchn(X,T,XI) k = dsearchn(X,T,XI,outval) k = dsearchn(X,XI) [k,d] = dsearchn(X,...) k = dsearchn(X,T,XI) returns the indices k of the closest points in X for each point in XI. X is an m-by-n matrix representing m points in n-D space. XI is a p-by-n matrix, representing p points in n-D space. T is a numt-by-n+1 matrix, a tessellation of the data X generated by delaunayn. The output k is a column vector of length p. k = dsearchn(X,T,XI,outval) returns the indices k of the closest points in X for each point in XI, unless a point is outside the convex hull. If XI(J,:) is outside the convex hull, then K(J) is assigned outval, a scalar double. Inf is often used for outval. If outval is [], then k is the same as in the case k = dsearchn(X,T,XI). k = dsearchn(X,XI) performs the search without using a tessellation. With large X and small XI, this approach is faster and uses much less memory. [k,d] = dsearchn(X,...) also returns the distances d to the closest points. d is a column vector of length p. Description See Also tsearch, dsearch, tsearchn, griddatan, delaunayn 2-465 echo Purpose Syntax 2echo Echo M-files during execution echo echo echo echo echo echo echo echo on off fcnname on fcnname off fcnname on all off all Description The echo command controls the echoing of M-files during execution. Normally, the commands in M-files do not display on the screen during execution. Command echoing is useful for debugging or for demonstrations, allowing the commands to be viewed as they execute. The echo command behaves in a slightly different manner for script files and function files. For script files, the use of echo is simple; echoing can be either on or off, in which case any script used is affected. echo on echo off echo Turns on the echoing of commands in all script les. Turns off the echoing of commands in all script les. Toggles the echo state. With function files, the use of echo is more complicated. If echo is enabled on a function file, the file is interpreted, rather than compiled. Each input line is then displayed as it is executed. Since this results in inefficient execution, use echo only for debugging. echo fcnname on echo fcnname off echo fcnname echo on all echo off all Turns on echoing of the named function le. Turns off echoing of the named function le. Toggles the echo state of the named function le. Set echoing on for all function les. Set echoing off for all function les. See Also function 2-466 edit Purpose Graphical Interface Syntax 2edit Edit or create M-file As an alternative to the edit function, select New or Open from the File menu in the MATLAB desktop. edit edit edit edit edit edit fun.m file.ext class/fun private/fun class/private/fun Description edit opens a new editor window. edit fun.m opens the M-file fun.m in the default editor. If fun.m does not exist, a prompt appears asking if you want to create a new file titled fun.m. After clicking Yes, the Editor/Debugger creates a blank file titled fun.m. If you do not want the prompt to appear in this situation, check that box in the prompt or specify it in preferences for Prompt on page 7-38. If you type edit fun and there is no file fun, fun.m opens in the default editor. edit file.ext opens the specified text file. edit class/fun, edit private/fun, or edit class/private/fun can be used to edit a method, private function, or private method (for the class named class). Remarks To specify the default editor for MATLAB, select Preferences from the File menu. On the Editor/Debugger panel, select MATLAB s Editor/Debugger or specify another. UNIX Users If you run MATLAB with the -nodisplay startup option, or run without the DISPLAY environment variable set, edit uses the External Editor command. It does not use the MATLAB Editor/Debugger, but instead uses the default editor defined for your system in $matlabroot/X11/app-defaults/Matlab. 2-467 edit You can specify the editor that the edit function uses or specify editor options by adding the following line to your own .Xdefaults file, located in ~home. matlab*externalEditorCommand: $EDITOR -option $FILE where: $EDITOR is the name of your default editor, for example, emacs; leaving it as $EDITOR means your default system editor will be used. -option is an option flag for the specified editor. $FILE means the filename you type with the edit command will open in the specified editor. Then, before starting MATLAB, run xrdb -merge ~home/.Xdefaults For the HP 700 platform, the default editor is instead defined in $matlabroot/ toolbox/matlab/general/edit.m. To change it, open the file edit.m and edit the line eval( ['!$EDITOR ' file '" &']); See Also open, type 2-468 eig Purpose Syntax 2eig Find eigenvalues and eigenvectors d = eig(A) d = eig(A,B) [V,D] = eig(A) [V,D] = eig(A,'nobalance') [V,D] = eig(A,B) [V,D] = eig(A,B,flag) d = eig(A) returns a vector of the eigenvalues of matrix A. Description Note If S is sparse and symmetric, you can use d = eig(S) to returns the eigenvalues of S. To request eigenvectors, and in all other cases, use eigs to nd the eigenvalues or eigenvectors of sparse matrices. d = eig(A,B) returns a vector containing the generalized eigenvalues, if A and B are square matrices. [V,D] = eig(A) produces matrices of eigenvalues (D) and eigenvectors (V) of matrix A, so that A*V = V*D. Matrix D is the canonical form of A a diagonal matrix with A s eigenvalues on the main diagonal. Matrix V is the modal matrix its columns are the eigenvectors of A. For eig(A), the eigenvectors are scaled so that the norm of each is 1.0. If W is a matrix such that W'*A = D*W', the columns of W are the left eigenvectors of A . Use [W,D] = eig(A.'); W = conj(W) to compute the left eigenvectors. [V,D] = eig(A,'nobalance') finds eigenvalues and eigenvectors without a preliminary balancing step. Ordinarily, balancing improves the conditioning of the input matrix, enabling more accurate computation of the eigenvectors and eigenvalues. However, if a matrix contains small elements that are really due to roundoff error, balancing may scale them up to make them as significant as the other elements of the original matrix, leading to incorrect eigenvectors. Use the nobalance option in this event. See the balance function for more details. 2-469 eig [V,D] = eig(A,B) produces a diagonal matrix D of generalized eigenvalues and a full matrix V whose columns are the corresponding eigenvectors so that A*V = B*V*D. [V,D] = eig(A,B,flag) specifies the algorithm used to compute eigenvalues and eigenvectors. flag can be: 'chol' Computes the generalized eigenvalues of A and B using the Cholesky factorization of B. This is the default for symmetric (Hermitian) A and symmetric (Hermitian) positive de nite B. Ignores the symmetry, if any, and uses the QZ algorithm as it would for nonsymmetric (non-Hermitian) A and B. 'qz' Remarks The eigenvalue problem is to determine the nontrivial solutions of the equation Ax = x where A is an n-by-n matrix, x is a length n column vector, and is a scalar. The n values of that satisfy the equation are the eigenvalues, and the corresponding values of x are the right eigenvectors. In MATLAB, the function eig solves for the eigenvalues , and optionally the eigenvectors x . The generalized eigenvalue problem is to determine the nontrivial solutions of the equation Ax = Bx where both A and B are n-by-n matrices and is a scalar. The values of that satisfy the equation are the generalized eigenvalues and the corresponding values of x are the generalized right eigenvectors. If B is nonsingular, the problem could be solved by reducing it to a standard eigenvalue problem B 1 Ax = x Because B can be singular, an alternative algorithm, called the QZ method, is necessary. When a matrix has no repeated eigenvalues, the eigenvectors are always independent and the eigenvector matrix V diagonalizes the original matrix A if applied as a similarity transformation. However, if a matrix has repeated 2-470 eig eigenvalues, it is not similar to a diagonal matrix unless it has a full (independent) set of eigenvectors. If the eigenvectors are not independent then the original matrix is said to be defective. Even if a matrix is defective, the solution from eig satisfies A*X = X*D. Examples The matrix B = [ 3 -2 -2 4 -eps/4 eps/2 -.5 -.5 -.9 1 -1 .1 2*eps -eps 0 1 ]; has elements on the order of roundoff error. It is an example for which the nobalance option is necessary to compute the eigenvectors correctly. Try the statements [VB,DB] = eig(B) B*VB - VB*DB [VN,DN] = eig(B,'nobalance') B*VN - VN*DN Algorithm MATLAB uses LAPACK routines to compute eigenvalues and eigenvectors: Case Routine DSYEV Real symmetric A Real nonsymmetric A: With preliminary balance step d = eig(A,'nobalance') [V,D] = eig(A,'nobalance') Hermitian A DGEEV (with SCLFAC = 2 instead of 8 in DGEBAL) DGEHRD, DHSEQR DGEHRD, DORGHR, DHSEQR, DTREVC ZHEEV 2-471 eig Case Routine Non-Hermitian A: With preliminary balance step d = eig(A,'nobalance') [V,D] = eig(A,'nobalance') Real symmetric A, symmetric positive de nite B. Special case: eig(A,B,'qz') for real A, B (same as real nonsymmetric A, real general B) Real nonsymmetric A, real general B Complex Hermitian A, Hermitian positive de nite B. Special case: eig(A,B,'qz') for complex A or B (same as complex non-Hermitian A, complex B) Complex non-Hermitian A, complex B ZGEEV (with SCLFAC = 2 instead of 8 in ZGEBAL) ZGEHRD, ZHSEQR ZGEHRD, ZUNGHR, ZHSEQR, ZTREVC DSYGV DGGEV DGGEV ZHEGV ZGGEV ZGGEV See Also References balance, condeig, eigs, hess, qz, schur [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-472 eigs Purpose Syntax 2eigs Find a few eigenvalues and eigenvectors of a square large sparse matrix d = eigs(A) d = eigs(A,B) d = eigs(A,k) d = eigs(A,B,k) d = eigs(A,k,sigma) d = eigs(A,B,k,sigma) d = eigs(A,k,sigma,options) d = eigs(A,B,k,sigma,options) d = eigs(Afun,n) d = eigs(Afun,n,B) d = eigs(Afun,n,k) d = eigs(Afun,n,B,k) d = eigs(Afun,n,k,sigma) d = eigs(Afun,n,B,k,sigma) d = eigs(Afun,n,k,sigma,options) d = eigs(Afun,n,B,k,sigma,options) d = eigs(Afun,n,k,sigma,options,p1,p2...) d = eigs(Afun,n,B,k,sigma,options,p1,p2...) [V,D] = eigs(A,...) [V,D] = eigs(Afun,n,...) [V,D,flag] = eigs(A,...) [V,D,flag] = eigs(Afun,n,...) d = eigs(A) returns a vector of A's six largest magnitude eigenvalues. [V,D] = eigs(A) returns a diagonal matrix D of A's six largest magnitude eigenvalues and a matrix V whose columns are the corresponding eigenvectors. [V,D,flag] = eigs(A) also returns a convergence flag. If flag is 0 then all Description the eigenvalues converged; otherwise not all converged. eigs(Afun,n) accepts the function Afun instead of the matrix A. y = Afun(x) should return y = A*x, where x is an n-by-1 vector, and n is the size of A. The matrix A represented by Afun is assumed to be real and nonsymmetric. In all these calling sequences, eigs(A,...) can be replaced by eigs(Afun,n,...). 2-473 eigs eigs(A,B) solves the generalized eigenvalue problem A*V == B*V*D. B must be symmetric (or Hermitian) positive definite and the same size as A. eigs(A,[],...) indicates the standard eigenvalue problem A*V == V*D. eigs(A,k) and eigs(A,B,k) return the k largest magnitude eigenvalues. eigs(A,k,sigma) and eigs(A,B,k,sigma) return k eigenvalues based on sigma, which can take any of the following values: scalar The eigenvalues closest to sigma. If A is a function, Afun (real or complex, must return Y = (A-sigma*B)\x (i.e., Y = A\x when including 0) sigma = 0). Note, B need only be symmetric (Hermitian) positive semi-de nite. 'lm' 'sm' Largest magnitude (default). Smallest magnitude. Same as sigma = 0. If A is a function, Afun must return Y = A\x. Note, B need only be symmetric (Hermitian) positive semi-de nite. For real symmetric problems, the following are also options: 'la' 'sa' 'be' Largest algebraic ('lr' in MATLAB 5) Smallest algebraic ('sr' in MATLAB 5) Both ends (one more from high end if k is odd) For nonsymmetric and complex problems, the following are also options: 'lr' 'sr' 'li' 'si' Largest real part Smallest real part Largest imaginary part Smallest imaginary part Note The MATLAB 5 value sigma = 'be' is obsolete for nonsymmetric and complex problems. 2-474 eigs eigs(A,K,sigma,opts) and eigs(A,B,k,sigma,opts) specify an options structure: Parameter options.issym Description 1 if A or A-sigma*B represented by Afun is symmetric, 0 otherwise. 1 if A or A-sigma*B represented by Afun is real, 0 otherwise. Default Value 0 options.isreal 1 options.tol Convergence: abs(lamda_computed-lamda_true) < tol*abs(lamda_computed). eps options.maxit options.p Maximum number of iterations. Number of basis vectors. p >= 2k (p >= 2k+1 real nonsymmetric) advised. Note: p must satisfy k < p <= n for real symmetric, k+1 < p <= n otherwise. Starting vector. 300 2k options.v0 Randomly generated by ARPACK 1 0 options.disp options.cholB Diagnostic information display level. 1 if B is really its Cholesky factor chol(B), 0 otherwise. options.permB Permutation vector permB if sparse B is really chol(B(permB,permB)). 1:n Note MATLAB 5 options stagtol and cheb are no longer allowed. 2-475 eigs eigs(Afun,n,k,sigma,opts,p1,p2,...) and eigs(Afun,n,B,k,sigma,opts,p1,p2,...) provide for additional arguments which are passed to Afun(x,p1,p2,...). Remarks d = eigs(A,k) is not a substitute for d = eig(full(A)) d = sort(d) d = d(end-k+1:end) but is most appropriate for large sparse matrices. If the problem fits into memory, it may be quicker to use eig(full(A)). Algorithm eigs provides the reverse communication required by the Fortran library ARPACK, namely the routines DSAUPD, DSEUPD, DNAUPD, DNEUPD, ZNAUPD, and ZNEUPD. Examples Example 1: This example shows the use of function handles. A = delsq(numgrid('C',15)); d1 = eigs(A,5,'sm'); Equivalently, if dnRk is the following one-line function: function y = dnRk(x,R,k) y = (delsq(numgrid(R,k))) * x; then pass dnRk's additional arguments, 'C' and 15, to eigs. n = size(A,1); opts.issym = 1; d2 = eigs(@dnRk,n,5,'sm',opts,'C',15); Example 2: west0479 is a real 479-by-479 sparse matrix with both real and pairs of complex conjugate eigenvalues. eig computes all 479 eigenvalues. eigs easily picks out the largest magnitude eigenvalues. This plot shows the 8 largest magnitude eigenvalues of west0479 as computed by eig and eigs. load west0479 d = eig(full(west0479)) dlm = eigs(west0479,8) 2-476 eigs [dum,ind] = sort(abs(d)); plot(dlm,'k+') hold on plot(d(ind(end-7:end)),'ks') hold off legend('eigs(west0479,8)','eig(full(west0479))') 2000 eigs(west0479,8) eig(full(west0479)) 1500 1000 500 0 500 1000 1500 2000 150 100 50 0 50 100 150 Example 3: A = delsq(numgrid('C',30)) is a symmetric positive definite matrix of size 632 with eigenvalues reasonably well-distributed in the interval (0 8), but with 18 eigenvalues repeated at 4. The eig function computes all 632 eigenvalues. It computes and plots the six largest and smallest magnitude eigenvalues of A successfully with: A = delsq(numgrid('C',30)); d = eig(full(A)); [dum,ind] = sort(abs(d)); dlm = eigs(A); dsm = eigs(A,6,'sm'); 2-477 eigs subplot(2,1,1) plot(dlm,'k+') hold on plot(d(ind(end:-1:end-5)),'ks') hold off legend('eigs(A)','eig(full(A))',3) set(gca,'XLim',[0.5 6.5]) subplot(2,1,2) plot(dsm,'k+') hold on plot(d(ind(1:6)),'ks') hold off legend('eigs(A,6,''sm'')','eig(full(A))',2) set(gca,'XLim',[0.5 6.5]) 8 7.95 7.9 7.85 eigs(A) eig(full(A)) 7.8 1 2 3 4 5 6 0.2 eigs(A,6, SM ) eig(full(A)) 0.15 0.1 0.05 0 1 2 3 4 5 6 However, the repeated eigenvalue at 4 must be handled more carefully. The call eigs(A,18,4.0) to compute 18 eigenvalues near 4.0 tries to find eigenvalues of A - 4.0*I. This involves divisions of the form 1/ 2-478 eigs (lambda - 4.0), where lambda is an estimate of an eigenvalue of A. As lambda gets closer to 4.0, eigs fails. We must use sigma near but not equal to 4 to find those 18 eigenvalues. sigma = 4 - 1e-6 [V,D] = eigs(A,18,sigma) The plot shows the 20 eigenvalues closest to 4 that were computed by eig, along with the 18 eigenvalues closest to 4 - 1e-6 that were computed by eigs. 18 repeated eigenvalues of delsq(numgrid( C ,30)) at 4 4.03 eigs(A,18,sigma) eig(A) 4.02 4.01 4 3.99 3.98 3.97 2 4 6 8 10 12 14 16 18 20 See Also References arpackc, eig, svds [1] Lehoucq, R.B. and D.C. Sorensen, Deflation Techniques for an Implicitly Re-Started Arnoldi Iteration, SIAM J. Matrix Analysis and Applications, Vol. 17, 1996, pp. 789-821. [2] Lehoucq, R.B., D.C. Sorensen, and C. Yang, ARPACK Users' Guide: Solution of Large-Scale Eigenvalue Problems with Implicitly Restarted Arnoldi Methods, SIAM Publications, Philadelphia, 1998. 2-479 eigs [3] Sorensen, D.C., Implicit Application of Polynomial Filters in a k-Step Arnoldi Method, SIAM J. Matrix Analysis and Applications, Vol. 13, 1992, pp. 357-385. 2-480 ellipj Purpose Syntax De nition 2ellipj Jacobi elliptic functions [SN,CN,DN] [SN,CN,DN] = = ellipj(U,M) ellipj(U,M,tol) The Jacobi elliptic functions are defined in terms of the integral: u = Then sn ( u ) = sin , cn ( u ) = cos , dn ( u ) = ( 1 m sin2 ) 2, am ( u ) = Some definitions of the elliptic functions use the modulus k instead of the parameter m . They are related by k 2 = m = sin2 The Jacobi elliptic functions obey many mathematical identities; for a good sample, see [1]. 1 -- 0 ------------------------------------2 ( 1 m sin ) 2 1 -- d Description [SN,CN,DN] = ellipj(U,M) returns the Jacobi elliptic functions SN, CN, and DN, evaluated for corresponding elements of argument U and parameter M. Inputs U and M must be the same size (or either can be scalar). [SN,CN,DN] = ellipj(U,M,tol) computes the Jacobi elliptic functions to accuracy tol. The default is eps; increase this for a less accurate but more quickly computed answer. Algorithm ellipj computes the Jacobi elliptic functions using the method of the arithmetic-geometric mean [1]. It starts with the triplet of numbers: a 0 = 1, b 0 = ( 1 m ) , c 0 = ( m ) 1 -2 1 -2 2-481 ellipj ellipj computes successive iterates with 1 a i = -- ( a i 1 + b i 1 ) 2 1 -bi = ( ai 1 bi 1 ) 2 1 c i = -- ( a i 1 b i 1 ) 2 Next, it calculates the amplitudes in radians using: cn sin ( 2 n 1 n ) = ----- sin ( n ) an being careful to unwrap the phases correctly. The Jacobian elliptic functions are then simply: sn ( u ) = sin 0 cn ( u ) = cos 0 dn ( u ) = ( 1 m sn ( u ) ) 2 2 1 -- Limitations The ellipj function is limited to the input domain 0 m 1 . Map other values of M into this range using the transformations described in [1], equations 16.10 and 16.11. U is limited to real values. ellipke See Also References [1] Abramowitz, M. and I.A. Stegun, Handbook of Mathematical Functions, Dover Publications, 1965, 17.6. 2-482 ellipke Purpose Syntax 2ellipke Complete elliptic integrals of the first and second kind K = ellipke(M) [K,E] = ellipke(M) [K,E] = ellipke(M,tol) De nition The complete elliptic integral of the first kind [1] is K (m) = F( 2 m) where F , the elliptic integral of the first kind, is K (m) = 0 1 [ ( 1 t 2 ) ( 1 mt 2 ) ] 2 dt = 1 ----- 0 -2 ( 1 m sin2 ) 2 d 1 ----- The complete elliptic integral of the second kind E ( m ) = E ( K ( m ) ) = E 2|m is E(m) = 0 1 ( 1 t 2 ) 2 ( 1 mt 2 ) 2 dt = 1 ----- 1 -- 0 ( 1 m sin2 ) d -2 1 -2 Some definitions of K and E use the modulus k instead of the parameter m . They are related by k 2 = m = sin2 Description K = ellipke(M) returns the complete elliptic integral of the first kind for the elements of M. [K,E] = ellipke(M) returns the complete elliptic integral of the first and second kinds. [K,E] = ellipke(M,tol) computes the Jacobian elliptic functions to accuracy tol. The default is eps; increase this for a less accurate but more quickly computed answer. 2-483 ellipke Algorithm ellipke computes the complete elliptic integral using the method of the arithmetic-geometric mean described in [1], section 17.6. It starts with the triplet of numbers a 0 = 1, b 0 = ( 1 m ) 2, c 0 = ( m ) 2 1 -1 -- ellipke computes successive iterations of a i , b i , and c i with 1 a i = -- ( a i 1 + b i 1 ) 2 1 -bi = ( ai 1 bi 1 ) 2 1 c i = -- ( a i 1 b i 1 ) 2 stopping at iteration n when cn 0 , within the tolerance specified by eps. The complete elliptic integral of the first kind is then K ( m ) = --------2a n Limitations See Also References ellipke is limited to the input domain 0 m 1 . ellipj [1] Abramowitz, M. and I.A. Stegun, Handbook of Mathematical Functions, Dover Publications, 1965, 17.6. 2-484 ellipsoid Purpose Syntax 2ellipsoid Generate ellipsoid [x,y,z] = ellipsoid(xc,yc,zc,xr,yr,zr,n) [x,y,z] = ellipsoid(xc,yc,zc,xr,yr,zr) ellipsoid(...) [x,y,z] = ellipsoid(xc,yc,zc,xr,yr,zr,n) generates three n+1-by-n+1 matrices so that surf(x,y,z) produces an ellipsoid with center (xc,yc,zc) and radii (xr,yr,zr). [x,y,z] = ellipsoid(xc,yc,zc,xr,yr,zr) uses n = 20. ellipsoid(...) with no output arguments graphs the ellipsoid as a surface. Description Algorithm ellipsoid generates the data using the following equation: ( x xc ) ( y yc ) ( z zc ) ---------------------- + ---------------------- + --------------------2 2 2 xr yr zr 2 2 2 See Also cylinder, sphere, surf 2-485 else Purpose Syntax 2else Conditionally execute statements if expression statements1 else statements2 end else is used to delineate an alternate block of statements. If expression evaluates as false, MATLAB executes the one or more commands denoted here as statements2. Description A true expression has either a logical true or nonzero value. For nonscalar expressions, (for example, if (matrix A is less than matrix B) ), true means that every element of the resulting matrix has a logical true or nonzero value. Expressions usually involve relational operations such as (count < limit) or isreal(A). Simple expressions can be combined by logical operators (&,|,~) into compound expressions such as: (count < limit) & ((height - offset) >= 0). See if for more information. Examples In this example, if both of the conditions are not satisfied, then the student fails the course. if ((attendance >= 0.90) & (grade_average >= 60)) pass = 1; else fail = 1; end; See Also if, elseif, end, for, while, switch, break, return, relational_operators, logical_operators 2-486 elseif Purpose Syntax 2elseif Conditionally execute statements if expression1 statements1 elseif expression2 statements2 end Description If expression1 evaluates as false and expression2 as true, MATLAB executes the one or more commands denoted here as statements2. A true expression has either a logical true or nonzero value. For nonscalar expressions, (for example, is matrix A less then matrix B), true means that every element of the resulting matrix has a logical true or nonzero value. Expressions usually involve relational operations such as (count < limit) or isreal(A). Simple expressions can be combined by logical operators (&,|,~) into compound expressions such as: (count < limit) & ((height - offset) >= 0). See if for more information. Remarks else if, with a space between the else and the if, differs from elseif, with no space. The former introduces a new, nested if, which must have a matching end. The latter is used in a linear sequence of conditional statements with only one terminating end. The two segments shown below produce identical results. Exactly one of the four assignments to x is executed, depending upon the values of the three logical expressions, A, B, and C. if A x = a else if B x = b else if C x = c else x = d if A x = a elseif B x = b elseif C x = c else x = d end 2-487 elseif end end end Examples Here is an example showing if, else, and elseif. for m = 1:k for n = 1:k if m == n a(m,n) = 2; elseif abs(m-n) == 2 a(m,n) = 1; else a(m,n) = 0; end end end For k=5 you get the matrix a = 2 0 1 0 0 0 2 0 1 0 1 0 2 0 1 0 1 0 2 0 0 0 1 0 2 See Also if, else, end, for, while, switch, break, return, relational_operators, logical_operators 2-488 end Purpose Syntax 2end Terminate for, while, switch, try, and if statements or indicate last index while expression% (or if, for, or try) statements end B = A(index:end,index) Description end is used to terminate for, while, switch, try, and if statements. Without an end statement, for, while, switch, try, and if wait for further input. Each end is paired with the closest previous unpaired for, while, switch, try, or if and serves to delimit its scope. The end command also serves as the last index in an indexing expression. In that context, end = (size(x,k)) when used as part of the kth index. Examples of this use are X(3:end) and X(1,1:2:end-1). When using end to grow an array, as in X(end+1)=5, make sure X exists first. You can overload the end statement for a user object by defining an end method for the object. The end method should have the calling sequence end(obj,k,n), where obj is the user object, k is the index in the expression where the end syntax is used, and n is the total number of indices in the expression. For example, consider the expression A(end-1,:) MATLAB will call the end method defined for A using the syntax end(A,1,2) Examples This example shows end used with the for and if statements. for k = 1:n if a(k) == 0 a(k) = a(k) + 2; end end In this example, end is used in an indexing expression. A = magic(5) 2-489 end A = 17 23 4 10 11 24 5 6 12 18 1 7 13 19 25 8 14 20 21 2 15 16 22 3 9 B = A(end,2:end) B = 18 25 2 9 See Also break, for, if, return, switch, try, while 2-490 eomday Purpose Syntax Description Examples 2eomday End of month E = eomday(Y,M) E = eomday(Y,M) returns the last day of the year and month given by corresponding elements of arrays Y and M. Because 1996 is a leap year, the statement eomday(1996,2) returns 29. To show all the leap years in this century, try: y = 1900:1999; E = eomday(y,2 ones(length(y),1)'); y(find(E==29))' ans = Columns 1 through 6 1904 1908 Columns 7 through 12 1928 1932 Columns 13 through 18 1952 1956 Columns 19 through 24 1976 1980 1912 1916 1920 1924 1936 1940 1944 1948 1960 1964 1968 1972 1984 1988 1992 1996 See Also datenum, datevec, weekday 2-491 eps Purpose Syntax Description 2eps Floating-point relative accuracy eps eps returns the distance from 1.0 to the next largest floating-point number. The value eps is a default tolerance for pinv and rank, as well as several other MATLAB functions. eps = 2^(-52), which is roughly 2.22e-16. See Also realmax, realmin 2-492 erf, erfc, erfcx, erfinv, erfcinv Purpose Syntax 2erf, erfc, erfcx, erfinv, erfcinv Error functions Y Y Y X X = = = = = erf(X) erfc(X) erfcx(X) erfinv(Y) erfcinv(Y) Error function Complementary error function Scaled complementary error function Inverse error function Inverse complementary error function De nition The error function erf(X) is twice the integral of the Gaussian distribution with 0 mean and variance of 1 2 . erf ( x ) = -----2 0 e t dt 2 x The complementary error function erfc(X) is defined as erfc ( x ) = -----2 x e t dt 2 2 = 1 erf ( x ) The scaled complementary error function erfcx(X) is defined as erfcx ( x ) = e x erfc ( x ) 1 1 - For large X, erfcx(X) is approximately ------ - x Description Y = erf(X) returns the value of the error function for each element of real array X. Y = erfc(X) computes the value of the complementary error function. Y = erfcx(X) computes the value of the scaled complementary error function. X = erfinv(Y) returns the value of the inverse error function for each element of Y. Elements of Y must be in the interval [-1 1]. The function erfinv satisfies y = erf( x) for 1 y 1 and x . X = erfcinv(Y) returns the value of the inverse of the complementary error function for each element of Y. Elements of Y must be in the interval [0 2]. The function erfcinv satisfies y = erfc( x) for 2 y 0 and x . 2-493 erf, erfc, erfcx, erfinv, erfcinv Remarks The relationship between the complementary error function erfc and the standard normal probability distribution returned by the Statistics Toolbox function normcdf is normcdf ( x ) = 0.5 * erfc ( x 2) The relationship between the inverse complementary error function erfcinv and the inverse standard normal probability distribution returned by the Statistics Toolbox function norminv is norminv ( p ) = 2 * erfcinv ( 2 p ) Examples erfinv(1) is Inf erfinv(-1) is -Inf. For abs(Y) > 1, erfinv(Y) is NaN. Algorithms For the error functions, the MATLAB code is a translation of a Fortran program by W. J. Cody, Argonne National Laboratory, NETLIB/SPECFUN, March 19, 1990. The main computation evaluates near-minimax rational approximations from [1]. For the inverse of the error function, rational approximations accurate to approximately six significant digits are used to generate an initial approximation, which is then improved to full accuracy by one step of Halley s method. References [1] Cody, W. J., Rational Chebyshev Approximations for the Error Function, Math. Comp., pgs. 631-638, 1969 2-494 error Purpose Syntax Description 2error Display error messages error('error_message') error('error_message') displays an error message and returns control to the keyboard. The error message contains the input string error_message. The error command has no effect if error_message is a null string. Examples The error command provides an error return from M-files. function foo(x,y) if nargin ~= 2 error('Wrong number of input arguments') end The returned error message looks like: foo(pi) ??? Error using ==> foo Wrong number of input arguments See Also dbstop, disp, lasterr, warning, errordlg 2-495 errorbar Purpose Syntax 2errorbar Plot error bars along a curve errorbar(Y,E) errorbar(X,Y,E) errorbar(X,Y,L,U) errorbar(...,LineSpec) h = errorbar(...) Description Error bars show the confidence level of data or the deviation along a curve. errorbar(Y,E) plots Y and draws an error bar at each element of Y. The error bar is a distance of E(i) above and below the curve so that each bar is symmetric and 2*E(i) long. errorbar(X,Y,E) plots X versus Y with symmetric error bars 2*E(i) long. X, Y, E must be the same size. When they are vectors, each error bar is a distance of E(i) above and below the point defined by (X(i),Y(i)). When they are matrices, each error bar is a distance of E(i,j) above and below the point defined by (X(i,j),Y(i,j)). errorbar(X,Y,L,U) plots X versus Y with error bars L(i)+U(i) long specifying the lower and upper error bars. X, Y, L, and U must be the same size. When they are vectors, each error bar is a distance of L(i) below and U(i) above the point defined by (X(i),Y(i)). When they are matrices, each error bar is a distance of L(i,j) below and U(i,j) above the point defined by (X(i,j),Y(i,j)). errorbar(...,LineSpec) draws the error bars using the line type, marker symbol, and color specified by LineSpec. h = errorbar(...) returns a vector of handles to line graphics objects. Remarks Examples When the arguments are all matrices, errorbar draws one line per matrix column. If X and Y are vectors, they specify one curve. Draw symmetric error bars that are two standard deviation units in length. X = 0:pi/10:pi; Y = sin(X); E = std(Y)*ones(size(X)); 2-496 errorbar errorbar(X,Y,E) 1.4 1.2 1 0.8 0.6 0.4 0.2 0 0.2 0.4 0.5 0 0.5 1 1.5 2 2.5 3 3.5 See Also LineSpec, plot, std 2-497 errordlg Purpose Syntax 2errordlg Create and display an error dialog box errordlg errordlg('errorstring') errordlg('errorstring','dlgname') errordlg('errorstring','dlgname','on') h = errordlg(...) errordlg creates an error dialog box, or if the named dialog exists, errordlg Description pops the named dialog in front of other windows. errordlg displays a dialog box named 'Error Dialog' that contains the string 'This is the default error string.' errordlg('errorstring') displays a dialog box named 'Error Dialog' that contains the string 'errorstring'. errordlg('errorstring','dlgname') displays a dialog box named 'dlgname' that contains the string 'errorstring'. errordlg('errorstring','dlgname','on') specifies whether to replace an existing dialog box having the same name. 'on' brings an existing error dialog having the same name to the foreground. In this case, errordlg does not create a new dialog. h = errordlg(...) returns the handle of the dialog box. Remarks MATLAB sizes the dialog box to fit the string 'errorstring'. The error dialog box has an OK pushbutton and remains on the screen until you press the OK button or the Return key. After pressing the button, the error dialog box disappears. The appearance of the dialog box depends on the windowing system you use. Examples The function errordlg('File not found','File Error'); 2-498 errordlg displays this dialog box on a UNIX system: See Also dialog, helpdlg, msgbox, questdlg, warndlg 2-499 etime Purpose Syntax Description 2etime Elapsed time e = etime(t2,t1) e = etime(t2,t1) returns the time in seconds between vectors t1 and t2. The two vectors must be six elements long, in the format returned by clock: T = [Year Month Day Hour Minute Second] Examples Calculate how long a 2048-point real FFT takes. x = rand(2048,1); t = clock; fft(x); etime(clock,t) ans = 0.4167 Limitations As currently implemented, the etime function fails across month and year boundaries. Since etime is an M-file, you can modify the code to work across these boundaries if needed. clock, cputime, tic, toc See Also 2-500 etree Purpose Syntax 2etree Elimination tree p = etree(A) p = etree(A,'col') p = etree(A,'sym') [p,q] = etree(...) p = etree(A) returns an elimination tree for the square symmetric matrix whose upper triangle is that of A. p(j) is the parent of column j in the tree, or 0 if j is a root. p = etree(A,'col') returns the elimination tree of A'*A. p = etree(A,'sym') is the same as p = etree(A). [p,q] = etree(...) also returns a postorder permutation q of the tree. Description See Also treelayout, treeplot, etreeplot 2-501 etreeplot Purpose Syntax Description 2etreeplot Plot elimination tree etreeplot(A) etreeplot(A,nodeSpec,edgeSpec) etreeplot(A) plots the elimination tree of A (or A+A', if non-symmetric). etreeplot(A,nodeSpec,edgeSpec) allows optional parameters nodeSpec and edgeSpec to set the node or edge color, marker, and linestyle. Use '' to omit one or both. See Also etree, treeplot, treelayout 2-502 eval Purpose Syntax 2eval Execute a string containing a MATLAB expression eval(expression) eval(expression,catch_expr) [a1,a2,a3,...] = eval(function(b1,b2,b3,...)) eval(expression) executes expression, a string containing any valid MATLAB expression. You can construct expression by concatenating substrings and variables inside square brackets: expression = [string1,int2str(var),string2,...] eval(expression,catch_expr) executes expression and, if an error is detected, executes the catch_expr string. If expression produces an error, the error string can be obtained with the lasterr function. This syntax is useful when expression is a string that must be constructed from substrings. If this is not the case, use the try...catch control flow statement in your code. [a1,a2,a3,...] = eval(function(b1,b2,b3,...)) executes function with arguments b1,b2,b3,..., and returns the results in the specified output Description variables. Remarks Using the eval output argument list is recommended over including the output arguments in the expression string. The first syntax below avoids strict checking by the MATLAB parser and can produce untrapped errors and other unexpected behavior. eval('[a1,a2,a3,...] = function(var)') [a1,a2,a3,...] = eval('function(var)') % not recommended % recommended syntax Examples This for loop generates a sequence of 12 matrices named M1 through M12: for n = 1:12 magic_str = ['M',int2str(n),' = magic(n)']; eval(magic_str) end 2-503 eval This example uses a function showdemo that runs a MATLAB demo selected by the user. If an error is encountered, a message is displayed that names the demo that failed. function showdemo(demos) errstring = 'Error running demo: '; n = input('Select a demo number: '); eval(demos(n,:),'[errstring demos(n,:)]') % ----- end of file showdemo.m ----D = ['odedemo'; 'quademo'; 'fitdemo']; showdemo(D) Select a demo number: 2 ans = Error running demo: quademo The next example executes the size function on a 3-dimensional array, returning the array dimensions in output variables d1, d2, and d3. A = magic(4); A(:,:,2) = A'; [d1,d2,d3] = eval('size(A)') d1 = 4 d2 = 4 d3 = 2 See Also assignin, catch, evalin, feval, lasterr, try 2-504 evalc Purpose Syntax 2evalc Evaluate MATLAB expression with capture T = evalc(S) T = evalc(s1,s2) [T,X,Y,Z,...] = evalc(S) T = evalc(S) is the same as eval(S) except that anything that would normally Description be written to the command window is captured and returned in the character array T (lines in T are separated by \n characters). T = evalc(s1,s2) is the same as eval(s1,s2) except that any output is captured into T. [T,X,Y,Z,...] = evalc(S) is the same as [X,Y,Z,...] = eval(S) except that any output is captured into T. Remark See Also When you are using evalc, diary, more, and input are disabled. diary, eval, evalin, input, more 2-505 evalin Purpose Syntax 2evalin Execute a string containing a MATLAB expression in a workspace evalin(ws,expression) [a1,a2,a3,...] = evalin(ws,expression) evalin(ws,expression,catch_expr) evalin(ws,expression) executes expression, a string containing any valid MATLAB expression, in the context of the workspace ws. ws can have a value of 'base' or 'caller' to denote the MATLAB base workspace or the workspace of the caller function. You can construct expression by concatenating Description substrings and variables inside square brackets: expression = [string1,int2str(var),string2,...] [a1,a2,a3,...] = evalin(ws,expression) executes expression and returns the results in the specified output variables. Using the evalin output argument list is recommended over including the output arguments in the expression string: evalin(ws,'[a1,a2,a3,...] = function(var)') The above syntax avoids strict checking by the MATLAB parser and can produce untrapped errors and other unexpected behavior. evalin(ws,expression,catch_expr) executes expression and, if an error is detected, executes the catch_expr string. If expression produces an error, the error string can be obtained with the lasterr function. This syntax is useful when expression is a string that must be constructed from substrings. If this is not the case, use the try...catch control flow statement in your code. Remarks The MATLAB base workspace is the workspace that is seen from the MATLAB command line (when not in the debugger). The caller workspace is the workspace of the function that called the M-file. Note, the base and caller workspaces are equivalent in the context of an M-file that is invoked from the MATLAB command line. This example extracts the value of the variable var in the MATLAB base workspace and captures the value in the local variable v: v = evalin( base , var ); Examples 2-506 evalin Limitation evalin cannot be used recursively to evaluate an expression. For example, a sequence of the form evalin('caller','evalin(''caller'',''x'')') doesn't work. See Also assignin, catch, eval, feval, lasterr, try 2-507 exist Purpose Graphical Interface Syntax 2exist Check if a variable or file exists As an alternative to the exist function, use the Workspace browser or the Current Directory Browser. To open either, select Workspace or Current Directory from the View menu in the MATLAB desktop. exist item exist item kind a = exist('item',...) exist item returns the status of the variable or file, item: 0 1 2 3 4 5 6 7 8 Description If item does not exist. If the variable item exists in the workspace. If item is an M- le or a le of unknown type. If item is a MEX- le on your MATLAB search path. If item is an MDL- le on your MATLAB search path. If item is a built-in MATLAB function. If item is a P- le on your MATLAB search path. If item is a directory. If item is a Java class. If item specifies a filename, that filename may include an extension to preclude conflicting with other similar filenames. For example, exist('file.ext'). MEX, MDL, and P-files must be on the MATLAB search path for exist to return the values shown above. If item is found, but is not on the MATLAB search path, exist('item') returns 2, because it considers item to be an unknown file type. Any other file type or directory specified by item is not required to be on the MATLAB search path to be recognized by exist. If the file or directory is not on the search path, then item must specify either a full pathname, a partial pathname relative to MATLABPATH, or a partial pathname relative to your current directory. 2-508 exist If item is a Java class, then exist('item') returns an 8. However, if item is a Java class file, then exist('item') returns a 2. exist item kind returns logical true (1), if an item of the specified kind is found; otherwise, it returns 0. The kind argument may be one of the following: builtin class dir file var Checks only for built-in functions. Checks only for Java classes. Checks only for directories. Checks only for les or directories. Checks only for variables. a = exist('item',...) returns the status of the variable or file in variable a. Remarks To check for the existence of more than one variable, use the ismember function. For example, a = 5.83; c = 'teststring'; ismember({'a','b','c'},who) ans = 1 0 1 Examples This example uses exist to check whether a MATLAB function is a built-in function or a file. type = exist('plot') type = 5 plot is a built-in function. 2-509 exist In the following example, exist returns 8 on the Java class, Welcome, and returns 2 on the Java class file, Welcome.class. exist Welcome ans = 8 exist javaclasses/Welcome.class ans = 2 indicates there is a Java class Welcome and a Java class file Welcome.class. See Also dir, help, lookfor, partialpath, what, which, who 2-510 exit Purpose Graphical Interface Syntax Description See Also 2exit Terminate MATLAB (same as quit) As an alternative to the exit function, select Exit MATLAB from the File menu or click the close box in the MATLAB desktop. exit exit ends the current MATLAB session. It is the same as quit. See quit for termination options. quit 2-511 exp Purpose Syntax Description 2exp Exponential Y = exp(X) The exp function is an elementary function that operates element-wise on arrays. Its domain includes complex numbers. Y = exp(X) returns the exponential for each element of X. For complex z = x + i* y , it returns the complex exponential e z = e x ( cos ( y ) + i sin ( y ) ) . Remark See Also Use expm for matrix exponentials. expm, log, log10, expint 2-512 expint Purpose Syntax De nitions 2expint Exponential integral Y = expint(X) The exponential integral computed by this function is defined as E 1( x) = x e t ------ dt t Another common definition of the exponential integral function is the Cauchy principal value integral Ei ( x ) = ---- dt t x et which, for real positive x, is related to expint as E 1 ( x ) = Ei ( x ) i Description References Y = expint(X) evaluates the exponential integral for each element of X. [1] Abramowitz, M. and I. A. Stegun. Handbook of Mathematical Functions. Chapter 5, New York: Dover Publications, 1965. 2-513 expm Purpose Syntax Description 2expm Matrix exponential Y = expm(X) Y = expm(X) raises the constant e to the matrix power X. The expm function produces complex results if X has nonpositive eigenvalues. Use exp for the element-by-element exponential. Algorithm expm is a built-in function that uses the Pad approximation with scaling and squaring. You can see the coding of this algorithm in the expm1 demo. Note The expm1, expm2, and expm3 demos illustrate the use of Pad approximation, Taylor series approximation, and eigenvalues and eigenvectors, respectively, to compute the matrix exponential. References [1] and [2] describe and compare many algorithms for computing a matrix exponential. The built-in method, expm, is essentially method 3 of [2]. Examples This example computes and compares the matrix exponential of A and the exponential of A. A = [1 0 0 expm(A) ans = 2.7183 0 0 exp(A) ans = 2.7183 1.0000 1.0000 1 0 0 0 2 -1 ]; 1.7183 1.0000 0 1.0862 1.2642 0.3679 2.7183 1.0000 1.0000 1.0000 7.3891 0.3679 2-514 expm Notice that the diagonal elements of the two results are equal. This would be true for any triangular matrix. But the off-diagonal elements, including those below the diagonal, are different. See Also References exp, funm, logm, sqrtm [1] Golub, G. H. and C. F. Van Loan, Matrix Computation, p. 384, Johns Hopkins University Press, 1983. [2] Moler, C. B. and C. F. Van Loan, Nineteen Dubious Ways to Compute the Exponential of a Matrix, SIAM Review 20, 1979, pp. 801-836. 2-515 eye Purpose Syntax 2eye Identity matrix Y Y Y Y Y = = = = eye(n) eye(m,n) eye(size(A)) eye(n) returns the n-by-n identity matrix. Description = eye(m,n) or eye([m n]) returns an m-by-n matrix with 1 s on the diagonal and 0 s elsewhere. Y = eye(size(A)) returns an identity matrix the same size as A. Limitations See Also The identity matrix is not defined for higher-dimensional arrays. The assignment y = eye([2,3,4]) results in an error. ones, rand, randn, zeros 2-516 ezcontour Purpose Syntax 2ezcontour Easy to use contour plotter ezcontour(f) ezcontour(f,domain) ezcontour(...,n) ezcontour(f) plots the contour lines of f(x,y), where f is a string that Description represents a mathematical function of two variables, such as x and y. The function f is plotted over the default domain: -2 < x < 2 , -2 < y < 2 . MATLAB chooses the computational grid according to the amount of variation that occurs; if the function f is not defined (singular) for points on the grid, then these points are not plotted. ezcontour(f,domain) plots f(x,y) over the specified domain. domain can be either a 4-by-1 vector [xmin, xmax, ymin, ymax] or a 2-by-1 vector [min, max] (where min < x < max, min < y < max). If f is a function of the variables u and v (rather than x and y), then the domain endpoints umin, umax, vmin, and vmax are sorted alphabetically. Thus, ezcontour('u^2 - v^3',[0,1],[3,6]) plots the contour lines for u2 - v3 over 0 < u < 1, 3 < v < 6. ezcontour(...,n) plots f over the default domain using an n-by-n grid. The default value for n is 60. ezcontour automatically adds a title and axis labels. Remarks Array multiplication, division, and exponentiation are always implied in the expression you pass to ezcontour. For example, the MATLAB syntax for a contour plot of the expression, sqrt(x.^2 + y.^2) is written as: ezcontour('sqrt(x^2 + y^2)') That is, x^2 is interpreted as x.^2 in the string you pass to ezcontour. Examples The following mathematical expression defines a function of two variables, x and y. 2-517 ezcontour 1 x 2 2 2 2 10 -- x 3 y 5 e x y -- e ( x + 1 ) y 5 3 ezcontour requires a string argument that expresses this function using MATLAB syntax to represent exponents, natural logs, etc. This function is represented by the string: f ( x, y ) = 3 ( 1 x ) 2 e x 2 ( y + 1 )2 f = ['3*(1 x)^2*exp( (x^2) (y+1)^2)',... ' 10*(x/5 x^3 y^5)*exp(-x^2 y^2)',... '- 1/3*exp( (x+1)^2 y^2)']; For convenience, this string is written on three lines and concatenated into one string using square brackets. Pass the string variable f to ezcontour along with a domain ranging from 3 to 3 and specify a computational grid of 49-by-49: ezcontour(f,[-3,3],49) 3 (1 x)2 exp( (x2) (y+1)2) ~~~ x2 y2) 1/3 exp( (x+1)2 y2) 3 2 1 0 y 1 2 3 3 2 1 0 x 1 2 3 In this particular case, the title is too long to fit at the top of the graph so MATLAB abbreviates the string. 2-518 ezcontour See Also contour, ezcontourf, ezmesh, ezmeshc, ezplot, ezplot3, ezpolar, ezsurf, ezsurfc 2-519 ezcontourf Purpose Syntax 2ezcontourf Easy to use filled contour plotter ezcontourf(f) ezcontourf(f,domain) ezcontourf(...,n) ezcontourf(f) plots the contour lines of f(x,y), where f is a string that Description represents a mathematical function of two variables, such as x and y. The function f is plotted over the default domain: -2 < x < 2 , -2 < y < 2 . MATLAB chooses the computational grid according to the amount of variation that occurs; if the function f is not defined (singular) for points on the grid, then these points are not plotted. ezcontourf(f,domain) plots f(x,y) over the specified domain. domain can be either a 4-by-1 vector [xmin, xmax, ymin, ymax] or a 2-by-1 vector [min, max] (where, min < x < max, min < y < max). If f is a function of the variables u and v (rather than x and y), then the domain endpoints umin, umax, vmin, and vmax are sorted alphabetically. Thus, ezcontourf('u^2 - v^3',[0,1],[3,6]) plots the contour lines for u2 - v3 over 0 < u < 1, 3 < v < 6. ezcontourf(...,n) plots f over the default domain using an n-by-n grid. The default value for n is 60. ezcontourf automatically adds a title and axis labels. Remarks Array multiplication, division, and exponentiation are always implied in the expression you pass to ezcontourf. For example, the MATLAB syntax for a filled contour plot of the expression, sqrt(x.^2 + y.^2); is written as: ezcontourf('sqrt(x^2 + y^2)') That is, x^2 is interpreted as x.^2 in the string you pass to ezcontourf. Examples The following mathematical expression defines a function of two variables, x and y. 2-520 ezcontourf 1 x 2 2 2 2 10 -- x 3 y 5 e x y -- e ( x + 1 ) y 5 3 ezcontourf requires a string argument that expresses this function using MATLAB syntax to represent exponents, natural logs, etc. This function is represented by the string: f ( x, y ) = 3 ( 1 x ) 2 e x 2 ( y + 1 )2 f = ['3*(1 x)^2*exp( (x^2) (y+1)^2)',... ' 10*(x/5 x^3 y^5)*exp(-x^2 y^2)',... '- 1/3*exp( (x+1)^2 y^2)']; For convenience, this string is written on three lines and concatenated into one string using square brackets. Pass the string variable f to ezcontourf along with a domain ranging from 3 to 3 and specify a grid of 49-by-49: ezcontourf(f,[-3,3],49) 3 (1 x)2 exp( (x2) (y+1)2) ~~~ x2 y2) 1/3 exp( (x+1)2 y2) 3 2 1 0 y 1 2 3 3 2 1 0 x 1 2 3 In this particular case, the title is too long to fit at the top of the graph so MATLAB abbreviates the string. 2-521 ezcontourf See Also contourf, ezcontour, ezmesh, ezmeshc, ezplot, ezplot3, ezpolar, ezsurf, ezsurfc 2-522 ezmesh Purpose Syntax 2ezmesh Easy to use 3-D mesh plotter ezmesh(f) ezmesh(f,domain) ezmesh(x,y,z) ezmesh(x,y,z,[smin,smax,tmin,tmax]) or ezmesh(x,y,z,[min,max]) ezmesh(...,n) ezmesh(...,'circ') ezmesh(f) creates a graph of f(x,y), where f is a string that represents a mathematical function of two variables, such as x and y. Description The function f is plotted over the default domain: -2 < x < 2 , -2 < y < 2 . MATLAB chooses the computational grid according to the amount of variation that occurs; if the function f is not defined (singular) for points on the grid, then these points are not plotted. ezmesh(f,domain) plots f over the specified domain. domain can be either a 4-by-1 vector [xmin, xmax, ymin, ymax] or a 2-by-1 vector [min, max] (where, min < x < max, min < y < max). If f is a function of the variables u and v (rather than x and y), then the domain endpoints umin, umax, vmin, and vmax are sorted alphabetically. Thus, ezmesh('u^2 - v^3',[0,1],[3,6]) plots u2 - v3 over 0 < u < 1, 3 < v < 6. ezmesh(x,y,z) plots the parametric surface x = x(s,t), y = y(s,t), and z = z(s,t) over the square: -2 < s < 2 , -2 < t < 2 . ezmesh(x,y,z,[smin,smax,tmin,tmax]) or ezmesh(x,y,z,[min,max]) plots the parametric surface using the specified domain. ezmesh(...,n) plots f over the default domain using an n-by-n grid. The default value for n is 60. ezmesh(...,'circ') plots f over a disk centered on the domain. Remarks rotate3d is always on. To rotate the graph, click and drag with the mouse. Array multiplication, division, and exponentiation are always implied in the expression you pass to ezmesh. For example, the MATLAB syntax for a mesh plot of the expression, 2-523 ezmesh sqrt(x.^2 + y.^2); is written as: ezmesh('sqrt(x^2 + y^2)') That is, x^2 is interpreted as x.^2 in the string you pass to ezmesh. Examples This example visualizes the function, f ( x, y ) = xe x y 2 2 with a mesh plot drawn on a 40-by-40 grid. The mesh lines are set to a uniform blue color by setting the colormap to a single color: ezmesh('x*exp(-x^2-y^2)',40) colormap [0 0 1] x exp( x2 y2) 0.5 0 0.5 2 1 0 1 y 2 2 x 0 2 See Also ezcontour, ezcontourf, ezmeshc, ezplot, ezplot3, ezpolar, ezsurf, ezsurfc, mesh 2-524 ezmeshc Purpose Syntax 2ezmeshc Easy to use combination mesh/contour plotter ezmeshc(f) ezmeshc(f,domain) ezmeshc(x,y,z) ezmeshc(x,y,z,[smin,smax,tmin,tmax]) or ezmeshc(x,y,z,[min,max]) ezmeshc(...,n) ezmeshc(...,'circ') ezmeshc(f) creates a graph of f(x,y), where f is a string that represents a Description mathematical function of two variables, such as x and y. The function f is plotted over the default domain: -2 < x < 2 , -2 < y < 2 . MATLAB chooses the computational grid according to the amount of variation that occurs; if the function f is not defined (singular) for points on the grid, then these points are not plotted. ezmeshc(f,domain) plots f over the specified domain. domain can be either a 4-by-1 vector [xmin, xmax, ymin, ymax] or a 2-by-1 vector [min, max] (where, min < x < max, min < y < max). If f is a function of the variables u and v (rather than x and y), then the domain endpoints umin, umax, vmin, and vmax are sorted alphabetically. Thus, ezmeshc('u^2 - v^3',[0,1],[3,6]) plots u2 - v3 over 0 < u < 1, 3 < v < 6. ezmeshc(x,y,z) plots the parametric surface x = x(s,t), y = y(s,t), and z = z(s,t) over the square: -2 < s < 2 , -2 < t < 2 . ezmeshc(x,y,z,[smin,smax,tmin,tmax]) or ezmeshc(x,y,z,[min,max]) plots the parametric surface using the specified domain. ezmeshc(...,n) plots f over the default domain using an n-by-n grid. The default value for n is 60. ezmeshc(...,'circ') plots f over a disk centered on the domain. Remarks rotate3d is always on. To rotate the graph, click and drag with the mouse. Array multiplication, division, and exponentiation are always implied in the expression you pass to ezmeshc. For example, the MATLAB syntax for a mesh/ contour plot of the expression, 2-525 ezmeshc sqrt(x.^2 + y.^2); is written as: ezmeshc('sqrt(x^2 + y^2)') That is, x^2 is interpreted as x.^2 in the string you pass to ezmeshc. Examples Create a mesh/contour graph of the expression, y f ( x, y ) = --------------------------2 2 1+x + y over the domain -5 < x < 5, -2*pi < y < 2*pi: ezmeshc('y/(1 + x^2 + y^2)',[ 5,5, 2*pi,2*pi]) Use the mouse to rotate the axes to better observe the contour lines (this picture uses a view of azimuth = -65.5 and elevation = 26). y/(1 + x2 + y2) 0.5 0 5 0.5 5 0 5 y 5 x 0 See Also ezcontour, ezcontourf, ezmesh, ezplot, ezplot3, ezpolar, ezsurf, ezsurfc, meshc 2-526 ezplot Purpose Syntax 2ezplot Easy to use function plotter ezplot(f) ezplot(f,[min,max]) ezplot(f,[xmin,xmax,ymin,ymax]) ezplot(x,y) ezplot(x,y,[tmin,tmax]) ezplot(...,figure) ezplot(f) plots the expression f = f(x) over the default domain: -2 < x < 2 . ezplot(f,[min,max]) plots f = f(x) over the domain: min < x < max. Description For implicitly defined functions, f = f(x,y): ezplot(f) plots f(x,y) = 0 over the default domain -2 < x < 2 , -2 < y < 2 . ezplot(f,[xmin,xmax,ymin,ymax]) plots f(x,y) = 0 over xmin < x < xmax and ymin < y < ymax. ezplot(f,[min,max])plots f(x,y) = 0 over min < x < max and min < y < max. If f is a function of the variables u and v (rather than x and y), then the domain endpoints umin, umax, vmin, and vmax are sorted alphabetically. Thus, ezplot('u^2 - v^2 - 1',[-3,2,-2,3]) plots u2 - v2 - 1 = 0 over -3 < u < 2, -2 < v < 3. ezplot(x,y) plots the parametrically defined planar curve x = x(t) and y = y(t) over the default domain 0 < t < 2 . ezplot(x,y,[tmin,tmax]) plots x = x(t) and y = y(t) over tmin < t < tmax. ezplot(...,figure) plots the given function over the specified domain in the figure window identified by the handle figure. Remarks Array multiplication, division, and exponentiation are always implied in the expression you pass to ezplot. For example, the MATLAB syntax for a plot of the expression, x.^2 - y.^2 which represents an implicitly defined function, is written as: ezplot('x^2 - y^2') 2-527 ezplot That is, x^2 is interpreted as x.^2 in the string you pass to ezplot. Examples This example plots the implicitly defined function, x2 - y4 = 0 over the domain [-2 , 2 ]: ezplot('x^2-y^4') x2 y4 = 0 6 4 2 0 y 2 4 6 6 4 2 0 x 2 4 6 See Also ezcontour, ezcontourf, ezmesh, ezmeshc, ezplot3, ezpolar, ezsurf, ezsurfc, plot 2-528 ezplot3 Purpose Syntax 2ezplot3 Easy to use 3-D parametric curve plotter ezplot3(x,y,z) ezplot3(x,y,z,[tmin,tmax]) ezplot3(...,'animate') ezplot3(x,y,z) plots the spatial curve x = x(t), y = y(t), and z = z(t) over the Description default domain 0 < t < 2 . ezplot3(x,y,z,[tmin,tmax]) plots the curve x = x(t), y = y(t), and z = z(t) over the domain tmin < t < tmax. ezplot3(...,'animate') produces an animated trace of the spatial curve. Remarks Array multiplication, division, and exponentiation are always implied in the expression you pass to ezplot3. For example, the MATLAB syntax for a plot of the expression, x = s./2, y = 2.*s, z = s.^2; which represents a parametric function, is written as: ezplot3('s/2','2*s','s^2') That is, s/2 is interpreted as s./2 in the string you pass to ezplot3. Examples This example plots the parametric curve, x = sin t , y = cos t , z=t over the domain [0,6 ]: ezplot3('sin(t)','cos(t)','t',[0,6*pi]) 2-529 ezplot3 x = sin(t), y = cos(t), z = t 20 15 z 10 5 0 1 0.5 0 0.5 y 1 1 0 0.5 x 0.5 1 See Also ezcontour, ezcontourf, ezmesh, ezmeshc, ezplot, ezpolar, ezsurf, ezsurfc, plot3 2-530 ezpolar Purpose Syntax Description 2ezpolar Easy to use polar coordinate plotter ezpolar(f) ezpolar(f,[a,b]) ezpolar(f) plots the polar curve rho = f(theta) over the default domain 0 < theta < 2 . ezpolar(f,[a,b]) plots f for a < theta < b. Examples This example creates a polar plot of the function, 1 + cos(t) over the domain [0, 2 ]: ezpolar('1+cos(t)') 90 120 1.5 2 60 150 1 30 0.5 180 0 210 330 240 270 r = 1+cos(t) 300 See Also ezplot, ezplot3, ezsurf, plot, plot3, polar 2-531 ezsurf Purpose Syntax 2ezsurf Easy to use 3-D colored surface plotter ezsurf(f) ezsurf(f,domain) ezsurf(x,y,z) ezsurf(x,y,z,[smin,smax,tmin,tmax]) or ezsurf(x,y,z,[min,max]) ezsurf(...,n) ezsurf(...,'circ') ezsurf(f) creates a graph of f(x,y), where f is a string that represents a mathematical function of two variables, such as x and y. Description The function f is plotted over the default domain: -2 < x < 2 , -2 < y < 2 . MATLAB chooses the computational grid according to the amount of variation that occurs; if the function f is not defined (singular) for points on the grid, then these points are not plotted. ezsurf(f,domain) plots f over the specified domain. domain can be either a 4-by-1 vector [xmin, xmax, ymin, ymax] or a 2-by-1 vector [min, max] (where, min < x < max, min < y < max). If f is a function of the variables u and v (rather than x and y), then the domain endpoints umin, umax, vmin, and vmax are sorted alphabetically. Thus, ezsurf('u^2 - v^3',[0,1],[3,6]) plots u2 - v3 over 0 < u < 1, 3 < v < 6. ezsurf(x,y,z) plots the parametric surface x = x(s,t), y = y(s,t), and z = z(s,t) over the square: -2 < s < 2 , -2 < t < 2 . ezsurf(x,y,z,[smin,smax,tmin,tmax]) or ezsurf(x,y,z,[min,max]) plots the parametric surface using the specified domain. ezsurf(...,n) plots f over the default domain using an n-by-n grid. The default value for n is 60. ezsurf(...,'circ') plots f over a disk centered on the domain. Remarks rotate3d is always on. To rotate the graph, click and drag with the mouse. Array multiplication, division, and exponentiation are always implied in the expression you pass to ezsurf. For example, the MATLAB syntax for a surface plot of the expression, 2-532 ezsurf sqrt(x.^2 + y.^2); is written as: ezsurf('sqrt(x^2 + y^2)') That is, x^2 is interpreted as x.^2 in the string you pass to ezsurf. Examples ezsurf does not graph points where the mathematical function is not defined (these data points are set to NaNs, which MATLAB does not plot). This example illustrates this filtering of singularities/discontinuous points by graphing the function, f ( x, y) = real ( atan ( x + iy ) ) over the default domain -2 < x < 2 , -2 < y < 2 : ezsurf('real(atan(x+i*y))') real(atan(x+i y)) 2 1 0 1 2 5 5 0 y 5 5 x 0 Using surf to plot the same data produces a graph without filtering of discontinuities (as well as requiring more steps): [x,y] = meshgrid(linspace(-2*pi,2*pi,60)); z = real(atan(x+i.*y)); 2-533 ezsurf surf(x,y,z) 2 1 0 1 2 10 5 0 5 10 10 5 5 0 10 Note also that ezsurf creates graphs that have axis labels, a title, and extend to the axis limits. See Also ezcontour, ezcontourf, ezmesh, ezmeshc, ezplot, ezpolar, ezsurfc, surf 2-534 ezsurfc Purpose Syntax 2ezsurfc Easy to use combination surface/contour plotter ezsurfc(f) ezsurfc(f,domain) ezsurfc(x,y,z) ezsurfc(x,y,z,[smin,smax,tmin,tmax]) or ezsurfc(x,y,z,[min,max]) ezsurfc(...,n) ezsurfc(...,'circ') ezsurfc(f) creates a graph of f(x,y), where f is a string that represents a Description mathematical function of two variables, such as x and y. The function f is plotted over the default domain: -2 < x < 2 , -2 < y < 2 . MATLAB chooses the computational grid according to the amount of variation that occurs; if the function f is not defined (singular) for points on the grid, then these points are not plotted. ezsurfc(f,domain) plots f over the specified domain. domain can be either a 4-by-1 vector [xmin, xmax, ymin, ymax] or a 2-by-1 vector [min, max] (where, min < x < max, min < y < max). If f is a function of the variables u and v (rather than x and y), then the domain endpoints umin, umax, vmin, and vmax are sorted alphabetically. Thus, ezsurfc('u^2 - v^3',[0,1],[3,6]) plots u2 - v3 over 0 < u < 1, 3 < v < 6. ezsurfc(x,y,z) plots the parametric surface x = x(s,t), y = y(s,t), and z = z(s,t) over the square: -2 < s < 2 , -2 < t < 2 . ezsurfc(x,y,z,[smin,smax,tmin,tmax]) or ezsurfc(x,y,z,[min,max]) plots the parametric surface using the specified domain. ezsurfc(...,n) plots f over the default domain using an n-by-n grid. The default value for n is 60. ezsurfc(...,'circ') plots f over a disk centered on the domain. Remarks rotate3d is always on. To rotate the graph, click and drag with the mouse. Array multiplication, division, and exponentiation are always implied in the expression you pass to ezsurfc. For example, the MATLAB syntax for a surface/contour plot of the experssion, 2-535 ezsurfc sqrt(x.^2 + y.^2); is written as: ezsurfc('sqrt(x^2 + y^2)') That is, x^2 is interpreted as x.^2 in the string you pass to ezsurfc. Examples Create a surface/contour plot of the expression, y f ( x, y ) = --------------------------2 2 1+x + y over the domain -5 < x < 5, -2*pi < y < 2*pi, with a computational grid of size 35-by-35: ezsurfc('y/(1 + x^2 + y^2)',[ 5,5, 2*pi,2*pi],35) Use the mouse to rotate the axes to better observe the contour lines (this picture uses a view of azimuth = -65.5 and elevation = 26) y/(1 + x2 + y2) 0.5 0 5 0.5 5 0 5 y 5 x 0 2-536 ezsurfc See Also ezcontour, ezcontourf, ezmesh, ezmeshc, ezplot, ezpolar, ezsurf, surfc 2-537 ezsurfc 2-538 Index Symbols ! 2-22 - 2-10 % 2-22 & 2-20 ' 2-10, 2-22 ( ) 2-22 * 2-10 + 2-10 , 2-22 . 2-22 ... 2-22 .avi 2-78 / 2-10 : 2-25 < 2-18 = 2-22 == 2-18 > 2-18 \ 2-10 ^ 2-10 {} 2-22 | 2-20 ~ 2-20 ~= 2-18 acsc 2-32 acsch 2-32 ActiveX object methods actxcontrol 2-34 actxserver 2-37 delete 2-428 actxcontrol 2-34 actxserver 2-37 addframe AVI files 2-38 addition (arithmetic operator) 2-10 addpath 2-40 addressing selected array elements 2-25 adjacency graph 2-455 airy 2-42 ALim, Axes property 2-96 all 2-45 AmbientLightColor, Axes property 2-96 and (M-file function equivalent for &) 2-20 AND, logical bit-wise 2-160 angle 2-53 ans 2-54 any 2-55 A abs 2-27 accuracy of linear equation solution 2-301 of matrix inversion 2-301 relative floating-point 2-492 acos 2-28 acosh 2-28 acot 2-30 acoth 2-30 arccosecant 2-32 arccosine 2-28 arccotangent 2-30 arcsecant 2-59 arcsine 2-61 arctangent 2-65 (four-quadrant) 2-67 area 2-57 arithmetic operations, matrix and array distinguished 2-10 arithmetic operators I-1 Index reference 2-10 array addressing selected elements of 2-25 displaying 2-447 left division (arithmetic operator) 2-11 multiplication (arithmetic operator) 2-10 power (arithmetic operator) 2-11 right division (arithmetic operator) 2-11 transpose (arithmetic operator) 2-11 arrays maximum size of 2-299 arrowhead matrix 2-291 ASCII delimited files writing 2-454 ASCII data printable characters (list of) 2-239 reading 2-453 asec 2-59 asech 2-59 asin 2-61 asinh 2-61 aviread 2-83 Axes creating 2-84 defining default properties 2-88 fixed-width font 2-105 property descriptions 2-96 axes setting and querying data aspect ratio 2-364 axes 2-84 axis 2-117 B balance 2-123 bar 2-126 bar3 2-130 bar3h 2-130 barh 2-126 base to decimal conversion 2-134 base two operations conversion from decimal to binary 2-409 base2dec 2-134 aspect ratio of axes 2-364 assignin 2-63 atan 2-65 atan2 2-67 atanh 2-65 .au files reading 2-76 writing 2-77 audio saving in AVI format 2-78 audioplayer 2-69 audiorecorder 2-72 auwrite 2-77 avifile 2-78 aviinfo 2-81 beep 2-135 Bessel functions 2-136, 2-141 first kind 2-138 modified 2-138 second kind 2-139 third kind 2-142 Bessel s equation (defined) 2-136, 2-141 modified (defined) 2-138 besselh 2-136 besseli 2-138 besselj 2-141 besselk 2-138 bessely 2-141 beta 2-144 I-2 Index beta function (defined) 2-144 incomplete (defined) 2-144 natural logarithm of 2-144 betainc 2-144 betaln 2-144 bicg 2-146 bicgstab 2-154 bin2dec 2-159 resuming execution from 2-380 setting in M-files 2-389 brighten 2-172 builtin 2-173 BusyAction Axes property 2-97 ButtonDownFcn Axes property 2-97 bvp4c 2-174 bvpget 2-181 bvpinit 2-182 bvpset 2-184 bvpval 2-186 binary to decimal conversion 2-159 bitand 2-160 bitcmp 2-161 bitget 2-162 bitmax 2-163 bitor 2-164 bitset 2-165 bitshift 2-166 C calendar 2-187 camdolly 2-188 bit-wise operations AND 2-160 get 2-162 OR 2-164 set bit 2-165 shift 2-166 XOR 2-167 bitxor 2-167 blanks removing trailing 2-407 blanks 2-168 blkdiag 2-169 box 2-170 Box, Axes property 2-97 braces, curly (special characters) 2-22 brackets (special characters) 2-22 break 2-171 breakpoints listing 2-387 removing 2-378 camera dollying position 2-188 moving camera and target postions 2-188 placing a light at 2-190 positioning to view objects 2-192 rotating around camera target 2-194, 2-196 rotating around viewing axis 2-200 setting and querying position 2-197 setting and querying projection type 2-199 setting and querying target 2-201 setting and querying up vector 2-203 setting and querying view angle 2-205 CameraPosition, Axes property 2-98 CameraPositionMode, Axes property 2-98 CameraTarget, Axes property 2-98 CameraTargetMode, Axes property 2-98 CameraUpVector, Axes property 2-98 CameraUpVectorMode, Axes property 2-98 CameraViewAngle, Axes property 2-99 I-3 Index CameraViewAngleMode, Axes property 2-99 camlight 2-190 camlookat 2-192 camorbit 2-194 campan 2-196 campos 2-197 camproj 2-199 camroll 2-200 camtarget 2-201 camup 2-203 camva 2-205 camzoom 2-207 capture 2-208 cart2pol 2-209 cart2sph 2-210 options 2-241 checkout 2-243 examples 2-244 options 2-243 Children Axes property 2-100 chol 2-246 Cholesky factorization 2-246 (as algorithm for solving linear equations) 2-14 preordering for 2-291 cholinc 2-248 cholinc 2-248 cholupdate 2-255 Cartesian coordinates 2-209, 2-210 case 2-211 cat 2-212 catch 2-213 caxis 2-214 cd 2-218 cdf2rdf 2-219 cdfinfo 2-221 cdfread 2-224 ceil 2-226 cell 2-227 cholupdate 2-255 cla 2-258 clabel 2-259 class 2-261 clc 2-263, 2-269 clear 2-264 clear cell array creating 2-227 structure of, displaying 2-233 cell2struct 2-229 celldisp 2-230 cellfun 2-231 cellplot 2-233 cgs 2-235 char 2-239 checkin 2-241 serial port I/O 2-268 clearing Command Window 2-263 items from workspace 2-264 Java import list 2-265 clf 2-269 CLim, Axes property 2-100 CLimMode, Axes property 2-100 clipboard 2-270 Clipping Axes property 2-100 clock 2-271 close 2-272 examples 2-242 AVI files 2-274 closest point search 2-465 cmopts 2-276 modifying for PVCS 2-276 I-4 Index colamd 2-277 colmmd 2-279 Color condition number of matrix 2-123, 2-301 coneplot 2-304 conj 2-309 Axes property 2-101 colorbar 2-282 colormap 2-285 ColorOrder, Axes property 2-101 ColorSpec 2-289 colperm 2-291 comet 2-292 comet3 2-293 comma (special characters) 2-24 Command Window clearing 2-263 compan 2-294 companion matrix 2-294 compass 2-295 complementary error function (defined) 2-493 scaled (defined) 2-493 complete elliptic integral (defined) 2-483 modulus of 2-481, 2-483 complex exponential (defined) 2-512 phase angle 2-53 complex 2-297 conjugate, complex 2-309 sorting pairs of 2-345 continuation (..., special characters) 2-23 continue 2-310 contour and mesh plot 2-525 filled plot 2-520 functions 2-517 of mathematical expression 2-517 with surface plot 2-535 contour 2-311 contour3 2-315 contourc 2-317 contourf 2-319 contours in slice planes 2-321 contourslice 2-321 contrast 2-324 conv 2-325 conv2 2-326 complex conjugate 2-309 sorting pairs of 2-345 complex data creating 2-297 computer 2-299 computer MATLAB is running on 2-299 concatenating arrays 2-212 cond 2-301 condeig 2-302 condest 2-303 conversion base to decimal 2-134 binary to decimal 2-159 Cartesian to cylindrical 2-209 Cartesian to polar 2-209 complex diagonal to real block diagonal 2-219 decimal number to base 2-405, 2-408 decimal to binary 2-409 decimal to hexadecimal 2-410 string matrix to cell array 2-234 vector to character string 2-239 convex hulls multidimensional vizualization 2-333 two-dimensional vizualization 2-331 I-5 Index convhull 2-331 convhulln 2-333 convn 2-335 csc 2-348 csch 2-348 csvread 2-350 csvwrite 2-352 ctranspose (M-file function equivalent for ') 2-12 cumprod 2-353 cumsum 2-354 cumtrapz 2-355 convolution 2-325 inverse See deconvolution two-dimensional 2-326 coordinates Cartesian 2-209, 2-210 cylindrical 2-209, 2-210 polar 2-209, 2-210 See also conversion copyfile 2-336 copyobj 2-337 corrcoef 2-339 cos 2-340 cumulative product 2-353 sum 2-354 curl 2-357 curly braces (special characters) 2-22 current directory changing 2-218 CurrentPoint cosecant 2-348 hyperbolic 2-348 inverse 2-32 inverse hyperbolic 2-32 cosh 2-340 Axes property 2-101 customverctrl 2-360 cylinder 2-361 cylindrical coordinates 2-209, 2-210 cosine 2-340 hyperbolic 2-340 inverse 2-28 inverse hyperbolic 2-28 cot 2-342 D daspect 2-364 cotangent 2-342 hyperbolic 2-342 inverse 2-30 inverse hyperbolic 2-30 coth 2-342 cov 2-344 cplxpair 2-345 cputime 2-346 CreateFcn data aspect ratio of axes 2-364 data types complex 2-297 DataAspectRatio, Axes property 2-102 DataAspectRatioMode, Axes property 2-104 date 2-367 date and time functions 2-491 date string format of 2-370 date vector 2-376 datenum 2-368 datestr 2-370 datevec 2-376 Axes property 2-101 cross 2-347 cross product 2-347 I-6 Index dbclear 2-378 dbcont 2-380 dbdown 2-381 dblquad 2-382 dbmex 2-384 dbquit 2-385 dbstack 2-386 dbstatus 2-387 dbstep 2-388 dbstop 2-389 dbtype 2-393 dbup 2-394 ddeadv 2-395 ddeexec 2-397 ddeinit 2-398 ddepoke 2-399 ddereq 2-401 ddeterm 2-403 ddeunadv 2-404 deal 2-405 deblank 2-407 to distinguish matrix and array operations 2-10 decomposition Dulmage-Mendelsohn 2-455 deconv 2-411 deconvolution 2-411 default tolerance 2-492 default4 2-412 del operator 2-413 del2 2-413 delaunay 2-416 Delaunay tessellation 3-dimensional vizualization 2-421 multidimensional vizualization 2-424 Delaunay triangulation vizualization 2-416 delaunay3 2-421 delaunayn 2-424 delete 2-427, 2-428 delete serial port I/O 2-429 DeleteFcn debugging changing workspace context 2-381 changing workspace to calling M-file 2-394 displaying function call stack 2-386 MEX-files on UNIX 2-384 quitting debug mode 2-385 removing breakpoints 2-378 resuming execution from breakpoint 2-388 setting breakpoints in 2-389 stepping through lines 2-388 dec2base 2-405, 2-408 dec2bin 2-409 dec2hex 2-410 Axes property 2-104 deleting files 2-427 items from workspace 2-264 delimiters in ASCII files 2-453, 2-454 depdir 2-430 depfun 2-431 derivative approximate 2-443 det 2-435 determinant of a matrix 2-435 detrend 2-436 deval 2-438 diag 2-439 decimal number to base conversion 2-405, 2-408 decimal point (.) (special characters) 2-23 diagonal 2-439 I-7 Index main 2-439 dialog 2-441 dmperm 2-455 doc 2-456 docopt 2-457 dialog box error 2-498 diary 2-442 diff 2-443 documentation location of files for UNIX 2-457 dolly camera 2-188 dot 2-460 differences between adjacent array elements 2-443 differential equation solvers ODE boundary value problems 2-174 adjusting parameters of 2-184 extracting properties of 2-181, 2-501, 2-502 forming an initial guess 2-182 dir 2-445 directories adding to search path 2-40 checking existence of 2-508 listing contents of 2-445 See also directory, search path directory See also directories directory, changing 2-218 discontinuities, plotting functions with 2-533 disp 2-447 disp dot product 2-347, 2-460 double 2-461 dragrect 2-462 DrawMode, Axes property 2-104 drawnow 2-463 dsearch 2-464 dsearchn 2-465 Dulmage-Mendelsohn decomposition 2-455 E echo 2-466 edge finding, Sobel technique 2-327 editing M-files 2-467 eig 2-469 serial port I/O 2-448 display 2-449 distribution Gaussian 2-493 division array, left (arithmetic operator) 2-11 array, right (arithmetic operator) 2-11 matrix, left (arithmetic operator) 2-11 matrix, right (arithmetic operator) 2-10 of polynomials 2-411 dlmread 2-453 dlmwrite 2-454 eigensystem transforming 2-219 eigenvalue accuracy of 2-123, 2-469 complex 2-219 of companion matrix 2-294 poorly conditioned 2-123 problem 2-470 problem, generalized 2-470 repeated 2-470 eigenvector left 2-470 right 2-470 eigs 2-473 I-8 Index ellipj 2-481 ellipke 2-483 elliptic functions, Jacobian (defined) 2-481 elliptic integral complete (defined) 2-483 modulus of 2-481, 2-483 else 2-486 elseif 2-487 end 2-489 end of line, indicating 2-24 eomday 2-491 eps 2-492 equal sign (special characters) 2-23 equations, linear accuracy of solution 2-301 erf 2-493 erfc 2-493 erfcinv 2-493 erfcx 2-493 erfinv 2-493 error 2-495 contouring mathematical expressions 2-517 mesh plot of mathematical function 2-524 mesh/contour plot 2-526 plotting filled contours 2-520 plotting function of two variables 2-528 plotting parametric curves 2-529 polar plot of function 2-531 surface plot of mathematical function 2-533 surface/contour plot 2-536 exclamation point (special characters) 2-24 execution resuming from breakpoint 2-380 exist 2-508 exit 2-511 exp 2-512 expint 2-513 expm 2-514 error function (defined) 2-493 complementary 2-493 scaled complementary 2-493 error message displaying 2-495 errorbar 2-496 errordlg 2-498 etime 2-500 etree 2-501 etreeplot 2-502 eval 2-503 evalc 2-505 evalin 2-506 exponential 2-512 complex (defined) 2-512 integral 2-513 matrix 2-514 exponentiation array (arithmetic operator) 2-11 matrix (arithmetic operator) 2-11 eye 2-516 ezcontour 2-517 ezcontourf 2-520 ezmesh 2-523 ezmeshc 2-525 ezplot 2-527 ezplot3 2-529 ezpolar 2-531 ezsurf 2-532 ezsurfc 2-535 examples I-9 Index F factorization, Cholesky 2-246 (as algorithm for solving linear equations) 2-14 preordering for 2-291 Figures updating from M-file 2-463 files ASCII delimited reading 2-453 writing 2-454 checking existence of 2-508 copying 2-336 deleting 2-427 listing names in a directory 2-445 sound reading 2-76 writing 2-77, 2-78 filter two-dimensional 2-326 fixed-width font axes 2-105 flint See floating-point, integer floating-point integer 2-161, 2-165 integer, maximum 2-163 numbers, interval between 2-492 flow control break 2-171 case 2-211 end 2-489 error 2-495 font fixed-width, axes 2-105 FontAngle FontName Axes property 2-105 FontSize Axes property 2-105 FontUnits Axes property 2-105 FontWeight Axes property 2-106 Fourier transform convolution theorem and 2-325 functions call stack for 2-386 checking existence of 2-508 clearing from workspace 2-264 G Gaussian distribution function 2-493 Gaussian elimination (as algorithm for solving linear equations) 2-15 generalized eigenvalue problem 2-470 generating a sequence of matrix names (M1 through M12) 2-503 global variables, clearing from workspace 2-264 graph adjacency 2-455 graphics objects Axes 2-84 graphics objects, deleting 2-427 GridLineStyle, Axes property 2-106 H HandleVisibility Axes property 2-104 Axes property 2-106 Hankel functions 2-136 Hankel functions, relationship to Bessel of 2-142 I-10 Index help files, location for UNIX 2-457 Help browser accessing from doc 2-456 HitTest Axes property 2-107 horzcat (M-file function equivalent for [,]) 2-24 Householder reflections (as algorithm for solving linear equations) 2-15 hyperbolic cosecant 2-348 cosecant, inverse 2-32 cosine 2-340 cosine, inverse 2-28 cotangent 2-342 cotangent, inverse 2-30 secant 2-59 secant, inverse 2-59 sine 2-61 sine, inverse 2-61 tangent 2-65 tangent, inverse 2-65 cotangent 2-30 four-quadrant tangent 2-67 hyperbolic cosecant 2-32 hyperbolic cosine 2-28 hyperbolic cotangent 2-30 hyperbolic secant 2-59 hyperbolic sine 2-61 hyperbolic tangent 2-65 secant 2-59 sine 2-61 tangent 2-65 inversion, matrix accuracy of 2-301 J Jacobian elliptic functions (defined) 2-481 Java class names 2-265 Java import list clearing 2-265 joining arrays See concatenating arrays I identity matrix 2-516 incomplete beta function (defined) 2-144 inheritance, of objects 2-262 integer floating-point 2-161, 2-165 floating-point, maximum 2-163 Interruptible L labeling matrix columns 2-447 Laplacian 2-413 Layer, Axes property 2-107 ldivide (M-file function equivalent for .\) 2-12 Light positioning in camera coordinates 2-190 line numbers in M-files 2-393 linear equation systems accuracy of solution 2-301 linear equation systems, methods for solving Axes property 2-107 inverse cosecant 2-32 cosine 2-28 I-11 Index Cholesky factorization 2-14 Gaussian elimination 2-15 Householder reflections 2-15 LineStyleOrder Axes property 2-108 LineWidth Axes property 2-108 Lobatto IIIa ODE solver 2-180 log saving session to file 2-442 logarithm of beta function (natural) 2-144 logical operations AND, bit-wise 2-160 OR, bit-wise 2-164 XOR, bit-wise 2-167 logical operators 2-20 logical tests all 2-45 any 2-55 M matrix addressing selected rows and columns of 2-25 arrowhead 2-291 companion 2-294 condition number of 2-123, 2-301 converting to vector 2-25 defective (defined) 2-471 determinant of 2-435 diagonal of 2-439 Dulmage-Mendelsohn decomposition of 2-455 exponential 2-514 identity 2-516 inversion, accuracy of 2-301 left division (arithmetic operator) 2-11 maximum size of 2-299 modal 2-469 multiplication (defined) 2-10 power (arithmetic operator) 2-11 reading files into 2-453 right division (arithmetic operator) 2-10 singularity, test for 2-435 trace of 2-439 transpose (arithmetic operator) 2-11 transposing 2-23 writing to ASCII delimited file 2-454 See also array matrix names, (M1 through M12) generating a sequence of 2-503 matrix power See matrix, exponential maximum matching 2-455 MDL-files checking existence of 2-508 memory clearing 2-264 methods inheritance of 2-262 MEX-files clearing from workspace 2-264 debugging on UNIX 2-384 M-file displaying during execution 2-466 function file, echoing 2-466 script file, echoing 2-466 M-files checking existence of 2-508 clearing from workspace 2-264 deleting 2-427 editing 2-467 line numbers, listing 2-393 setting breakpoints 2-389 minus (M-file function equivalent for -) 2-12 I-12 Index mldivide (M-file function equivalent for \) 2-12 modal matrix 2-469 movies exporting in AVI format 2-78 mpower (M-file function equivalent for ^) 2-12 mrdivide (M-file function equivalent for /) 2-12 mtimes (M-file function equivalent for *) 2-12 multidimensional arrays concatenating 2-212 multiplication array (arithmetic operator) 2-10 matrix (defined) 2-10 of polynomials 2-325 or (M-file function equivalent for |) 2-20 orthographic projection, setting and querying 2-199 P parametric curve, plotting 2-529 Parent N NextPlot Axes property 2-108 not (M-file function equivalent for ~) 2-20 numbers complex 2-53 O object inheritance 2-262 object classes, list of predefined 2-261 online help location of files for UNIX 2-457 operating system command, issuing 2-24 operators arithmetic 2-10 logical 2-20 relational 2-18 special characters 2-22 logical OR bit-wise 2-164 Axes property 2-109 parentheses (special characters) 2-23 path adding directories to 2-40 pauses, removing 2-378 percent sign (special characters) 2-24 period (.), to distinguish matrix and array operations 2-10 period (special characters) 2-23 perspective projection, setting and querying 2-199 P-files checking existence of 2-508 phase, complex 2-53 platform MATLAB is running on 2-299 PlotBoxAspectRatio, Axes property 2-109 PlotBoxAspectRatioMode, Axes property 2-109 plotting contours (a 2-517 contours (ez function) 2-517 errorbars 2-496 ez-function mesh plot 2-523 filled contours 2-520 functions with discontinuities 2-533 in polar coordinates 2-531 mathematical function 2-527 mesh contour plot 2-525 parametric curve 2-529 surfaces 2-532 I-13 Index velocity vectors 2-304 plus (M-file function equivalent for +) 2-12 polar coordinates 2-209, 2-210 plotting in 2-531 polynomial division 2-411 multiplication 2-325 poorly conditioned eigenvalues 2-123 Position relative accuracy floating-point 2-492 rolling camera 2-200 rotating camera 2-194 rotating camera target 2-196 round towards infinity 2-226 roundoff error convolution theorem and 2-325 effect on eigenvalues 2-123 Axes property 2-109 position of camera dollying 2-188 position of camera, setting and querying 2-197 power matrix See matrix exponential power (M-file function equivalent for .^) 2-12 printing, suppressing 2-24 product cumulative 2-353 of vectors (cross) 2-347 scalar (dot) 2-347 projection type, setting and querying 2-199 ProjectionType, Axes property 2-110 S saving session to a file 2-442 scalar product (of vectors) 2-347 scaled complementary error function (defined) 2-493 search path adding directories to 2-40 secant, inverse 2-59 secant, inverse hyperbolic 2-59 Selected Axes property 2-110 SelectionHighlight R rdivide (M-file function equivalent for ./) 2-12 rearranging arrays converting to vector 2-25 rearranging matrices converting to vector 2-25 transposing 2-23 reference page accessing from doc 2-456 regularly spaced vectors, creating 2-25 relational operators 2-18 Axes property 2-110 semicolon (special characters) 2-24 sequence of matrix names (M1 through M12) generating 2-503 session saving 2-442 sine, inverse 2-61 sine, inverse hyperbolic 2-61 single quote (special characters) 2-23 slice planes, contouring 2-321 sorting complex conjugate pairs 2-345 I-14 Index sound files reading 2-76 writing 2-77 source control systems checking in files 2-241 checking out files 2-243 viewing current system 2-276 sparse matrix minimum degree ordering of 2-279 permuting columns of 2-291 spreadsheets reading into a matrix 2-453 writing matrices into 2-454 stack, displaying 2-386 str2cell 2-234 stretch-to-fill 2-85 string converting from vector to 2-239 string matrix to cell array conversion 2-234 subsref (M-file function equivalent for A(i,j,k...)) 2-24 subtraction (arithmetic operator) 2-10 sum cumulative 2-354 Surface and contour plotter 2-535 plotting mathematical functions 2-532 test, logical See logical tests and detecting TickDir, Axes property 2-111 TickDirMode, Axes property 2-111 TickLength, Axes property 2-111 time CPU 2-346 required to execute commands 2-500 time and date functions 2-491 times (M-file function equivalent for .*) 2-12 Title, Axes property 2-111 tolerance, default 2-492 trace of a matrix 2-439 trailing blanks removing 2-407 transformation See also conversion transpose array (arithmetic operator) 2-11 matrix (arithmetic operator) 2-11 transpose (M-file function equivalent for .') 2-12 truth tables (for logical operations) 2-20 Type Axes property 2-112 U UIContextMenu Axes property 2-112 uminus (M-file function equivalent for unary ) 2-12 T Tag Units Axes property 2-110 tangent (four-quadrant), inverse 2-67 tangent, inverse 2-65 tangent, inverse hyperbolic 2-65 target, of camera 2-201 Axes property 2-112 up vector, of camera 2-203 updating figure during M-file execution 2-463 uplus (M-file function equivalent for unary +) 2-12 UserData I-15 Index Axes property 2-112 X XAxisLocation, Axes property 2-113 XColor, Axes property 2-113 XDir, Axes property 2-113 XGrid, Axes property 2-114 XLabel, Axes property 2-114 XLim, Axes property 2-114 XLimMode, Axes property 2-114 XMinorGrid, Axes property 2-115 V variables checking existence of 2-508 clearing from workspace 2-264 vector dot product 2-460 product (cross) 2-347 vector field, plotting 2-304 vectorizing ODE function (BVP) 2-185 vectors, creating regularly spaced 2-25 velocity vectors, plotting 2-304 vertcat (M-file function equivalent for [;]) 2-24 video saving in AVI format 2-78 view 2-192 view angle, of camera 2-205 View, Axes property (obsolete) 2-112 viewing a group of object 2-192 a specific object in a scene 2-192 Visible logical XOR bit-wise 2-167 XScale, Axes property 2-115 XTick, Axes property 2-115 XTickLabel, Axes property 2-115 XTickLabelMode, Axes property 2-116 XTickMode, Axes property 2-116 Y YAxisLocation, Axes property 2-113 YColor, Axes property 2-113 YDir, Axes property 2-113 YGrid, Axes property 2-114 YLabel, Axes property 2-114 YLim, Axes property 2-114 YLimMode, Axes property 2-114 YMinorGrid, Axes property 2-115 YScale, Axes property 2-115 YTick, Axes property 2-115 YTickLabel, Axes property 2-115 YTickLabelMode, Axes property 2-116 YTickMode, Axes property 2-116 Axes property 2-113 visualizing cell array structure 2-233 volumes contouring slice planes 2-321 W workspace changing context while debugging 2-381, 2-394 clearing items from 2-264 Z ZColor, Axes property 2-113 ZDir, Axes property 2-113 I-16 Index ZGrid, Axes property 2-114 ZLim, Axes property 2-114 ZLimMode, Axes property 2-114 ZMinorGrid, Axes property 2-115 ZScale, Axes property 2-115 ZTick, Axes property 2-115 ZTickLabel, Axes property 2-115 ZTickLabelMode, Axes property 2-116 ZTickMode, Axes property 2-116 I-17
Find millions of documents here - Study Guides, Homework Solutions, Papers, Exam Answer Keys and more.
Course Hero has millions of course related materials that will enable you to learn better,
faster and get an A in all your courses.
Below is a small sample set of documents:
Below is a small sample set of documents:
Pittsburgh >> ENGR >> 3097 (Fall, 2009)
IE 3097 Homework 2 Solutions 2 Asymptotic growth notation 1. Chapter 2, Solved Exercise 2 on page 66. You dont have to turn anything in. Try it rst without reading the solution. Then check the solution. Nothing to say here. 2. Chapter 2, Exercises 3 ...
Allan Hancock College >> WROFB >> 2008354 (Fall, 2009)
2008 THE LEGISLATIVE ASSEMBLY FOR THE AUSTRALIAN CAPITAL TERRITORY (As presented) (Minister for the Environment, Water and Climate Change) Water Resources (Validation of Fees) Bill 2008 A Bill for An Act to validate certain fees The Legislative ...
Pittsburgh >> MATH >> 0220 (Fall, 2008)
HW-7c Name 1. Integrate the following: (a) 3x cos x dx (b) 3 x ln x dx (c) arcsin x dx (d) x2 e2x dx (e) (x2 + 3x 4) ln x dx (f) sin x dx (let u = x so u2 = x and 2u du = dx) (g) e2x sin 3x dx 2. (a) x2 2 dx + 3x 1 (b) x...
Pittsburgh >> MATH >> 0220 (Fall, 2008)
EXAM I Name 1. When a camera ash goes o, the batteries immediately begin to recharge the ashs capacitor, which stores electric charge given by Q(t) = Q0 (1 et/2 ) (a) Determine the maximum charge capacity? (b) How long does it take to recharge th...
Pittsburgh >> MATH >> 230 (Spring, 2008)
First Miderm for Math 230 October 3, 2007 Last Name: First Name: Discussion Session(Your TAs name): 1. Evaluate the integral (a) (10 points) 1 1 2 3 dx; 1 x2 Solution: This is a type II improper integral. 1 1 2 3 dx 1 x2 t = lim t1 t1 1...
Pittsburgh >> IS >> 2935 (Fall, 2009)
Quiz 5, IS2935, Nov 6, 2003 Name : 1. Name 3 design principles and state what they mean. (3) Answer: a. Complete mediation: Check every access to an object to ensure that access is allowed. b. Least privilege: A subject should be given only those pr...
Pittsburgh >> TELCOM >> 2700 (Fall, 2008)
Richard K. Gilbert 11-10-2004 Assignment 4 1. How many physical channels are available in each IS-95 carrier? What type of coding separates these channels from one another? Physical channels: Physical channels are defined in terms of an RF frequenc...
Pittsburgh >> IS >> 2938 (Fall, 2009)
I N F O R M AT I O N P O L I C Y OF THE UNITED STATES CONSTITUTION PREPARED FOR DR. TONI CARBO PROFESSOR OF INFORMATION SCIENCE UNIVERSITY OF PITTSBURGH PREPARED BY RICHARD K. GILBERT INFSCI 2938 UNIVERSITY OF PITTSBURGH SEPTEMBER 16, 2004 2004 ...
Washington >> ENGL >> 198 (Fall, 2008)
English 198 Pronouns & Ambiguous Antecedents THIS THEY THEIR IT If the notation above appears in your essays, the antecedent to the pronoun is not clear. Pronoun = a word replacing a noun or noun phrase We use pronouns because they make spoken...
Washington >> LING >> 567 (Fall, 2008)
Knowledge Engineering for NLP January 21, 2009 The Grammar Matrix Overview Goals Architecture Technical details Grammar Matrix: Goals Speed-up precision grammar development Standardize semantic representations Bottom-up exploration of lingu...
Washington >> B >> 571 (Fall, 2009)
STAT/BIOSTAT 571: Takehome Exam Solution 1. 7 marks Informative plot. See Figure 1. 2. (a) 5 marks Interpretation. GEE assumes a marginal model so exp(1 ) is the average odds of illiteracy for native-born whites, across states in 1930. GLMM assumes a...
Washington >> PHYS >> 322 (Fall, 2008)
Controlling Electromagnetic Fields J. B. Pendry,1* D. Schurig,2 D. R. Smith2 Department of Physics, Blackett Laboratory, Imperial College London, London SW7 2AZ, UK. 2Department of Electrical and Computer Engineering, Duke University, Box 90291, Durh...
Washington >> B >> 537 (Fall, 2009)
...
Washington >> BIOEN >> 303 (Fall, 2008)
...
Washington >> BIOEN >> 303 (Fall, 2008)
BIOEN 303 AB Lab groups, Winter 2009 Find your name in the alphabetical list at the left, then read across to the appropriate lab number, then up or down to find your partner. Alicia Martin David Zhang Marissa Hackett Monica Kumar Anibel America Al...
Washington >> BIOEN >> 303 (Fall, 2008)
BIOEN 303 Bioengineering Signal Processing Winter 2009 Lab 6: IIR Filters Objectives: Design and test IIR filters that remove baseline wander from pulse oximetry data, and 60-Hz noise from ECG data. Consider the equivalence of feedback control lo...
Pepperdine >> BA >> 445 (Fall, 2009)
BA 445 Exam 1 (Version D) Dr. Jon Burke This is a 100-minute exam (1hr. 40 min.). There are 6 questions (about 16 minutes per question). The exam begins exactly at the normal time that class starts. To avoid the temptation to cheat, you cannot take...
Pepperdine >> BA >> 452 (Fall, 2009)
BA 452 Dr. Jon Burke Spring 2008 Pepperdine University Exam Grades Exam Score 3.85-4.00 3.50-3.84 Ltr Grade Final Version F 3.15-3.49 2.85-3.14 B+ B 2.50-2.84 B2.15-2.49 C+ 1.85-2.14 1.50-1.84 1.15-1.49 C CForm. Mixed 2 pts. 2.0 D+ 0.85-1.14 D 0-0....
Pepperdine >> BA >> 452 (Fall, 2009)
BA 452 Spring 2008 Exam 1 Version F 1 Find your code number in the first column to the left. Email Jon.Burke@Pepperdine.edu if you lost your code. 2 Each question is worth a maximum of 4 points. Those 4 points are divided into catagories that are sc...
Pepperdine >> BA >> 452 (Fall, 2009)
BA 452 Spring 2008 Exam 2 Version E 1 Find your code number in the first column to the left. Email Jon.Burke@Pepperdine.edu if you lost your code. 2 Each question is worth a maximum of 4 points. Those 4 points are divided into catagories that are sc...
Pepperdine >> BA >> 445 (Fall, 2009)
BA 445 Dr. Jon Burke Spring 2009 Pepperdine University Exam Grades Exam Score Ltr Grade Exam 1 Version D 3.85-4.00 A 3.50-3.84 A3.15-3.49 B+ 2.85-3.14 B 2.50-2.84 B2.15-2.49 C+ 1.85-2.14 C 1.50-1.84 C1.15-1.49 D+ 0.85-1.14 D 0-0.84 F Student Code ...
Washington >> ESC >> 210 (Fall, 2009)
Introduction to Soils ESC 210 Prof: Phone: Email: Office: Office hrs: TA: Email: Basics about the class Dr. Sally Brown 616 1299 slb@u.washington.edu 156B Bloedel MWF 9:30-10:30 Gage Wagoner gagew@u.washington.edu Text: Nature and Property of Soi...
Pittsburgh >> IS >> 2610 (Fall, 2009)
IS 2610: Data Structures Recursion, Divide and conquer Dynamic programming, Feb 2, 2004 Recursion and Trees n Recursive algorithm is one that solves a problem by solving one or more smaller instances of the same problem q q Functions that call th...
Erskine >> PH >> 120 (Fall, 2009)
PH 120: Principles of Physics I Work and Kinetic Energy 1. Form a team with one other person. Spring 2009 Activity 10, Chapter 7 2. Open the video in Logger Pro, and select the option that allows you to click on two points in each frame. 3. Drag ov...
Erskine >> PH >> 120 (Fall, 2009)
PH 120: Principles of Physics I Work and Kinetic Energy Spring 2009 Activity 9, Chapter 6 1. Form a team with someone you have not worked with before. 2. Consider a rolling chair being pushed horizontally. Draw a free-body diagram of the chair syst...
Mercer >> BA >> 056 (Fall, 2009)
MERCERIAN A Publication for Alumni and Friends of Mercer University Winter 2005 Volume 15, Number 1 THE Mercer Expands Offerings in Graduate Programs A wide variety of new graduate programs including business, education, music and health care ...
Pittsburgh >> CS >> 131 (Spring, 2008)
Part 1: Tables and Queries Introduction Microsoft Access is a database program A database is an organized set of information Excel is primarily useful for numerical information Access can be used for just about any type of info Creating a Tab...
Pittsburgh >> CS >> 131 (Spring, 2008)
Part 2: Animations Smart Art Process Create the title page as shown in the lab Add the Vertical Process SmartArt (go to the Insert tab, and click SmarArt; select Vertical Process) Fill in the SmartArt as shown Add the star shapes (Use the 4 thro...
Pittsburgh >> CS >> 131 (Spring, 2008)
University of Pittsburgh VERITAS ET VIRTUS Outline History of the University Founding Development of the Polio vaccine Historic Buildings The Cathedral of Learning Allegheny Observatory Athletics Football Basketball History of the Universi...
Pittsburgh >> CS >> 449 (Spring, 2008)
Race Condition Shared Data: 5 6 4 1 8 5 6 20 9 ? Synchronization and Deadlocks Jonathan Misurda jmisurda@cs.pitt.edu tail A[] Enqueue(): A[tail] = 20; tail+; thread switch A[tail] = 9; tail+; Thread 1 Thread 0 Critical Regions Enters critical ...
Pittsburgh >> CS >> 1550 (Fall, 2008)
Page Replacement Algorithms Optimal Not Recently Used (NRU) FIFO PAGE REPLACEMENT ALGORITHMS Second Chance Page Replacement Clock Algorithm H t=30 G t=29 F t=22 A t=32 t=0 B t=32 t=4 C t=32 t=8 D J t=32 t=15 referenced unreferenced A t=0 B t=4...
Pittsburgh >> CS >> 449 (Spring, 2008)
A Mystery #include <stdio.h> int main() { char a[10]; char b; scanf(\"%s\", a); printf(\"a is %s\ \", a); b = getchar(); printf(\"b is %c\ \", b); return 0; } BUFFERING: THE SILENT KILLER Jonathan Misurda jmisurda@cs.pitt.edu Output (16) thot $ ./a.out t...
Washington >> IS >> 300 (Fall, 2009)
IS300 Lab Session 2 Lab 2 Web Development Lab Topic Activating web publishing service Creating a simple web site Using webpage editor and ftp program Software Used We\'re going to use three kinds of software to do this: Microsoft FrontPage - design...
Embry-Riddle FL/AZ >> PS >> 150 (Fall, 2008)
Chapter 6 Work and Kinetic Energy Up until now, we have assumed that the force is constant and thus, the acceleration is constant. Is there a simple technique for dealing with non-constant forces? Fortunately, the answer is, Yes. In this chapter, we ...
Mercer >> ETM >> 645 (Fall, 2009)
...
Washington >> GS >> 559 (Winter, 2009)
Genome 559: Introduction to Statistical and Computational Genomics Winter 2009 Lecture 20b Exceptions Larry Ruzzo 1 1 Minute responses Today\'s freeform exercise was helpful in that it generated more questions to explore than it answered - things t...
Washington >> M >> 111 (Fall, 2009)
Compound Interest Review Problems 1. You make a deposit of $1000 into an account paying 8% annual interest, compounded monthly. How much money is in the account after 9 years? (Ans.: $2049.5302) 2. You open an account with $500. The account pays 7.3...
Washington >> M >> 120 (Fall, 2009)
Rational Function Sketching Example Graph h(x) = 2x2 + 4x 6 . x2 + 3x + 2 It will make things easier if we factor the numerator and denominator rst: h(x) = 2(x + 3)(x 1) . (x + 2)(x + 1) Find the domain: D = {all real x = 2, 1} Once youve foun...
Washington >> ME >> 557 (Fall, 2009)
Optical Sensor Technology Wei-Chih Wang University of Washington Department of Mechanical Engineering 1 W.Wang Objectives The main goal of this course is to introduce the characteristics of light that can be used to accomplish a variety of enginee...
Embry-Riddle FL/AZ >> ELEMENTS >> 0708 (Fall, 2009)
EMBRY-RIDDLE AT-A-GLANCE UNDERGRADUATE PROGRAMS AVIATION AND EMBRY-RIDDLE: THE LIFELONG PARTNERSHIP A t the beginning of the last century no flying schools existed, much less an aviation university. It was not until 1903 that the Wright brothers a...
Washington >> ENVIR >> 100 (Fall, 2008)
Population, Health, and Human Well-Being- United States United States Demographic and Health Indicators Total Population (in thousands of people) 1950 157,813 2002 288,530 2025 (projected) 346,822 Population Density (people per square km), 2000: 29.4...
Washington >> CHEM >> 419 (Spring, 2008)
Hemocyanin (Hc) Function: Found: MW: transports O2 lobster, octopus, crabs, etc. 50,000 g (octopus) 400,000 20,000,000 g (crabs) 6 (octopus) 10 20 (crabs) protein: active site: binuclear Cu2/ subunit DeoxyHc spectroscopically \"silent\" CuI...
UCSC >> CMPE >> 150 (Fall, 2008)
Winter 2009 PEM CMPE 150 Assignment #5 Solutions Due February 24, 2009 1. For the network of Figure 5.7a (and ignore the line weights), suppose flooding is used for the routing algorithm. If a packet is sent from E to D, with a maximum hop count o...
UCSC >> CMPE >> 150 (Fall, 2008)
CMPE 150 Winter 2009 Lecture 17 March 5, 2009 , Mantey P.E. CMPE 150 - Introduction to Computer Networks Instructor: Patrick Mantey mantey@soe.ucsc.edu http:/www.soe.ucsc.edu/~mantey/ htt / d / t / Office: Engr. 2 Room 595J Office hours: Tues 3-5...
UCSC >> CMPE >> 150 (Fall, 2008)
CMPE 150 Winter 2009 Lecture 12 February 17, 2009 y , P.E. Mantey CMPE 150 - Introduction to Computer Networks Instructor: Patrick Mantey mantey@soe.ucsc.edu http:/www.soe.ucsc.edu/~mantey/ htt / d / t / Office: Engr. 2 Room 595J Office hours: Tue...
UCSC >> CMPE >> 150 (Fall, 2008)
CMPE 150 Winter 2009 Lecture 15 February 26, 2009 y , P.E. Mantey CMPE 150 - Introduction to Computer Networks Instructor: Patrick Mantey mantey@soe.ucsc.edu http:/www.soe.ucsc.edu/~mantey/ htt / d / t / Office: Engr. 2 Room 595J Office hours: Tue...
UCSC >> BME >> 155 (Winter, 2008)
Course Reading Assignments Winter 2009 Textbook (T): B.R. Glick and JJ Pasternak (2003) Molecular Biotechnology, ASM Press. Reader Assignments (R): Reader for BME155/255, available from Bay Tree Bookshop Page 1 of 2 Students may also be given sets ...
UCSC >> CMPE >> 220 (Fall, 2008)
...
UCSC >> CMPE >> 220 (Fall, 2008)
...
UCSC >> CMPE >> 220 (Fall, 2008)
Thu Nov 20 19:02:09 PST 2008 <> Page 1 Thu Nov 20 19:02:09 PST 2008 <> Page 2 Page 1 ...
UCSC >> CMPE >> 220 (Fall, 2008)
CPU CUBLAS, CUFFT Application CUDA Libraries cuda* CUDA Runtime cu* CUDA Driver GPU (\"Device\") ...
Winona >> CS >> 116 (Fall, 2009)
CS 116 Web Technology Spring 2009 Course Description: CS 116 is an introductory, hands-on course on Web Site development. Students will learn how to plan and publish web sites and develop electronic portfolios that are exciting, efficient, accessibl...
Winona >> CS >> 116 (Fall, 2009)
About Lists ! Almost anything that isnt narrative text can be considered a list. Lists ! ! ! ! ! ! ! The Solar System (less Pluto!) Your family tree A recipe Your friends A table of contents PowerPoint\'s And so on Lists ! There are 3 different ki...
Winona >> CS >> 275 (Fall, 2009)
!\"#$%/(!-\'22( We all know that the sum of two even integers is an even integer. We learned that a long time ago. When you think about it, its just obvious, right? Well, for most of us, the fact that the sum of two even integers is ...
UCSC >> CE >> 185 (Fall, 2009)
CMPE 185: Punctuation/Grammar Professor Tara Madhyastha 1 Fonts and Formatting 4 Stick with plain, italic, bold, possibly fixed width for code 4 Use a large enough font 4 Wide enough margins 2 Periods 4 Periods end sentences. 4 Dont use at end o...
UCSC >> CS >> 290 (Fall, 2009)
wpP f ww w t w\"w$3 w{ i ir 4p fd1w w z wp xy w( B\"w t xi w t 1i{ !y \'Ai $ #{\"~p f y www{A pfT & pwPw{ tww 0 ~w w ) p 5ap!pww...
Maine >> BIO >> 621 (Fall, 2008)
Environmental and Ecological Statistics 11, 5571, 2004 Random denominators and the analysis of ratio data MARTIN LIERMANN,1* ASHLEY STEEL,1 M I C H A E L RO S I N G 2 and P E T E R G U T TO R P 3 Watershed Program, NW Fisheries Science Center, 2725 ...
UCSC >> ASTR >> 1110 (Fall, 2009)
APS 1010 Astronomy Lab 95 Kepler\'s Laws KEPLER\'S LAWS SYNOPSIS: Johannes Kepler formulated three laws that described how the planets orbit around the Sun. His work paved the way for Isaac Newton, who derived the underlying physical reasons why the...
UCSC >> CSE >> 185 (Winter, 2009)
Chapter 13 Progress Report 13.1 Goalswriting progress reports, making sure there is progress This assignment is an opportunity for you to tell us, in writing, how you are doing on your nal project. Put your progress report into the form of a memo. ...
UCSC >> SSO >> 2096 (Fall, 2009)
SSO2096.t06 n_notor2 6 5 4 3 2 1 NN S G X X NNN N N BN B H NBSB ABNBSP SN NNNSNHH NP N N S P S B N B P AA G GH N A N G G G F S XXXNSXAXXSXXNXXGXXXXHNXXGXXXXXX X X X H PB 1 10 20 30 40 N 6 5 4 3 2 1 P N H N H N H N H H 6 5 4 3 2 1 ...
UCSC >> YNL >> 178 (Fall, 2009)
YNL178W.t2k CB_BURIAL_14_7 3 2 1 AA X X 1 10 20 30 40 A 3 2 1 E F B D A D A E B D B E D B D F B D B A B D E E D E D B A B E D F D F B D E ABBDDE A E D C D E E D E C CCC A D CAFEDEDDCCACDCEEGCF E D A D E F F CE E DCCCCC FE D D X X...
UCSC >> YJL >> 187 (Fall, 2009)
YJL187C dssp-ehl2 2 1 1 10 20 30 40 H 2 1 H H H 51 60 70 80 90 H 2 1 101 110 120 130 140 E 2 1 151 160 170 180 190 2 1 201 210 220 230 240 2 1 251 260 270 280 290 2 1 301 310 320 330 340 2 1 351 360 370...
UCSC >> YPR >> 200 (Fall, 2009)
YPR200C.t2k ALPHA 3 2 1 SA I B E A C A C XXXSXX C T T E T X 1 10 20 30 40 S E G B E B H 3 2 1 S A E G A E A S B H S H B G S H E S B H HHHHH 51 B S G H T B H S AHEII C A S H H I H TBSAHHX F G G H T HHHH I H I I I B XXXXXXXXXXXXXXXXXXXXBBX...
UCSC >> YLL >> 030 (Fall, 2009)
YLL030C.t2k STR2 3 2 1 C H H H Z Z X X X X C C H T T H H H C H C T H H X X X XXCXX X H H X X X H H C C HHH XXXXXXXX 1 10 20 30 40 H 3 2 1 H H H T H T H X X X X X 51 60 70 80 90 T 3 2 1 H A S Z H T H X T H H H H H ...
UCSC >> YFR >> 001 (Fall, 2009)
YFR001W.t2k STR2 3 2 1 CCC 1 C HHSCH H H HHHHCSTTCH T C T C C S C C C C C C S C X X X X X X X X X XHHXXHHXCXXHHHTTXTXXXTTXHCHHHXCCTHXHXXCXH X X XXCX X X X X X X XXHXXXXXCXXXXHXHHXHX C S S H H H H T H H S S C H C T T T H CSC C H HH HHH HHHHHHH...
UCSC >> YMR >> 036 (Fall, 2009)
YMR036C.t06 o_notor2 4 3 2 1 10 20 30 40 N 4 3 2 1 H N G N 51 60 70 80 90 H 4 3 2 1 M H N 101 110 120 130 140 H M H M N 4 3 2 1 G N 151 160 170 180 190 H M H 4 3 2 1 M H N 201 210 220 230 240 G N 4 3 2 1 H M H 2...
UCSC >> YBR >> 256 (Fall, 2009)
YBR256C.t2k CB_BURIAL_14_7 3 2 1 A X B BBA A C D B A C C E C C A B D CCCXXC C B DXADCDDDDDCDBXXXX D C F D D D D D E D E A C X X X X X X X X X X X X B E A B D B CEBADB B C BDCC AC X X B AAAA B BB A B E F D D F X X X X X E X X X F B...
UCSC >> YMR >> 036 (Fall, 2009)
YMR036C.t04 str2 5 4 3 2 1 1 10 20 30 40 H 5 4 3 2 1 T H S S T S T T H Y Z T 51 60 70 80 90 H 5 4 3 2 1 T S T T S H T 101 110 120 130 140 T S 5 4 3 2 1 Q S T H T S H T T 151 160 170 180 190 T 5 4 3 2 ...
UCSC >> YMR >> 036 (Fall, 2009)
YMR036C.t2k CB_burial_14_7 3 2 1 1 10 20 30 40 A 3 2 1 D A 51 60 70 80 90 D A D A 3 2 1 D A 101 110 120 130 140 D A 3 2 1 D A D A 151 160 170 180 190 B A 3 2 1 201 210 220 230 240 B 3 2 1 E B A B D E B A B E ...
UCSC >> YER >> 142 (Fall, 2009)
YER142C.t2k ALPHA 3 2 1 EEEE B A A A A XXXBBBXXXXXX XXX E E B B E E H B B C E H H H X X X H H S H HXIIIIIIIXXXXSBXXH X X X X X X X X XX X B H H I H B H HH HHH 20 H H X X X X X H H H H XXIHIII XXXX S BH C E H H 1 10 30 40 E 3 ...
What are you waiting for?