MATLAB® 7Function Reference: P - Z
How to Contact The MathWorks
www.mathworks.com Webcomp.soft-sys.matlab Newsgroupwww.mathworks.com/contact_TS.html Technical [email protected] Product enhancement [email protected] Bug [email protected] Documentation error [email protected] Order status, license renewals, [email protected] Sales, pricing, and general information
508-647-7000 (Phone)
508-647-7001 (Fax)
The MathWorks, Inc.3 Apple Hill DriveNatick, MA 01760-2098For contact information about worldwide offices, see the MathWorks Web site.MATLAB Function Reference© COPYRIGHT 1984–2009 by The MathWorks, Inc.The software described in this document is furnished under a license agreement. The software may be usedor copied only under the terms of the license agreement. No part of this manual may be photocopied orreproduced in any form without prior written consent from The MathWorks, Inc.FEDERAL ACQUISITION: This provision applies to all acquisitions of the Program and Documentationby, for, or through the federal government of the United States. By accepting delivery of the Programor Documentation, the government hereby agrees that this software or documentation qualifies ascommercial computer software or commercial computer software documentation as such terms are usedor defined in FAR 12.212, DFARS Part 227.72, and DFARS 252.227-7014. Accordingly, the terms andconditions of this Agreement and only those rights specified in this Agreement, shall pertain to and governthe use, modification, reproduction, release, performance, display, and disclosure of the Program andDocumentation by the federal government (or other entity acquiring for or through the federal government)and shall supersede any conflicting contractual terms or conditions. If this License fails to meet thegovernment’s needs or is inconsistent in any respect with federal procurement law, the government agreesto return the Program and Documentation, unused, to The MathWorks, Inc.
Trademarks
MATLAB and Simulink are registered trademarks of The MathWorks, Inc. Seewww.mathworks.com/trademarks for a list of additional trademarks. Other product or brandnames may be trademarks or registered trademarks of their respective holders.Patents
The MathWorks products are protected by one or more U.S. patents. Please seewww.mathworks.com/patents for more information.
http://www.mathworks.com/trademarkshttp://www.mathworks.com/patents
Revision HistoryDecember 1996 First printing For MATLAB 5.0 (Release 8)June 1997 Online only Revised for MATLAB 5.1 (Release 9)October 1997 Online only Revised for MATLAB 5.2 (Release 10)January 1999 Online only Revised for MATLAB 5.3 (Release 11)June 1999 Second printing For MATLAB 5.3 (Release 11)June 2001 Online only Revised for MATLAB 6.1 (Release 12.1)July 2002 Online only Revised for 6.5 (Release 13)June 2004 Online only Revised for 7.0 (Release 14)September 2006 Online only Revised for 7.3 (Release 2006b)March 2007 Online only Revised for 7.4 (Release 2007a)September 2007 Online only Revised for Version 7.5 (Release 2007b)March 2008 Online only Revised for Version 7.6 (Release 2008a)October 2008 Online only Revised for Version 7.7 (Release 2008b)March 2009 Online only Revised for Version 7.8 (Release 2009a)
Contents
Function Reference1
Desktop Tools and Development Environment . . . . . . . 1-3Startup and Shutdown . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-3Command Window and History . . . . . . . . . . . . . . . . . . . . . . 1-4Help for Using MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-5Workspace, Search Path, and File Operations . . . . . . . . . . 1-6Programming Tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-8System . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-11
Mathematics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-13Arrays and Matrices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-14Linear Algebra . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-20Elementary Math . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-24Polynomials . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-28Interpolation and Computational Geometry . . . . . . . . . . . . 1-29Cartesian Coordinate System Conversion . . . . . . . . . . . . . . 1-32Nonlinear Numerical Methods . . . . . . . . . . . . . . . . . . . . . . . 1-33Specialized Math . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-36Sparse Matrices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-37Math Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-41
Data Analysis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-43Basic Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-43Descriptive Statistics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-43Filtering and Convolution . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-44Interpolation and Regression . . . . . . . . . . . . . . . . . . . . . . . . 1-44Fourier Transforms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-45Derivatives and Integrals . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-45Time Series Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-46Time Series Collections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-49
Programming and Data Types . . . . . . . . . . . . . . . . . . . . . . 1-51Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-51Data Type Conversion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-59Operators and Special Characters . . . . . . . . . . . . . . . . . . . . 1-61Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-64
v
Bit-Wise Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-67Logical Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-67Relational Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-68Set Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-68Date and Time Operations . . . . . . . . . . . . . . . . . . . . . . . . . . 1-69Programming in MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . 1-69
Object-Oriented Programming . . . . . . . . . . . . . . . . . . . . . . 1-77Classes and Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-77Handle Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-78Events and Listeners . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-79Meta-Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-79
File I/O . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-81File Name Construction . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-81File Opening, Loading, and Saving . . . . . . . . . . . . . . . . . . . 1-82Memory Mapping . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-82Low-Level File I/O . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-82Text Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-83XML Documents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-84Spreadsheets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-84Scientific Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-85Audio and Audio/Video . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-88Images . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-90Internet Exchange . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-91
Graphics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-93Basic Plots and Graphs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-93Plotting Tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-94Annotating Plots . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-94Specialized Plotting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-95Bit-Mapped Images . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-99Printing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-99Handle Graphics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-100
3-D Visualization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-104Surface and Mesh Plots . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-104View Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-106Lighting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-108Transparency . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-108Volume Visualization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-108
vi Contents
GUI Development . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-110Predefined Dialog Boxes . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-110User Interface Deployment . . . . . . . . . . . . . . . . . . . . . . . . . . 1-111User Interface Development . . . . . . . . . . . . . . . . . . . . . . . . . 1-111User Interface Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-112Objects from Callbacks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-113GUI Utilities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-113Program Execution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-114
External Interfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-115Shared Libraries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-115Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-116.NET . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-117Component Object Model and ActiveX . . . . . . . . . . . . . . . . . 1-117Web Services . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-120Serial Port Devices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-120
Alphabetical List
2
Index
vii
viii Contents
1
Function Reference
Desktop Tools and DevelopmentEnvironment (p. 1-3)
Startup, Command Window, help,editing and debugging, tuning, othergeneral functions
Mathematics (p. 1-13) Arrays and matrices, linear algebra,other areas of mathematics
Data Analysis (p. 1-43) Basic data operations, descriptivestatistics, covariance and correlation,filtering and convolution, numericalderivatives and integrals, Fouriertransforms, time series analysis
Programming and Data Types(p. 1-51)
Function/expression evaluation,program control, function handles,object oriented programming, errorhandling, operators, data types,dates and times, timers
Object-Oriented Programming(p. 1-77)
Functions for working with classesand objects
File I/O (p. 1-81) General and low-level file I/O, plusspecific file formats, like audio,spreadsheet, HDF, images
Graphics (p. 1-93) Line plots, annotating graphs,specialized plots, images, printing,Handle Graphics
3-D Visualization (p. 1-104) Surface and mesh plots, view control,lighting and transparency, volumevisualization
1 Function Reference
GUI Development (p. 1-110) GUIDE, programming graphicaluser interfaces
External Interfaces (p. 1-115) Interfaces to shared librariess,Java, .NET, COM and ActiveX, Webservices, and serial port devices, andC and Fortran routines
1-2
Desktop Tools and Development Environment
Desktop Tools and Development Environment
Startup and Shutdown (p. 1-3) Startup and shutdown options,preferences
Command Window and History(p. 1-4)
Control Command Window andHistory, enter statements and runfunctions
Help for Using MATLAB (p. 1-5) Command line help, onlinedocumentation in the Help browser,demos
Workspace, Search Path, and FileOperations (p. 1-6)
Work with files, MATLAB searchpath, manage variables
Programming Tools (p. 1-8) Edit and debug M-files, improveperformance, source control, publishresults
System (p. 1-11) Identify current computer, license,product version, and more
Startup and Shutdown
exit Terminate MATLAB® program(same as quit)
finish Termination M-file for MATLABprogram
matlab (UNIX) Start MATLAB program (UNIX®platforms)
matlab (Windows) Start MATLAB program (Windows®platforms)
matlabrc Startup M-file for MATLAB programprefdir Directory containing preferences,
history, and layout filespreferences Open Preferences dialog boxquit Terminate MATLAB program
1-3
1 Function Reference
startup Startup M-file for user-definedoptions
userpath View or change user portion ofsearch path
Command Window and History
clc Clear Command Windowcommandhistory Open Command History window, or
select it if already opencommandwindow Open Command Window, or select
it if already opendiary Save session to filedos Execute DOS command and return
resultformat Set display format for outputhome Move cursor to upper-left corner of
Command Windowmatlabcolon (matlab:) Run specified function via hyperlinkmore Control paged output for Command
Windowperl Call Perl script using appropriate
operating system executablesystem Execute operating system command
and return resultunix Execute UNIX command and return
result
1-4
Desktop Tools and Development Environment
Help for Using MATLAB
builddocsearchdb Build searchable documentationdatabase
demo Access product demos via Helpbrowser
doc Reference page in Help browserdocsearch Open Help browser and search for
specified termechodemo Run M-file demo step-by-step in
Command Windowhelp Help for functions in Command
Windowhelpbrowser Open Help browser to access all
online documentation and demoshelpwin Provide access to M-file help for all
functionsinfo Information about contacting The
MathWorkslookfor Search for keyword in all help
entriesplayshow Run M-file demo (deprecated; use
echodemo instead)support Open MathWorks Technical Support
Web pagewhatsnew Release Notes for MathWorks™
products
1-5
1 Function Reference
Workspace, Search Path, and File Operations
Workspace (p. 1-6) Manage variablesSearch Path (p. 1-6) View and change MATLAB search
pathFile Operations (p. 1-7) View and change files and directories
Workspace
assignin Assign value to variable in specifiedworkspace
clear Remove items from workspace,freeing up system memory
evalin Execute MATLAB expression inspecified workspace
exist Check existence of variable, function,directory, or Java™ programminglanguage class
openvar Open workspace variable in VariableEditor or other graphical editing tool
pack Consolidate workspace memoryuiimport Open Import Wizard to import datawhich Locate functions and fileswho, whos List variables in workspaceworkspace Open Workspace browser to manage
workspace
Search Path
addpath Add directories to search pathgenpath Generate path string
1-6
Desktop Tools and Development Environment
partialpath Partial pathname descriptionpath View or change search pathpath2rc Save current search path to
pathdef.m filepathsep Path separator for current platformpathtool Open Set Path dialog box to view
and change search pathrestoredefaultpath Restore default search pathrmpath Remove directories from search pathsavepath Save current search pathuserpath View or change user portion of
search path
File OperationsSee also “File I/O” on page 1-81 functions.
cd Change working directorycopyfile Copy file or directorydelete Remove files or graphics objectsdir Directory listingexist Check existence of variable, function,
directory, or Java programminglanguage class
fileattrib Set or get attributes of file ordirectory
filebrowser Open Current Directory browser, orselect it if already open
isdir Determine whether input is directorylookfor Search for keyword in all help
entries
1-7
1 Function Reference
ls Directory contentsmatlabroot Root directorymkdir Make new directorymovefile Move file or directorypwd Identify current directoryrecycle Set option to move deleted files to
recycle folderrehash Refresh function and file system
path cachesrmdir Remove directorytoolboxdir Root directory for specified toolboxtype Display contents of filevisdiff Compare two text files, MAT-Files,
or binary fileswhat List MATLAB files in current
directorywhich Locate functions and files
Programming Tools
M-File Editing and Debugging(p. 1-9)
Edit and debug M-files
M-File Performance (p. 1-9) Improve performance and findpotential problems in M-files
Source Control (p. 1-10) Interface MATLAB with sourcecontrol system
Publishing (p. 1-10) Publish M-file code and results
1-8
Desktop Tools and Development Environment
M-File Editing and Debugging
clipboard Copy and paste strings to and fromsystem clipboard
datatipinfo Produce short description of inputvariable
dbclear Clear breakpointsdbcont Resume executiondbdown Reverse workspace shift performed
by dbup, while in debug modedbquit Quit debug modedbstack Function call stackdbstatus List all breakpointsdbstep Execute one or more lines from
current breakpointdbstop Set breakpointsdbtype List M-file with line numbersdbup Shift current workspace to
workspace of caller, while indebug mode
debug List M-file debugging functionsedit Edit or create M-filekeyboard Input from keyboard
M-File Performance
bench MATLAB benchmarkmlint Check M-files for possible problemsmlintrpt Run mlint for file or directory,
reporting results in browserpack Consolidate workspace memory
1-9
1 Function Reference
profile Profile execution time for functionprofsave Save profile report in HTML formatrehash Refresh function and file system
path cachessparse Create sparse matrixzeros Create array of all zeros
Source Control
checkin Check files into source controlsystem (UNIX platforms)
checkout Check files out of source controlsystem (UNIX platforms)
cmopts Name of source control systemcustomverctrl Allow custom source control system
(UNIX platforms)undocheckout Undo previous checkout from source
control system (UNIX platforms)verctrl Source control actions (Windows
platforms)
Publishing
grabcode MATLAB code from M-filespublished to HTML
notebook Open M-book in Microsoft® Wordsoftware (on Microsoft Windowsplatforms)
publish Publish M-file containing cells,saving output to file of specified type
snapnow Force snapshot of image for inclusionin published document
1-10
Desktop Tools and Development Environment
System
Operating System Interface (p. 1-11) Exchange operating systeminformation and commands withMATLAB
MATLAB Version and License(p. 1-12)
Information about MATLAB versionand license
Operating System Interface
clipboard Copy and paste strings to and fromsystem clipboard
computer Information about computer onwhich MATLAB software is running
dos Execute DOS command and returnresult
getenv Environment variablehostid Server host identification numbermaxNumCompThreads Control maximum number of
computational threadsperl Call Perl script using appropriate
operating system executablesetenv Set environment variablesystem Execute operating system command
and return resultunix Execute UNIX command and return
resultwinqueryreg Item from Windows registry
1-11
1 Function Reference
MATLAB Version and License
ismac Determine if version is for Mac OS®X platform
ispc Determine if version is for Windows(PC) platform
isstudent Determine if version is StudentVersion
isunix Determine if version is for UNIXplatform
javachk Generate error message based onSun™ Java feature support
license Return license number or performlicensing task
prefdir Directory containing preferences,history, and layout files
usejava Determine whether Sun Java featureis supported in MATLAB software
ver Version information for MathWorksproducts
verLessThan Compare toolbox version to specifiedversion string
version Version number for MATLAB
1-12
Mathematics
Mathematics
Arrays and Matrices (p. 1-14) Basic array operators andoperations, creation of elementaryand specialized arrays and matrices
Linear Algebra (p. 1-20) Matrix analysis, linear equations,eigenvalues, singular values,logarithms, exponentials,factorization
Elementary Math (p. 1-24) Trigonometry, exponentials andlogarithms, complex values,rounding, remainders, discrete math
Polynomials (p. 1-28) Multiplication, division, evaluation,roots, derivatives, integration,eigenvalue problem, curve fitting,partial fraction expansion
Interpolation and ComputationalGeometry (p. 1-29)
Interpolation, Delaunaytriangulation and tessellation,convex hulls, Voronoi diagrams,domain generation
Cartesian Coordinate SystemConversion (p. 1-32)
Conversions between Cartesian andpolar or spherical coordinates
Nonlinear Numerical Methods(p. 1-33)
Differential equations, optimization,integration
Specialized Math (p. 1-36) Airy, Bessel, Jacobi, Legendre, beta,elliptic, error, exponential integral,gamma functions
Sparse Matrices (p. 1-37) Elementary sparse matrices,operations, reordering algorithms,linear algebra, iterative methods,tree operations
Math Constants (p. 1-41) Pi, imaginary unit, infinity,Not-a-Number, largest and smallestpositive floating point numbers,floating point relative accuracy
1-13
1 Function Reference
Arrays and Matrices
Basic Information (p. 1-14) Display array contents, get arrayinformation, determine array type
Operators (p. 1-15) Arithmetic operatorsElementary Matrices and Arrays(p. 1-16)
Create elementary arrays of differenttypes, generate arrays for plotting,array indexing, etc.
Array Operations (p. 1-17) Operate on array content, applyfunction to each array element, findcumulative product or sum, etc.
Array Manipulation (p. 1-18) Create, sort, rotate, permute,reshape, and shift array contents
Specialized Matrices (p. 1-19) Create Hadamard, Companion,Hankel, Vandermonde, Pascalmatrices, etc.
Basic Information
disp Display text or arraydisplay Display text or array (overloaded
method)isempty Determine whether array is emptyisequal Test arrays for equalityisequalwithequalnans Test arrays for equality, treating
NaNs as equalisfinite Array elements that are finiteisfloat Determine whether input is
floating-point arrayisinf Array elements that are infiniteisinteger Determine whether input is integer
array
1-14
Mathematics
islogical Determine whether input is logicalarray
isnan Array elements that are NaNisnumeric Determine whether input is numeric
arrayisscalar Determine whether input is scalarissparse Determine whether input is sparseisvector Determine whether input is vectorlength Length of vectormax Largest elements in arraymin Smallest elements in arrayndims Number of array dimensionsnumel Number of elements in array or
subscripted array expressionsize Array dimensions
Operators
+ Addition+ Unary plus- Subtraction- Unary minus* Matrix multiplication^ Matrix power\ Backslash or left matrix divide/ Slash or right matrix divide’ Transpose.’ Nonconjugated transpose.* Array multiplication (element-wise)
1-15
1 Function Reference
.^ Array power (element-wise)
.\ Left array divide (element-wise)
./ Right array divide (element-wise)
Elementary Matrices and Arrays
blkdiag Construct block diagonal matrixfrom input arguments
create (RandStream) Create random number streamsdiag Diagonal matrices and diagonals of
matrixeye Identity matrixfreqspace Frequency spacing for frequency
responseget (RandStream) Random stream propertiesgetDefaultStream (RandStream) Default random number streamind2sub Subscripts from linear indexlinspace Generate linearly spaced vectorslist (RandStream) Random number generator
algorithmslogspace Generate logarithmically spaced
vectorsmeshgrid Generate X and Y arrays for 3-D plotsndgrid Generate arrays for N-D functions
and interpolationones Create array of all onesrand Uniformly distributed
pseudorandom numbersrand (RandStream) Uniformly distributed random
numbers
1-16
Mathematics
randi Uniformly distributedpseudorandom integers
randi (RandStream) Uniformly distributedpseudorandom integers
randn Normally distributed pseudorandomnumbers
randn (RandStream) Normally distributed pseudorandomnumbers
randperm (RandStream)RandStream Random number streamRandStream (RandStream) Random number streamset (RandStream) Set random stream propertysetDefaultStream (RandStream) Set default random number streamsub2ind Single index from subscriptszeros Create array of all zeros
Array Operations
See “Linear Algebra” on page 1-20 and “Elementary Math” on page 1-24 forother array operations.
accumarray Construct array with accumulationarrayfun Apply function to each element of
arraybsxfun Apply element-by-element binary
operation to two arrays withsingleton expansion enabled
cast Cast variable to different data typecross Vector cross productcumprod Cumulative productcumsum Cumulative sum
1-17
1 Function Reference
dot Vector dot productidivide Integer division with rounding
optionkron Kronecker tensor productprod Product of array elementssum Sum of array elementstril Lower triangular part of matrixtriu Upper triangular part of matrix
Array Manipulation
blkdiag Construct block diagonal matrixfrom input arguments
cat Concatenate arrays along specifieddimension
circshift Shift array circularlydiag Diagonal matrices and diagonals of
matrixend Terminate block of code, or indicate
last array indexflipdim Flip array along specified dimensionfliplr Flip matrix left to rightflipud Flip matrix up to downhorzcat Concatenate arrays horizontallyinline Construct inline objectipermute Inverse permute dimensions of N-D
arraypermute Rearrange dimensions of N-D arrayrepmat Replicate and tile arrayreshape Reshape array
1-18
Mathematics
rot90 Rotate matrix 90 degreesshiftdim Shift dimensionssort Sort array elements in ascending or
descending ordersortrows Sort rows in ascending ordersqueeze Remove singleton dimensionsvectorize Vectorize expressionvertcat Concatenate arrays vertically
Specialized Matrices
compan Companion matrixgallery Test matriceshadamard Hadamard matrixhankel Hankel matrixhilb Hilbert matrixinvhilb Inverse of Hilbert matrixmagic Magic squarepascal Pascal matrixrosser Classic symmetric eigenvalue test
problemtoeplitz Toeplitz matrixvander Vandermonde matrixwilkinson Wilkinson’s eigenvalue test matrix
1-19
1 Function Reference
Linear Algebra
Matrix Analysis (p. 1-20) Compute norm, rank, determinant,condition number, etc.
Linear Equations (p. 1-21) Solve linear systems, leastsquares, LU factorization, Choleskyfactorization, etc.
Eigenvalues and Singular Values(p. 1-22)
Eigenvalues, eigenvectors, Schurdecomposition, Hessenburgmatrices, etc.
Matrix Logarithms and Exponentials(p. 1-23)
Matrix logarithms, exponentials,square root
Factorization (p. 1-23) Cholesky, LU, and QR factorizations,diagonal forms, singular valuedecomposition
Matrix Analysis
cond Condition number with respect toinversion
condeig Condition number with respect toeigenvalues
det Matrix determinantnorm Vector and matrix normsnormest 2-norm estimatenull Null spaceorth Range space of matrixrank Rank of matrixrcond Matrix reciprocal condition number
estimaterref Reduced row echelon form
1-20
Mathematics
subspace Angle between two subspacestrace Sum of diagonal elements
Linear Equations
chol Cholesky factorizationcholinc Sparse incomplete Cholesky and
Cholesky-Infinity factorizationscond Condition number with respect to
inversioncondest 1-norm condition number estimatefunm Evaluate general matrix functionilu Sparse incomplete LU factorizationinv Matrix inverselinsolve Solve linear system of equationslscov Least-squares solution in presence
of known covariancelsqnonneg Solve nonnegative least-squares
constraints problemlu LU matrix factorizationluinc Sparse incomplete LU factorizationpinv Moore-Penrose pseudoinverse of
matrixqr Orthogonal-triangular
decompositionrcond Matrix reciprocal condition number
estimate
1-21
1 Function Reference
Eigenvalues and Singular Values
balance Diagonal scaling to improveeigenvalue accuracy
cdf2rdf Convert complex diagonal form toreal block diagonal form
condeig Condition number with respect toeigenvalues
eig Eigenvalues and eigenvectorseigs Largest eigenvalues and
eigenvectors of matrixgsvd Generalized singular value
decompositionhess Hessenberg form of matrixordeig Eigenvalues of quasitriangular
matricesordqz Reorder eigenvalues in QZ
factorizationordschur Reorder eigenvalues in Schur
factorizationpoly Polynomial with specified rootspolyeig Polynomial eigenvalue problemrsf2csf Convert real Schur form to complex
Schur formschur Schur decompositionsqrtm Matrix square rootss2tf Convert state-space filter parameters
to transfer function formsvd Singular value decompositionsvds Find singular values and vectors
1-22
Mathematics
Matrix Logarithms and Exponentials
expm Matrix exponentiallogm Matrix logarithmsqrtm Matrix square root
Factorization
balance Diagonal scaling to improveeigenvalue accuracy
cdf2rdf Convert complex diagonal form toreal block diagonal form
chol Cholesky factorizationcholinc Sparse incomplete Cholesky and
Cholesky-Infinity factorizationscholupdate Rank 1 update to Cholesky
factorizationgsvd Generalized singular value
decompositionilu Sparse incomplete LU factorizationlu LU matrix factorizationluinc Sparse incomplete LU factorizationplanerot Givens plane rotationqr Orthogonal-triangular
decompositionqrdelete Remove column or row from QR
factorizationqrinsert Insert column or row into QR
factorizationqrupdate
1-23
1 Function Reference
qz QZ factorization for generalizedeigenvalues
rsf2csf Convert real Schur form to complexSchur form
svd Singular value decomposition
Elementary Math
Trigonometric (p. 1-24) Trigonometric functions with resultsin radians or degrees
Exponential (p. 1-26) Exponential, logarithm, power, androot functions
Complex (p. 1-26) Numbers with real and imaginarycomponents, phase angles
Rounding and Remainder (p. 1-27) Rounding, modulus, and remainderDiscrete Math (p. 1-27) Prime factors, factorials,
permutations, rational fractions,least common multiple, greatestcommon divisor
Trigonometric
acos Inverse cosine; result in radiansacosd Inverse cosine; result in degreesacosh Inverse hyperbolic cosineacot Inverse cotangent; result in radiansacotd Inverse cotangent; result in degreesacoth Inverse hyperbolic cotangentacsc Inverse cosecant; result in radiansacscd Inverse cosecant; result in degreesacsch Inverse hyperbolic cosecant
1-24
Mathematics
asec Inverse secant; result in radiansasecd Inverse secant; result in degreesasech Inverse hyperbolic secantasin Inverse sine; result in radiansasind Inverse sine; result in degreesasinh Inverse hyperbolic sineatan Inverse tangent; result in radiansatan2 Four-quadrant inverse tangentatand Inverse tangent; result in degreesatanh Inverse hyperbolic tangentcos Cosine of argument in radianscosd Cosine of argument in degreescosh Hyperbolic cosinecot Cotangent of argument in radianscotd Cotangent of argument in degreescoth Hyperbolic cotangentcsc Cosecant of argument in radianscscd Cosecant of argument in degreescsch Hyperbolic cosecanthypot Square root of sum of squaressec Secant of argument in radianssecd Secant of argument in degreessech Hyperbolic secantsin Sine of argument in radianssind Sine of argument in degreessinh Hyperbolic sine of argument in
radianstan Tangent of argument in radians
1-25
1 Function Reference
tand Tangent of argument in degreestanh Hyperbolic tangent
Exponential
exp Exponentialexpm1 Compute exp(x)-1 accurately for
small values of xlog Natural logarithmlog10 Common (base 10) logarithmlog1p Compute log(1+x) accurately for
small values of xlog2 Base 2 logarithm and dissect
floating-point numbers intoexponent and mantissa
nextpow2 Next higher power of 2nthroot Real nth root of real numberspow2 Base 2 power and scale floating-point
numbersreallog Natural logarithm for nonnegative
real arraysrealpow Array power for real-only outputrealsqrt Square root for nonnegative real
arrayssqrt Square root
Complex
abs Absolute value and complexmagnitude
angle Phase angle
1-26
Mathematics
complex Construct complex data from realand imaginary components
conj Complex conjugatecplxpair Sort complex numbers into complex
conjugate pairsi Imaginary unitimag Imaginary part of complex numberisreal Check if input is real arrayj Imaginary unitreal Real part of complex numbersign Signum functionunwrap Correct phase angles to produce
smoother phase plots
Rounding and Remainder
ceil Round toward positive infinityfix Round toward zerofloor Round toward negative infinityidivide Integer division with rounding
optionmod Modulus after divisionrem Remainder after divisionround Round to nearest integer
Discrete Math
factor Prime factorsfactorial Factorial functiongcd Greatest common divisor
1-27
1 Function Reference
isprime Array elements that are primenumbers
lcm Least common multiplenchoosek Binomial coefficient or all
combinationsperms All possible permutationsprimes Generate list of prime numbersrat, rats Rational fraction approximation
Polynomials
conv Convolution and polynomialmultiplication
deconv Deconvolution and polynomialdivision
poly Polynomial with specified rootspolyder Polynomial derivativepolyeig Polynomial eigenvalue problempolyfit Polynomial curve fittingpolyint Integrate polynomial analyticallypolyval Polynomial evaluationpolyvalm Matrix polynomial evaluationresidue Convert between partial fraction
expansion and polynomialcoefficients
roots Polynomial roots
1-28
Mathematics
Interpolation and Computational Geometry
Interpolation (p. 1-29) Data interpolation, data gridding,polynomial evaluation, nearest pointsearch
Delaunay Triangulation andTessellation (p. 1-30)
Delaunay triangulation andtessellation, triangular surface andmesh plots
Convex Hull (p. 1-32) Plot convex hull, plotting functionsVoronoi Diagrams (p. 1-32) Plot Voronoi diagram, patch graphics
object, plotting functionsDomain Generation (p. 1-32) Generate arrays for 3-D plots, or for
N-D functions and interpolation
Interpolation
dsearch Search Delaunay triangulation fornearest point
dsearchn N-D nearest point searchgriddata Data griddinggriddata3 Data gridding and hypersurface
fitting for 3-D datagriddatan Data gridding and hypersurface
fitting (dimension >= 2)interp1 1-D data interpolation (table lookup)interp1q Quick 1-D linear interpolationinterp2 2-D data interpolation (table lookup)interp3 3-D data interpolation (table lookup)interpft 1-D interpolation using FFT methodinterpn N-D data interpolation (table lookup)meshgrid Generate X and Y arrays for 3-D plots
1-29
1 Function Reference
mkpp Make piecewise polynomialndgrid Generate arrays for N-D functions
and interpolationpadecoef Padé approximation of time delayspchip Piecewise Cubic Hermite
Interpolating Polynomial (PCHIP)ppval Evaluate piecewise polynomialspline Cubic spline data interpolationtsearchn N-D closest simplex searchunmkpp Piecewise polynomial details
Delaunay Triangulation and Tessellation
baryToCart (TriRep) Converts point coordinates frombarycentric to Cartesian
cartToBary (TriRep) Convert point coordinates fromcartesian to barycentric
circumcenters (TriRep) Circumcenters of specified simplicesconvexHull (DelaunayTri) Convex hulldelaunay Delaunay triangulationdelaunay3 3-D Delaunay tessellationdelaunayn N-D Delaunay tessellationDelaunayTri Contruct Delaunay triangulationDelaunayTri Delaunay triangulation in 2-D and
3-Ddsearch Search Delaunay triangulation for
nearest pointdsearchn N-D nearest point searchedgeAttachments (TriRep) Simplices attached to specified edgesedges (TriRep) Triangulation edges
1-30
Mathematics
faceNormals (TriRep) Unit normals to specified trianglesfeatureEdges (TriRep) Sharp edges of surface triangulationfreeBoundary (TriRep) Facets referenced by only one
simplexincenters (TriRep) Incenters of specified simplicesinOutStatus (DelaunayTri) Status of triangles in 2-D constrained
Delaunay triangulationisEdge (TriRep) Test if vertices are joined by edgenearestNeighbor (DelaunayTri) Point closest to specified locationneighbors (TriRep) Simplex neighbor informationpointLocation (DelaunayTri) Simplex containing specified locationsize (TriRep) Size of triangulation matrixtetramesh Tetrahedron mesh plottrimesh Triangular mesh plottriplot 2-D triangular plotTriRep Triangulation representationTriRep Triangulation representationTriScatteredInterp Interpolate scattered dataTriScatteredInterptrisurf Triangular surface plottsearch Search for enclosing Delaunay
triangletsearchn N-D closest simplex searchvertexAttachments (TriRep) Return simplices attached to
specified verticesvoronoiDiagram (DelaunayTri) Voronoi diagram
1-31
1 Function Reference
Convex Hull
convhull Convex hullconvhulln N-D convex hullpatch Create patch graphics objectplot 2-D line plottrisurf Triangular surface plot
Voronoi Diagrams
dsearch Search Delaunay triangulation fornearest point
patch Create patch graphics objectplot 2-D line plotvoronoi Voronoi diagramvoronoin N-D Voronoi diagram
Domain Generation
meshgrid Generate X and Y arrays for 3-D plotsndgrid Generate arrays for N-D functions
and interpolation
Cartesian Coordinate System Conversion
cart2pol Transform Cartesian coordinates topolar or cylindrical
cart2sph Transform Cartesian coordinates tospherical
1-32
Mathematics
pol2cart Transform polar or cylindricalcoordinates to Cartesian
sph2cart Transform spherical coordinates toCartesian
Nonlinear Numerical Methods
Ordinary Differential Equations(p. 1-33)
Solve stiff and nonstiff differentialequations, define the problem, setsolver options, evaluate solution
Delay Differential Equations(p. 1-34)
Solve delay differential equationswith constant and general delays,set solver options, evaluate solution
Boundary Value Problems (p. 1-35) Solve boundary value problems forordinary differential equations, setsolver options, evaluate solution
Partial Differential Equations(p. 1-35)
Solve initial-boundary valueproblems for parabolic-elliptic PDEs,evaluate solution
Optimization (p. 1-35) Find minimum of single andmultivariable functions, solvenonnegative least-squares constraintproblem
Numerical Integration (Quadrature)(p. 1-36)
Evaluate Simpson, Lobatto, andvectorized quadratures, evaluatedouble and triple integrals
Ordinary Differential Equations
decic Compute consistent initial conditionsfor ode15i
deval Evaluate solution of differentialequation problem
1-33
1 Function Reference
ode15i Solve fully implicit differentialequations, variable order method
ode23, ode45, ode113, ode15s,ode23s, ode23t, ode23tb
Solve initial value problems forordinary differential equations
odefile Define differential equation problemfor ordinary differential equationsolvers
odeget Ordinary differential equationoptions parameters
odeset Create or alter options structurefor ordinary differential equationsolvers
odextend Extend solution of initial valueproblem for ordinary differentialequation
Delay Differential Equations
dde23 Solve delay differential equations(DDEs) with constant delays
ddeget Extract properties from delaydifferential equations optionsstructure
ddesd Solve delay differential equations(DDEs) with general delays
ddeset Create or alter delay differentialequations options structure
deval Evaluate solution of differentialequation problem
1-34
Mathematics
Boundary Value Problems
bvp4c Solve boundary value problems forordinary differential equations
bvp5c Solve boundary value problems forordinary differential equations
bvpget Extract properties from optionsstructure created with bvpset
bvpinit Form initial guess for bvp4cbvpset Create or alter options structure of
boundary value problembvpxtend Form guess structure for extending
boundary value solutionsdeval Evaluate solution of differential
equation problem
Partial Differential Equations
pdepe Solve initial-boundary valueproblems for parabolic-elliptic PDEsin 1-D
pdeval Evaluate numerical solution of PDEusing output of pdepe
Optimization
fminbnd Find minimum of single-variablefunction on fixed interval
fminsearch Find minimum of unconstrainedmultivariable function usingderivative-free method
fzero Find root of continuous function ofone variable
1-35
1 Function Reference
lsqnonneg Solve nonnegative least-squaresconstraints problem
optimget Optimization options valuesoptimset Create or edit optimization options
structure
Numerical Integration (Quadrature)
dblquad Numerically evaluate doubleintegral over a rectangle
quad Numerically evaluate integral,adaptive Simpson quadrature
quad2d Numerically evaluate doubleintegral over planar region
quadgk Numerically evaluate integral,adaptive Gauss-Kronrod quadrature
quadl Numerically evaluate integral,adaptive Lobatto quadrature
quadv Vectorized quadraturetriplequad Numerically evaluate triple integral
Specialized Math
airy Airy functionsbesselh Bessel function of third kind (Hankel
function)besseli Modified Bessel function of first kindbesselj Bessel function of first kindbesselk Modified Bessel function of second
kindbessely Bessel function of second kind
1-36
Mathematics
beta Beta functionbetainc Incomplete beta functionbetaincinv Beta inverse cumulative distribution
functionbetaln Logarithm of beta functionellipj Jacobi elliptic functionsellipke Complete elliptic integrals of first
and second kinderf, erfc, erfcx, erfinv, erfcinv Error functionsexpint Exponential integralgamma, gammainc, gammaln Gamma functionsgammaincinv Inverse incomplete gamma functionlegendre Associated Legendre functionspsi Psi (polygamma) function
Sparse Matrices
Elementary Sparse Matrices(p. 1-38)
Create random and nonrandomsparse matrices
Full to Sparse Conversion (p. 1-38) Convert full matrix to sparse, sparsematrix to full
Sparse Matrix Manipulation (p. 1-39) Test matrix for sparseness, getinformation on sparse matrix,allocate sparse matrix, applyfunction to nonzero elements,visualize sparsity pattern
Reordering Algorithms (p. 1-39) Random, column, minimum degree,Dulmage-Mendelsohn, and reverseCuthill-McKee permutations
1-37
1 Function Reference
Linear Algebra (p. 1-40) Compute norms, eigenvalues,factorizations, least squares,structural rank
Linear Equations (IterativeMethods) (p. 1-40)
Methods for conjugate andbiconjugate gradients, residuals,lower quartile
Tree Operations (p. 1-41) Elimination trees, tree plotting,factorization analysis
Elementary Sparse Matrices
spdiags Extract and create sparse band anddiagonal matrices
speye Sparse identity matrixsprand Sparse uniformly distributed
random matrixsprandn Sparse normally distributed random
matrixsprandsym Sparse symmetric random matrix
Full to Sparse Conversion
find Find indices and values of nonzeroelements
full Convert sparse matrix to full matrixsparse Create sparse matrixspconvert Import matrix from sparse matrix
external format
1-38
Mathematics
Sparse Matrix Manipulation
issparse Determine whether input is sparsennz Number of nonzero matrix elementsnonzeros Nonzero matrix elementsnzmax Amount of storage allocated for
nonzero matrix elementsspalloc Allocate space for sparse matrixspfun Apply function to nonzero sparse
matrix elementsspones Replace nonzero sparse matrix
elements with onesspparms Set parameters for sparse matrix
routinesspy Visualize sparsity pattern
Reordering Algorithms
amd Approximate minimum degreepermutation
colamd Column approximate minimumdegree permutation
colperm Sparse column permutation basedon nonzero count
dmperm Dulmage-Mendelsohn decompositionldl Block LDL’ factorization for
Hermitian indefinite matricesrandperm Random permutationsymamd Symmetric approximate minimum
degree permutationsymrcm Sparse reverse Cuthill-McKee
ordering
1-39
1 Function Reference
Linear Algebra
cholinc Sparse incomplete Cholesky andCholesky-Infinity factorizations
condest 1-norm condition number estimateeigs Largest eigenvalues and
eigenvectors of matrixilu Sparse incomplete LU factorizationluinc Sparse incomplete LU factorizationnormest 2-norm estimatespaugment Form least squares augmented
systemsprank Structural ranksvds Find singular values and vectors
Linear Equations (Iterative Methods)
bicg Biconjugate gradients methodbicgstab Biconjugate gradients stabilized
methodbicgstabl Biconjugate gradients stabilized (l)
methodcgs Conjugate gradients squared methodgmres Generalized minimum residual
method (with restarts)lsqr LSQR methodminres Minimum residual methodpcg Preconditioned conjugate gradients
methodqmr Quasi-minimal residual method
1-40
Mathematics
symmlq Symmetric LQ methodtfqmr Transpose-free quasi-minimal
residual method
Tree Operations
etree Elimination treeetreeplot Plot elimination treegplot Plot nodes and links representing
adjacency matrixsymbfact Symbolic factorization analysistreelayout Lay out tree or foresttreeplot Plot picture of treeunmesh Convert edge matrix to coordinate
and Laplacian matrices
Math Constants
eps Floating-point relative accuracyi Imaginary unitInf Infinityintmax Largest value of specified integer
typeintmin Smallest value of specified integer
typej Imaginary unitNaN Not-a-Numberpi Ratio of circle’s circumference to its
diameter, π
1-41
1 Function Reference
realmax Largest positive floating-pointnumber
realmin Smallest positive normalizedfloating-point number
1-42
Data Analysis
Data Analysis
Basic Operations (p. 1-43) Sums, products, sortingDescriptive Statistics (p. 1-43) Statistical summaries of dataFiltering and Convolution (p. 1-44) Data preprocessingInterpolation and Regression(p. 1-44)
Data fitting
Fourier Transforms (p. 1-45) Frequency content of dataDerivatives and Integrals (p. 1-45) Data rates and accumulationsTime Series Objects (p. 1-46) Methods for timeseries objectsTime Series Collections (p. 1-49) Methods for tscollection objects
Basic Operations
brush Interactively mark, delete, modify,and save observations in graphs
cumprod Cumulative productcumsum Cumulative sumlinkdata Automatically update graphs when
variables changeprod Product of array elementssort Sort array elements in ascending or
descending ordersortrows Sort rows in ascending ordersum Sum of array elements
Descriptive Statistics
corrcoef Correlation coefficientscov Covariance matrix
1-43
1 Function Reference
max Largest elements in arraymean Average or mean value of arraymedian Median value of arraymin Smallest elements in arraymode Most frequent values in arraystd Standard deviationvar Variance
Filtering and Convolution
conv Convolution and polynomialmultiplication
conv2 2-D convolutionconvn N-D convolutiondeconv Deconvolution and polynomial
divisiondetrend Remove linear trendsfilter 1-D digital filterfilter2 2-D digital filter
Interpolation and Regression
interp1 1-D data interpolation (table lookup)interp2 2-D data interpolation (table lookup)interp3 3-D data interpolation (table lookup)interpn N-D data interpolation (table lookup)mldivide \, mrdivide / Left or right matrix divisionpolyfit Polynomial curve fittingpolyval Polynomial evaluation
1-44
Data Analysis
Fourier Transforms
abs Absolute value and complexmagnitude
angle Phase anglecplxpair Sort complex numbers into complex
conjugate pairsfft Discrete Fourier transformfft2 2-D discrete Fourier transformfftn N-D discrete Fourier transformfftshift Shift zero-frequency component to
center of spectrumfftw Interface to FFTW library run-time
algorithm tuning controlifft Inverse discrete Fourier transformifft2 2-D inverse discrete Fourier
transformifftn N-D inverse discrete Fourier
transformifftshift Inverse FFT shiftnextpow2 Next higher power of 2unwrap Correct phase angles to produce
smoother phase plots
Derivatives and Integrals
cumtrapz Cumulative trapezoidal numericalintegration
del2 Discrete Laplaciandiff Differences and approximate
derivatives
1-45
1 Function Reference
gradient Numerical gradientpolyder Polynomial derivativepolyint Integrate polynomial analyticallytrapz Trapezoidal numerical integration
Time Series Objects
Utilities (p. 1-46) Combine timeseries objects,query and set timeseries objectproperties, plot timeseries objects
Data Manipulation (p. 1-47) Add or delete data, manipulatetimeseries objects
Event Data (p. 1-48) Add or delete events, create newtimeseries objects based on eventdata
Descriptive Statistics (p. 1-48) Descriptive statistics for timeseriesobjects
Utilities
get (timeseries) Query timeseries object propertyvalues
getdatasamplesize Size of data sample in timeseriesobject
getqualitydesc Data quality descriptionsisempty (timeseries) Determine whether timeseries
object is emptylength (timeseries) Length of time vectorplot (timeseries) Plot time seriesset (timeseries) Set properties of timeseries objectsize (timeseries) Size of timeseries object
1-46
Data Analysis
timeseries Create timeseries objecttsdata.event Construct event object for
timeseries objecttsprops Help on timeseries object
propertieststool Open Time Series Tools GUI
Data Manipulation
addsample Add data sample to timeseriesobject
ctranspose (timeseries) Transpose timeseries objectdelsample Remove sample from timeseries
objectdetrend (timeseries) Subtract mean or best-fit line and all
NaNs from time seriesfilter (timeseries) Shape frequency content of time
seriesgetabstime (timeseries) Extract date-string time vector into
cell arraygetinterpmethod Interpolation method for timeseries
objectgetsampleusingtime (timeseries) Extract data samples into new
timeseries objectidealfilter (timeseries) Apply ideal (noncausal) filter to
timeseries objectresample (timeseries) Select or interpolate timeseries
data using new time vectorsetabstime (timeseries) Set times of timeseries object as
date stringssetinterpmethod Set default interpolation method for
timeseries object
1-47
1 Function Reference
synchronize Synchronize and resample twotimeseries objects using commontime vector
transpose (timeseries) Transpose timeseries objectvertcat (timeseries) Vertical concatenation of
timeseries objects
Event Data
addevent Add event to timeseries objectdelevent Remove tsdata.event objects from
timeseries objectgettsafteratevent New timeseries object with samples
occurring at or after eventgettsafterevent New timeseries object with samples
occurring after eventgettsatevent New timeseries object with samples
occurring at eventgettsbeforeatevent New timeseries object with samples
occurring before or at eventgettsbeforeevent New timeseries object with samples
occurring before eventgettsbetweenevents New timeseries object with samples
occurring between events
Descriptive Statistics
iqr (timeseries) Interquartile range of timeseriesdata
max (timeseries) Maximum value of timeseries datamean (timeseries) Mean value of timeseries datamedian (timeseries) Median value of timeseries data
1-48
Data Analysis
min (timeseries) Minimum value of timeseries datastd (timeseries) Standard deviation of timeseries
datasum (timeseries) Sum of timeseries datavar (timeseries) Variance of timeseries data
Time Series Collections
Utilities (p. 1-49) Query and set tscollection objectproperties, plot tscollectionobjects
Data Manipulation (p. 1-50) Add or delete data, manipulatetscollection objects
Utilities
get (tscollection) Query tscollection object propertyvalues
isempty (tscollection) Determine whether tscollectionobject is empty
length (tscollection) Length of time vectorplot (timeseries) Plot time seriesset (tscollection) Set properties of tscollection
objectsize (tscollection) Size of tscollection objecttscollection Create tscollection objecttstool Open Time Series Tools GUI
1-49
1 Function Reference
Data Manipulation
addsampletocollection Add sample to tscollection objectaddts Add timeseries object to
tscollection objectdelsamplefromcollection Remove sample from tscollection
objectgetabstime (tscollection) Extract date-string time vector into
cell arraygetsampleusingtime (tscollection) Extract data samples into new
tscollection objectgettimeseriesnames Cell array of names of timeseries
objects in tscollection objecthorzcat (tscollection) Horizontal concatenation for
tscollection objectsremovets Remove timeseries objects from
tscollection objectresample (tscollection) Select or interpolate data in
tscollection using new time vectorsetabstime (tscollection) Set times of tscollection object as
date stringssettimeseriesnames Change name of timeseries object
in tscollectionvertcat (tscollection) Vertical concatenation for
tscollection objects
1-50
Programming and Data Types
Programming and Data Types
Data Types (p. 1-51) Numeric, character, structures, cellarrays, and data type conversion
Data Type Conversion (p. 1-59) Convert one numeric type to another,numeric to string, string to numeric,structure to cell array, etc.
Operators and Special Characters(p. 1-61)
Arithmetic, relational, and logicaloperators, and special characters
Strings (p. 1-64) Create, identify, manipulate, parse,evaluate, and compare strings
Bit-Wise Operations (p. 1-67) Perform set, shift, and, or, compare,etc. on specific bit fields
Logical Operations (p. 1-67) Evaluate conditions, testing for trueor false
Relational Operations (p. 1-68) Compare values for equality, greaterthan, less than, etc.
Set Operations (p. 1-68) Find set members, unions,intersections, etc.
Date and Time Operations (p. 1-69) Obtain information about dates andtimes
Programming in MATLAB (p. 1-69) M-files, function/expressionevaluation, program control,function handles, object orientedprogramming, error handling
Data Types
Numeric Types (p. 1-52) Integer and floating-point dataCharacters and Strings (p. 1-53) Characters and arrays of charactersStructures (p. 1-54) Data of varying types and sizes
stored in fields of a structure
1-51
1 Function Reference
Cell Arrays (p. 1-55) Data of varying types and sizesstored in cells of array
Function Handles (p. 1-56) Invoke a function indirectly viahandle
Java Classes and Objects (p. 1-56) Access Java classes throughMATLAB interface
Data Type Identification (p. 1-58) Determine data type of a variable
Numeric Types
arrayfun Apply function to each element ofarray
cast Cast variable to different data typecat Concatenate arrays along specified
dimensionclass Create object or return class of objectfind Find indices and values of nonzero
elementsintmax Largest value of specified integer
typeintmin Smallest value of specified integer
typeintwarning Control state of integer warningsipermute Inverse permute dimensions of N-D
arrayisa Determine whether input is object
of given classisequal Test arrays for equalityisequalwithequalnans Test arrays for equality, treating
NaNs as equalisfinite Array elements that are finite
1-52
Programming and Data Types
isinf Array elements that are infiniteisnan Array elements that are NaNisnumeric Determine whether input is numeric
arrayisreal Check if input is real arrayisscalar Determine whether input is scalarisvector Determine whether input is vectorpermute Rearrange dimensions of N-D arrayrealmax Largest positive floating-point
numberrealmin Smallest positive normalized
floating-point numberreshape Reshape arraysqueeze Remove singleton dimensionszeros Create array of all zeros
Characters and Strings
See “Strings” on page 1-64 for all string-related functions.
cellstr Create cell array of strings fromcharacter array
char Convert to character array (string)eval Execute string containing MATLAB
expressionfindstr Find string within another, longer
stringisstr Determine whether input is
character arrayregexp, regexpi Match regular expressionsprintf Write formatted data to string
1-53
1 Function Reference
sscanf Read formatted data from stringstrcat Concatenate strings horizontallystrcmp, strcmpi Compare stringsstrings String handlingstrjust Justify character arraystrmatch Find possible matches for stringstrread Read formatted data from stringstrrep Find and replace substringstrtrim Remove leading and trailing white
space from stringstrvcat Concatenate strings vertically
Structures
arrayfun Apply function to each element ofarray
cell2struct Convert cell array to structure arrayclass Create object or return class of objectdeal Distribute inputs to outputsfieldnames Field names of structure, or public
fields of objectgetfield Field of structure arrayisa Determine whether input is object
of given classisequal Test arrays for equalityisfield Determine whether input is
structure array fieldisscalar Determine whether input is scalarisstruct Determine whether input is
structure array
1-54
Programming and Data Types
isvector Determine whether input is vectororderfields Order fields of structure arrayrmfield Remove fields from structuresetfield Set value of structure array fieldstruct Create structure arraystruct2cell Convert structure to cell arraystructfun Apply function to each field of scalar
structure
Cell Arrays
cell Construct cell arraycell2mat Convert cell array of matrices to
single matrixcell2struct Convert cell array to structure arraycelldisp Cell array contentscellfun Apply function to each cell in cell
arraycellplot Graphically display structure of cell
arraycellstr Create cell array of strings from
character arrayclass Create object or return class of objectdeal Distribute inputs to outputsisa Determine whether input is object
of given classiscell Determine whether input is cell
arrayiscellstr Determine whether input is cell
array of strings
1-55
1 Function Reference
isequal Test arrays for equalityisscalar Determine whether input is scalarisvector Determine whether input is vectormat2cell Divide matrix into cell array of
matricesnum2cell Convert numeric array to cell arraystruct2cell Convert structure to cell array
Function Handles
class Create object or return class of objectfeval Evaluate functionfunc2str Construct function name string from
function handlefunctions Information about function handlefunction_handle (@) Handle used in calling functions
indirectlyisa Determine whether input is object
of given classisequal Test arrays for equalitystr2func Construct function handle from
function name string
Java Classes and Objects
cell Construct cell arrayclass Create object or return class of objectclear Remove items from workspace,
freeing up system memorydepfun List dependencies of M-file or P-file
1-56
Programming and Data Types
exist Check existence of variable, function,directory, or Java programminglanguage class
fieldnames Field names of structure, or publicfields of object
im2java Convert image to Java imageimport Add package or class to current
import listinmem Names of M-files, MEX-files, Sun
Java classes in memoryisa Determine whether input is object
of given classisjava Determine whether input is Sun
Java objectjavaaddpath Add entries to dynamic Sun Java
class pathjavaArray Construct Sun Java arrayjavachk Generate error message based on
Sun Java feature supportjavaclasspath Get and set Sun Java class pathjavaMethod Call Sun Java methodjavaMethodEDT Call Sun Java method from Event
Dispatch Thread (EDT)javaObject Construct Sun Java objectjavaObjectEDT Construct Sun Java object on Event
Dispatch Thread (EDT)javarmpath Remove entries from dynamic Sun
Java class pathmethods Information on class methodsmethodsview Information on class methods in
separate window
1-57
1 Function Reference
usejava Determine whether Sun Java featureis supported in MATLAB software
which Locate functions and files
Data Type Identification
is* Detect stateisa Determine whether input is object
of given classiscell Determine whether input is cell
arrayiscellstr Determine whether input is cell
array of stringsischar Determine whether item is character
arrayisfield Determine whether input is
structure array fieldisfloat Determine whether input is
floating-point arrayisinteger Determine whether input is integer
arrayisjava Determine whether input is Sun
Java objectislogical Determine whether input is logical
arrayisnumeric Determine whether input is numeric
arrayisobject Determine if input is MATLAB
objectisreal Check if input is real arrayisstr Determine whether input is
character array
1-58
Programming and Data Types
isstruct Determine whether input isstructure array
validateattributes Check validity of arraywho, whos List variables in workspace
Data Type Conversion
Numeric (p. 1-59) Convert data of one numeric type toanother numeric type
String to Numeric (p. 1-60) Convert characters to numericequivalent
Numeric to String (p. 1-60) Convert numeric to characterequivalent
Other Conversions (p. 1-61) Convert to structure, cell array,function handle, etc.
Numeric
cast Cast variable to different data typedouble Convert to double precisionint8, int16, int32, int64 Convert to signed integersingle Convert to single precisiontypecast Convert data types without changing
underlying datauint8, uint16, uint32, uint64 Convert to unsigned integer
1-59
1 Function Reference
String to Numeric
base2dec Convert base N number string todecimal number
bin2dec Convert binary number string todecimal number
cast Cast variable to different data typehex2dec Convert hexadecimal number string
to decimal numberhex2num Convert hexadecimal number string
to double-precision numberstr2double Convert string to double-precision
valuestr2num Convert string to numberunicode2native Convert Unicode® characters to
numeric bytes
Numeric to String
cast Cast variable to different data typechar Convert to character array (string)dec2base Convert decimal to base N number
in stringdec2bin Convert decimal to binary number
in stringdec2hex Convert decimal to hexadecimal
number in stringint2str Convert integer to stringmat2str Convert matrix to stringnative2unicode Convert numeric bytes to Unicode
charactersnum2str Convert number to string
1-60
Programming and Data Types
Other Conversions
cell2mat Convert cell array of matrices tosingle matrix
cell2struct Convert cell array to structure arraydatestr Convert date and time to string
formatfunc2str Construct function name string from
function handlelogical Convert numeric values to logicalmat2cell Divide matrix into cell array of
matricesnum2cell Convert numeric array to cell arraynum2hex Convert singles and doubles to
IEEE® hexadecimal stringsstr2func Construct function handle from
function name stringstr2mat Form blank-padded character matrix
from stringsstruct2cell Convert structure to cell array
Operators and Special Characters
Arithmetic Operators (p. 1-62) Plus, minus, power, left and rightdivide, transpose, etc.
Relational Operators (p. 1-62) Equal to, greater than, less than orequal to, etc.
Logical Operators (p. 1-62) Element-wise and short circuit and,or, not
Special Characters (p. 1-63) Array constructors, linecontinuation, comments, etc.
1-61
1 Function Reference
Arithmetic Operators
+ 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
Relational Operators
< Less than Greater than>= Greater than or equal to== Equal to~= Not equal to
Logical OperatorsSee also “Logical Operations” on page 1-67 for functions like xor, all, any, etc.
1-62
Programming and Data Types
&& Logical AND|| Logical OR& Logical AND for arrays| Logical OR for arrays~ Logical NOT
Special Characters
: Create vectors, subscript arrays, specify for-loop iterations( ) Pass function arguments, prioritize operators[ ] Construct array, concatenate elements, specify multiple
outputs from function{ } Construct cell array, index into cell array. Insert decimal point, define structure field, reference methods
of object.( ) Reference dynamic field of structure.. Reference parent directory
... Continue statement to next line, Separate rows of array, separate function input/output
arguments, separate commands; Separate columns of array, suppress output from current
command% Insert comment line into code
%{ %} Insert block of comments into code! Issue command to operating system’ ’ Construct character array@ Construct function handle, reference class directory
1-63
1 Function Reference
Strings
Description of Strings in MATLAB(p. 1-64)
Basics of string handling inMATLAB
String Creation (p. 1-64) Create strings, cell arrays of strings,concatenate strings together
String Identification (p. 1-65) Identify characteristics of stringsString Manipulation (p. 1-65) Convert case, strip blanks, replace
charactersString Parsing (p. 1-66) Formatted read, regular expressions,
locate substringsString Evaluation (p. 1-66) Evaluate stated expression in stringString Comparison (p. 1-66) Compare contents of strings
Description of Strings in MATLAB
strings String handling
String Creation
blanks Create string of blank characterscellstr Create cell array of strings from
character arraychar Convert to character array (string)sprintf Write formatted data to stringstrcat Concatenate strings horizontallystrvcat Concatenate strings vertically
1-64
Programming and Data Types
String Identification
class Create object or return class of objectisa Determine whether input is object
of given classiscellstr Determine whether input is cell
array of stringsischar Determine whether item is character
arrayisletter Array elements that are alphabetic
lettersisscalar Determine whether input is scalarisspace Array elements that are space
charactersisstrprop Determine whether string is of
specified categoryisvector Determine whether input is vectorvalidatestring Check validity of text string
String Manipulation
deblank Strip trailing blanks from end ofstring
lower Convert string to lowercasestrjust Justify character arraystrrep Find and replace substringstrtrim Remove leading and trailing white
space from stringupper Convert string to uppercase
1-65
1 Function Reference
String Parsing
findstr Find string within another, longerstring
regexp, regexpi Match regular expressionregexprep Replace string using regular
expressionregexptranslate Translate string into regular
expressionsscanf Read formatted data from stringstrfind Find one string within anotherstrread Read formatted data from stringstrtok Selected parts of string
String Evaluation
eval Execute string containing MATLABexpression
evalc Evaluate MATLAB expression withcapture
evalin Execute MATLAB expression inspecified workspace
String Comparison
strcmp, strcmpi Compare stringsstrmatch Find possible matches for stringstrncmp, strncmpi Compare first n characters of strings
1-66
Programming and Data Types
Bit-Wise Operations
bitand Bitwise ANDbitcmp Bitwise complementbitget Bit at specified positionbitmax Maximum double-precision
floating-point integerbitor Bitwise ORbitset Set bit at specified positionbitshift Shift bits specified number of placesbitxor Bitwise XORswapbytes Swap byte ordering
Logical Operations
all Determine whether all arrayelements are nonzero
and Find logical AND of array or scalarinputs
any Determine whether any arrayelements are nonzero
false Logical 0 (false)find Find indices and values of nonzero
elementsisa Determine whether input is object
of given classiskeyword Determine whether input is
MATLAB keywordisvarname Determine whether input is valid
variable namelogical Convert numeric values to logical
1-67
1 Function Reference
not Find logical NOT of array or scalarinput
or Find logical OR of array or scalarinputs
true Logical 1 (true)xor Logical exclusive-OR
See “Operators and Special Characters” on page 1-61 for logical operators.
Relational Operations
eq Test for equalityge Test for greater than or equal togt Test for greater thanle Test for less than or equal tolt Test for less thanne Test for inequality
See “Operators and Special Characters” on page 1-61 for relational operators.
Set Operations
intersect Find set intersection of two vectorsismember Array elements that are members
of setissorted Determine whether set elements are
in sorted ordersetdiff Find set difference of two vectorssetxor Find set exclusive OR of two vectors
1-68
Programming and Data Types
union Find set union of two vectorsunique Find unique elements of vector
Date and Time Operations
addtodate Modify date number by fieldcalendar Calendar for specified monthclock Current time as date vectorcputime Elapsed CPU timedate Current date stringdatenum Convert date and time to serial date
numberdatestr Convert date and time to string
formatdatevec Convert date and time to vector of
componentseomday Last day of monthetime Time elapsed between date vectorsnow Current date and timeweekday Day of week
Programming in MATLAB
M-Files and Scripts (p. 1-70) Declare functions, handlearguments, identify dependencies,etc.
Evaluation (p. 1-71) Evaluate expression in string, applyfunction to array, run script file, etc.
Timer (p. 1-72) Schedule execution of MATLABcommands
1-69
1 Function Reference
Variables and Functions in Memory(p. 1-73)
List files in memory, clear M-filesin memory, assign to variable innondefault workspace, refreshcaches
Control Flow (p. 1-74) if-then-else, for loops, switch-case,try-catch
Error Handling (p. 1-75) Generate warnings and errors, testfor and catch errors, retrieve mostrecent error message
MEX Programming (p. 1-76) Compile MEX function from C orFortran code, list MEX-files inmemory, debug MEX-files
M-Files and Scripts
addOptional (inputParser) Add optional argument toinputParser schema
addParamValue (inputParser) Add parameter-value argument toinputParser schema
addRequired (inputParser) Add required argument toinputParser schema
createCopy (inputParser) Create copy of inputParser objectdepdir List dependent directories of M-file
or P-filedepfun List dependencies of M-file or P-fileecho Echo M-files during executionend Terminate block of code, or indicate
last array indexfunction Declare M-file functioninput Request user inputinputname Variable name of function inputinputParser Construct input parser object
1-70
Programming and Data Types
mfilename Name of currently running M-filenamelengthmax Maximum identifier lengthnargchk Validate number of input argumentsnargin, nargout Number of function argumentsnargoutchk Validate number of output
argumentsparse (inputParser) Parse and validate named inputspcode Create protected M-file (P-file)script Script M-file descriptionsyntax Two ways to call MATLAB functionsvarargin Variable length input argument listvarargout Variable length output argument list
Evaluation
ans Most recent answerarrayfun Apply function to each element of
arrayassert Generate error when condition is
violatedbuiltin Execute built-in function from
overloaded methodcellfun Apply function to each cell in cell
arrayecho Echo M-files during executioneval Execute string containing MATLAB
expressionevalc Evaluate MATLAB expression with
capture
1-71
1 Function Reference
evalin Execute MATLAB expression inspecified workspace
feval Evaluate functioniskeyword Determine whether input is
MATLAB keywordisvarname Determine whether input is valid
variable namepause Halt execution temporarilyrun Run script that is not on current
pathscript Script M-file descriptionstructfun Apply function to each field of scalar
structuresymvar Determine symbolic variables in
expressiontic, toc Measure performance using
stopwatch timer
Timer
delete (timer) Remove timer object from memorydisp (timer) Information about timer objectget (timer) Timer object propertiesisvalid (timer) Determine whether timer object is
validset (timer) Configure or display timer object
propertiesstart Start timer(s) runningstartat Start timer(s) running at specified
timestop Stop timer(s)
1-72
Programming and Data Types
timer Construct timer objecttimerfind Find timer objectstimerfindall Find timer objects, including
invisible objectswait Wait until timer stops running
Variables and Functions in Memory
ans Most recent answerassignin Assign value to variable in specified
workspacedatatipinfo Produce short description of input
variablegenvarname Construct valid variable name from
stringglobal Declare global variablesinmem Names of M-files, MEX-files, Sun
Java classes in memoryisglobal Determine whether input is global
variablememory Display memory informationmislocked Determine whether M-file or
MEX-file cannot be cleared frommemory
mlock Prevent clearing M-file or MEX-filefrom memory
munlock Allow clearing M-file or MEX-filefrom memory
namelengthmax Maximum identifier lengthpack Consolidate workspace memory
1-73
1 Function Reference
persistent Define persistent variablerehash Refresh function and file system
path caches
Control Flow
break Terminate execution of for or whileloop
case Execute block of code if condition istrue
catch Specify how to respond to error intry statement
continue Pass control to next iteration of foror while loop
else Execute statements if condition isfalse
elseif Execute statements if additionalcondition is true
end Terminate block of code, or indicatelast array index
error Display message and abort functionfor Execute block of code specified
number of timesif Execute statements if condition is
trueotherwise Default part of switch statementparfor Parallel for-loopreturn Return to invoking functionswitch Switch among several cases, based
on expression
1-74
Programming and Data Types
try Attempt to execute block of code, andcatch errors
while Repeatedly execute statements whilecondition is true
Error Handling
addCause (MException) Append MException objectsassert Generate error when condition is
violatedcatch Specify how to respond to error in
try statementdisp (MException) Display MException objecteq (MException) Compare MException objects for
equalityerror Display message and abort functionferror Query MATLAB software about
errors in file input or outputgetReport (MException) Get error message for exceptionintwarning Control state of integer warningsisequal (MException) Compare MException objects for
equalitylast (MException) Last uncaught exceptionlasterr Last error messagelasterror Last error message and related
informationlastwarn Last warning messageMException Construct MException objectne (MException) Compare MException objects for
inequalityrethrow Reissue error
1-75
1 Function Reference
rethrow (MException) Reissue existing exceptionthrow (MException) Terminate function and issue
exceptiontry Attempt to execute block of code, and
catch errorswarning Warning message
MEX Programming
dbmex Enable MEX-file debugging (onUNIX platforms)
inmem Names of M-files, MEX-files, SunJava classes in memory
mex Compile MEX-function from C/ C++or Fortran source code
mex.getCompilerConfigurations Get compiler configurationinformation for building MEX-files
mexext Binary MEX-file name extension
1-76
Object-Oriented Programming
Object-Oriented Programming
Classes and Objects (p. 1-77) Get information about classes andobjects
Handle Classes (p. 1-78) Define and use handle classesEvents and Listeners (p. 1-79) Define and use events and listenersMeta-Classes (p. 1-79) Access information about classes
without requiring instances
Classes and Objects
class Create object or return class of objectclassdef Class definition key wordsfieldnames Field names of structure, or public
fields of objectimport Add package or class to current
import listinferiorto Specify inferior class relationshipisa Determine whether input is object
of given classisobject Determine if input is MATLAB
objectloadobj Modify how load function loads
objectsmethods Information on class methodsmethodsview Information on class methods in
separate windowproperties Display class property namessaveobj Modify how save function saves
objectssubsasgn Subscripted assignment for objects
1-77
1 Function Reference
subsindex Subscripted indexing using object asindex
subsref Subscripted reference for objectssubstruct Create structure argument for
subsasgn or subsrefsuperiorto Establish superior class relationship
Handle Classes
addlistener (handle) Create event listeneraddprop (dynamicprops) Add dynamic propertydelete (handle) Handle object destructor functiondynamicprops Abstract class used to derive handle
class with dynamic propertiesfindobj (handle) Find objects matching specified
conditionsfindprop (handle) Find meta.property object
associated with property nameget (hgsetget) Query property values of handle
objects derived from hgsetget classgetdisp (hgsetget) Override to change command
window displayhandle Abstract class for deriving handle
classeshgsetget Abstract class used to derive handle
class with set and get methodsisvalid (handle) Is object valid handle class objectnotify (handle) Notify listeners that event is
occurringrelationaloperators (handle) Equality and sorting of handle
objects
1-78
Object-Oriented Programming
set (hgsetget) Assign property values to handleobjects derived from hgsetget class
setdisp (hgsetget) Override to change commandwindow display
Events and Listeners
addlistener (handle) Create event listenerevent.EventData Base class for all data objects passed
to event listenersevent.listener Class defining listener objectsevent.PropertyEvent Listener for property eventsevent.proplistener Define listener object for property
eventsevents Display class event namesnotify (handle) Notify listeners that event is
occurring
Meta-Classes
meta.class meta.class class describesMATLAB classes
meta.class.fromName Return meta.class object associatedwith named class
meta.DynamicProperty meta.DynamicProperty classdescribes dynamic property ofMATLAB object
meta.event meta.event class describesMATLAB class events
meta.method meta.method class describesMATLAB class methods
1-79
1 Function Reference
meta.package meta.package class describesMATLAB packages
meta.package.fromName Return meta.package object forspecified package
meta.package.getAllPackages Get all top-level packagesmeta.property meta.property class describes
MATLAB class propertiesmetaclass Return meta.class object
1-80
File I/O
File I/O
File Name Construction (p. 1-81) Get path, directory, filenameinformation; construct filenames
File Opening, Loading, and Saving(p. 1-82)
Open files; transfer data betweenfiles and MATLAB workspace
Memory Mapping (p. 1-82) Access file data via memory mapusing MATLAB array indexing
Low-Level File I/O (p. 1-82) Low-level operations that use a fileidentifier
Text Files (p. 1-83) Delimited or formatted I/O to textfiles
XML Documents (p. 1-84) Documents written in ExtensibleMarkup Language
Spreadsheets (p. 1-84) Excel and Lotus 1-2-3 filesScientific Data (p. 1-85) CDF, FITS, HDF formatsAudio and Audio/Video (p. 1-88) General audio functions;
SparcStation, WAVE, AVI filesImages (p. 1-90) Graphics filesInternet Exchange (p. 1-91) URL, FTP, zip, tar, and e-mail
To see a listing of file formats that are readable from MATLAB, go to fileformats.
File Name Construction
filemarker Character to separate file name andinternal function name
fileparts Parts of file name and pathfilesep Directory separator for current
platformfullfile Build full filename from parts
1-81
1 Function Reference
tempdir Name of system’s temporarydirectory
tempname Unique name for temporary file
File Opening, Loading, and Saving
daqread Read Data Acquisition Toolbox™(.daq) file
importdata Load data from disk fileload Load workspace variables from diskopen Open files based on extensionsave Save workspace variables to diskuiimport Open Import Wizard to import datawinopen Open file in appropriate application
(Windows)
Memory Mapping
disp (memmapfile) Information about memmapfileobject
get (memmapfile) Memmapfile object propertiesmemmapfile Construct memmapfile object
Low-Level File I/O
fclose Close one or more open filesfeof Test for end-of-fileferror Query MATLAB software about
errors in file input or output
1-82
File I/O
fgetl Read line from file, discardingnewline characters
fgets Read line from file, keeping newlinecharacters
fopen Open file, or obtain informationabout open files
fprintf Write formatted data to filefread Read binary data from filefrewind Move file position indicator to
beginning of open filefscanf Read formatted data from a text filefseek Set file position indicatorftell File position indicatorfwrite Write binary data to file
Text Files
csvread Read comma-separated value filecsvwrite Write comma-separated value filedlmread Read ASCII-delimited file of numeric
data into matrixdlmwrite Write matrix to ASCII-delimited filefileread Return contents of file as string
vectortextread Read data from text file; write to
multiple outputstextscan Read formatted data from text file
or string
1-83
1 Function Reference
XML Documents
xmlread Parse XML document and returnDocument Object Model node
xmlwrite Serialize XML Document ObjectModel node
xslt Transform XML document usingXSLT engine
Spreadsheets
Microsoft Excel (p. 1-84) Read and write Microsoft Excelspreadsheet
Lotus 1-2-3 (p. 1-84) Read and write Lotus WK1spreadsheet
Microsoft Excel
xlsfinfo Determine whether file contains aMicrosoft® Excel® spreadsheet
xlsread Read Microsoft Excel spreadsheetfile
xlswrite Write Microsoft Excel spreadsheetfile
Lotus 1-2-3
wk1finfo Determine whether file contains1-2-3 WK1 worksheet
wk1read Read Lotus 1-2-3 WK1 spreadsheetfile into matrix
wk1write Write matrix to Lotus 1-2-3 WK1spreadsheet file
1-84
File I/O
Scientific Data
Common Data Format (p. 1-85) Work with CDF filesNetwork Common Data Form(p. 1-85)
Work with netCDF files
Flexible Image Transport System(p. 1-87)
Work with FITS files
Hierarchical Data Format (p. 1-87) Work with HDF filesBand-Interleaved Data (p. 1-88) Work with band-interleaved files
Common Data Format