“Overview” on page 1-2 “Constructing a Simple Matrix” on page 1-3 “Specialized Matrix Functions” on page 1-4 “Concatenating Matrices” on page 1-7 “Matrix Concatenation Functions” on page
Trang 2suggest@mathworks.com Product enhancement suggestions
bugs@mathworks.com Bug reports
doc@mathworks.com Documentation error reports
service@mathworks.com Order status, license renewals, passcodes
info@mathworks.com Sales, pricing, and general information
508-647-7000 (Phone)
508-647-7001 (Fax)
The MathWorks, Inc.
3 Apple Hill Drive
Natick, MA 01760-2098
For contact information about worldwide offices, see the MathWorks Web site
MATLAB Programming Fundamentals
© COPYRIGHT 1984–2008 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, for, or through the federal government of the United States By accepting delivery of the Program
or Documentation, the government hereby agrees that this software or documentation qualifies as commercial computer software or commercial computer software documentation as such terms are used
or defined in FAR 12.212, DFARS Part 227.72, and DFARS 252.227-7014 Accordingly, the terms and conditions of this Agreement and only those rights specified in this Agreement, shall pertain to and govern the use, modification, reproduction, release, performance, display, and disclosure of the Program and Documentation 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 the government’s needs or is inconsistent in any respect with federal procurement law, the government agrees
to return the Program and Documentation, unused, to The MathWorks, Inc.
Trademarks
MATLAB and Simulink are registered trademarks of The MathWorks, Inc See
www.mathworks.com/trademarks for a list of additional trademarks Other product or brand names may be trademarks or registered trademarks of their respective holders.
Patents
The MathWorks products are protected by one or more U.S patents Please see
www.mathworks.com/patents for more information.
Trang 3March 2006 Online only Revised for MATLAB 7.2 (Release 2006a) September 2006 Online only Revised for MATLAB 7.3 (Release 2006b) March 2007 Online only Revised for MATLAB 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)
Trang 5Matrices and Arrays 1
Creating and Concatenating Matrices . 1-2
Overview . 1-2
Constructing a Simple Matrix . 1-3
Specialized Matrix Functions . 1-4
Concatenating Matrices . 1-7
Matrix Concatenation Functions . 1-8
Generating a Numeric Sequence . 1-10
Combining Unlike Classes . 1-12
Matrix Indexing . 1-17
Accessing Single Elements . 1-17
Linear Indexing . 1-18
Functions That Control Indexing Style . 1-18
Accessing Multiple Elements . 1-19
Using Logicals in Array Indexing . 1-21
Single-Colon Indexing with Different Array Types . 1-25
Indexing on Assignment . 1-25
Getting Information About a Matrix . 1-27
Dimensions of the Matrix . 1-27
Classes Used in the Matrix . 1-28
Data Structures Used in the Matrix . 1-29
Resizing and Reshaping Matrices . 1-30
Expanding the Size of a Matrix . 1-30
Diminishing the Size of a Matrix . 1-34
Reshaping a Matrix . 1-35
Preallocating Memory . 1-37
Shifting and Sorting Matrices . 1-40
Shift and Sort Functions . 1-40
Shifting the Location of Matrix Elements . 1-40
Sorting the Data in Each Column . 1-42
Sorting the Data in Each Row . 1-42
Trang 6Returning a Triangular Portion of a Matrix . 1-46
Concatenating Matrices Diagonally . 1-46
Empty Matrices, Scalars, and Vectors . 1-47
Creating Multidimensional Arrays . 1-57
Accessing Multidimensional Array Properties . 1-61
Indexing Multidimensional Arrays . 1-61
Reshaping Multidimensional Arrays . 1-65
Permuting Array Dimensions . 1-67
Computing with Multidimensional Arrays . 1-69
Organizing Data in Multidimensional Arrays . 1-70
Multidimensional Cell Arrays . 1-72
Multidimensional Structure Arrays . 1-73 Summary of Matrix and Array Functions . 1-75
Classes (Data Types) 2
Overview of MATLAB Classes . 2-2
Fundamental Classes . 2-2
How to Use the Different Classes . 2-3
Trang 7Complex Numbers . 2-23
Infinity and NaN . 2-24
Identifying Numeric Classes . 2-26
Display Format for Numeric Values . 2-26
Function Summary . 2-28
Logical Classes . 2-32
Overview of Logical Classes . 2-32
Identifying Logical Arrays . 2-33
Functions that Return a Logical Result . 2-34
Using Logical Arrays in Conditional Statements . 2-36
Using Logical Arrays in Indexing . 2-37
Characters and Strings . 2-38
Creating Character Arrays . 2-38
Cell Arrays of Strings . 2-43
Formatting Strings . 2-45
String Comparisons . 2-58
Searching and Replacing . 2-61
Converting from Numeric to String . 2-62
Converting from String to Numeric . 2-64
Function Summary . 2-66
Structures . 2-69
Overview . 2-69
Building Structure Arrays . 2-70
Accessing Data in Structure Arrays . 2-73
Using Dynamic Field Names . 2-75
Finding the Size of Structure Arrays . 2-76
Adding Fields to Structures . 2-77
Deleting Fields from Structures . 2-78
Applying Functions and Operators . 2-78
Writing Functions to Operate on Structures . 2-79
Organizing Data in Structure Arrays . 2-80
Nesting Structures . 2-86
Function Summary . 2-87
Cell Arrays . 2-88
Trang 8Reshaping Cell Arrays . 2-101
Replacing Lists of Variables with Cell Arrays . 2-102
Applying Functions and Operators . 2-103
Organizing Data in Cell Arrays . 2-104
Nesting Cell Arrays . 2-105
Converting Between Cell and Numeric Arrays . 2-107
Cell Arrays of Structures . 2-108
Function Summary . 2-109
Function Handles . 2-110
Overview . 2-110
Creating a Function Handle . 2-110
Calling a Function Using Its Handle . 2-113
Handling Values Returned From a Call . 2-114
Applications of Function Handles . 2-115
Saving and Loading Function Handles . 2-120
Advanced Operations on Function Handles . 2-121
Functions That Operate on Function Handles . 2-127
Map Containers . 2-128
Overview of the Map Data Structure . 2-128
Description of the Map Class . 2-129
Creating a Map Object . 2-131
Examining the Contents of the Map . 2-134
Reading and Writing Using a Key Index . 2-135
Modifying Keys and Values in the Map . 2-138
Mapping to Different Value Types . 2-140
Methods Summary . 2-142 Definìng Your Own Classes . 2-143 Sun Java Classes . 2-144
Trang 9MATLAB Commands . 3-2
Basic Command Syntax . 3-2
Entering More Than One Command on a Line . 3-3
Assigning to Multiple Outputs . 3-3
Commands that Call MATLAB Functions . 3-5
What Is a Comma-Separated List? . 3-34
Generating a Comma-Separated List . 3-34
Assigning Output from a Comma-Separated List . 3-36
Assigning to a Comma-Separated List . 3-37
How to Use the Comma-Separated Lists . 3-38
Fast Fourier Transform Example . 3-40
Program Control Statements . 3-42
Conditional Control — if, switch . 3-42
Trang 10Overview . 3-51
Types of Date Formats . 3-51
Conversions Between Date Formats . 3-53
Date String Formats . 3-54
Trang 11Overloaded MATLAB Functions . 3-122
Functions and Scripts 4
Program Development . 4-2
Overview . 4-2
Creating a Program . 4-2
Getting the Bugs Out . 4-4
Cleaning Up the Program . 4-5
Basic Parts of an M-File . 4-8
Creating a Simple M-File . 4-13
Providing Help for Your Program . 4-15
Cleaning Up the M-File When Done . 4-16
Creating P-Code Files . 4-17
M-File Scripts and Functions . 4-19
Trang 12Determining Which Function Gets Called . 4-34
Calling External Functions . 4-37
Running External Programs . 4-38
Function Arguments . 4-39
Overview . 4-39
Passing Certain Argument Types . 4-39
Passing Arguments in Structures or Cell Arrays . 4-41
Assigning Output Arguments . 4-43
Checking the Number of Input Arguments . 4-45
Passing Variable Numbers of Arguments . 4-47
Parsing Inputs with inputParser . 4-50
Passing Optional Arguments to Nested Functions . 4-60
Returning Modified Input Arguments . 4-63
Types of Functions 5
Overview of MATLAB Function Types . 5-2
Anonymous Functions . 5-3
Constructing an Anonymous Function . 5-3
Arrays of Anonymous Functions . 5-6
Outputs from Anonymous Functions . 5-7
Variables Used in the Expression . 5-8
Examples of Anonymous Functions . 5-11 Primary M-File Functions . 5-15
Nested Functions . 5-16
Writing Nested Functions . 5-16
Calling Nested Functions . 5-18
Variable Scope in Nested Functions . 5-19
Trang 13MATLAB Objects . 6-2
What Are Objects? . 6-2
Objects In the MATLAB Language . 6-3
Other Kinds of Objects Used by MATLAB . 6-3
General Purpose Vs Specialized Arrays . 6-5
How They Differ . 6-5
Using General-Purpose Variables . 6-5
Using Specialized Objects . 6-6
Key Object Concepts . 6-8
Basic Concepts . 6-8
Classes Describe How to Create Objects . 6-8
Properties Contain Data . 6-8
Methods Implement Operations . 6-9
Creating Objects . 6-11
Class Constructor . 6-11
When to Use Package Names . 6-11
Trang 14Calling Object Methods . 6-16
What Operations Can You Perform . 6-16
Method Syntax . 6-16
Class of Objects Returned by Methods . 6-18
Desktop Tools Are Object Aware . 6-19
Tab Completion Works with Objects . 6-19
Editing Objects with the Variable Editor . 6-19
Getting Information About Objects . 6-21
The Class of Workspace Variables . 6-21
Information About Class Members . 6-23
Logical Tests for Objects . 6-23
Displaying Objects . 6-24
Getting Help for MATLAB Objects . 6-25
Copying Objects . 6-26
Two Copy Behaviors . 6-26
Value Object Copy Behavior . 6-26
Handle Object Copy Behavior . 6-27
Testing for Handle or Value Class . 6-29
Data Import and Export 7
Overview . 7-2
Supported File Types . 7-2
Other MATLAB I/O Capabilities . 7-4
Functions Used in File Management . 7-6 Supported File Formats . 7-8 Using the Import Wizard . 7-11
Trang 15Determining Assignment to Variables . 7-16
Automated M-Code Generation . 7-19
Writing Data to the Workspace . 7-22
Accessing Files with Memory-Mapping . 7-24
Overview of Memory-Mapping . 7-24
The memmapfile Class . 7-28
Constructing a memmapfile Object . 7-30
Reading a Mapped File . 7-44
Writing to a Mapped File . 7-49
Methods of the memmapfile Class . 7-57
Deleting a Memory Map . 7-59
Unicode Character Encoding . 7-69
Optional Output Formats . 7-70
Storage Requirements . 7-71
Saving from External Programs . 7-72
Importing Data From MAT-Files . 7-73
Using the load Function . 7-73
Previewing MAT-File Contents . 7-73
Loading Into a Structure . 7-74
Loading Binary Data . 7-74
Loading ASCII Data . 7-75
Importing Text Data . 7-76
The MATLAB Import Wizard . 7-76
Using Import Functions with Text Data . 7-76
Importing Numeric Text Data . 7-79
Importing Delimited ASCII Data Files . 7-80
Importing Numeric Data with Text Headers . 7-81
Trang 16Exporting Delimited ASCII Data Files . 7-87
Using the diary Function to Export Data . 7-88
Exporting to XML Documents . 7-89
Working with Graphics Files . 7-90
Getting Information About Graphics Files . 7-90
Importing Graphics Data . 7-91
Exporting Graphics Data . 7-91
Working with Audio and Video Data . 7-93
Getting Information About Audio/Video Files . 7-93
Importing Audio/Video Data . 7-93
Exporting Audio/Video Data . 7-95
Working with Spreadsheets . 7-98
Microsoft®Excel Spreadsheets . 7-98
Lotus 123 Spreadsheets . 7-101
Using Low-Level File I/O Functions . 7-104
Overview . 7-104
Opening Files . 7-105
Reading Binary Data . 7-107
Writing Binary Data . 7-109
Controlling Position in a File . 7-109
Reading Strings Line by Line from Text Files . 7-112
Reading Formatted ASCII Data . 7-113
Writing Formatted Text Files . 7-114
Closing a File . 7-115
Exchanging Files over the Internet . 7-117
Overview . 7-117
Downloading Web Content and Files . 7-117
Creating and Decompressing Zip Archives . 7-119
Sending E-Mail . 7-120
Performing FTP File Operations . 7-122
Trang 17Common Data Format (CDF) Files . 8-2
Getting Information About CDF Files . 8-2
Importing Data from a CDF File . 8-3
Exporting Data to a CDF File . 8-6
Network Common Data Form (netCDF) Files . 8-8
Overview . 8-8
Mapping netCDF API Syntax to MATLAB Function
Syntax . 8-9
Example: Exploring the Contents of a netCDF File . 8-10
Example: Reading Data from a netCDF File . 8-14
Example: Storing Data in a netCDF File . 8-14
Flexible Image Transport System (FITS) Files . 8-17
Getting Information About FITS Files . 8-17
Importing Data from a FITS File . 8-18
Hierarchical Data Format (HDF5) Files . 8-20
Using the MATLAB High-Level HDF5 Functions . 8-20
Using the MATLAB Low-Level HDF5 Functions . 8-35
Hierarchical Data Format (HDF4) Files . 8-45
Using the HDF Import Tool . 8-45
Using the HDF Import Tool Subsetting Options . 8-50
Using the MATLAB HDF4 High-Level Functions . 8-62
Using the HDF4 Low-Level Functions . 8-65
Error Handling 9
Error Reporting in a MATLAB Application . 9-2
Overview . 9-2
Getting an Exception at the Command Line . 9-2
Getting an Exception in Your Program Code . 9-3
Generating a New Exception . 9-4
Trang 18Throwing an Exception . 9-16
Responding to an Exception . 9-17
Overview . 9-17
The try-catch Statement . 9-17
Suggestions on How to Handle an Exception . 9-19
Warning Control Statements . 9-26
Output from Control Statements . 9-28
Saving and Restoring State . 9-30
Backtrace and Verbose Modes . 9-31 Debugging Errors and Warnings . 9-34
Program Scheduling 10
Using a MATLAB Timer Object . 10-2
Overview . 10-2
Example: Displaying a Message . 10-3
Creating Timer Objects . 10-5
Creating the Object . 10-5
Naming the Object . 10-6
Trang 19Starting and Stopping Timers . 10-10
Starting a Timer . 10-10
Starting a Timer at a Specified Time . 10-10
Stopping Timer Objects . 10-11
Blocking the MATLAB Command Line . 10-12
Creating and Executing Callback Functions . 10-14
Associating Commands with Timer Object Events . 10-14
Creating Callback Functions . 10-15
Specifying the Value of Callback Function Properties . 10-17
Timer Object Execution Modes . 10-19
Executing a Timer Callback Function Once . 10-19
Executing a Timer Callback Function Multiple Times . 10-20
Handling Callback Function Queuing Conflicts . 10-21
Deleting Timer Objects from Memory . 10-23
Deleting One or More Timer Objects . 10-23
Testing the Validity of a Timer Object . 10-23
Finding Timer Objects in Memory . 10-24
Finding All Timer Objects . 10-24
Finding Invisible Timer Objects . 10-24
Performance 11
Analyzing Your Program’s Performance . 11-2
Overview . 11-2
The M-File Profiler Utility . 11-2
Stopwatch Timer Functions . 11-2
Techniques for Improving Performance . 11-4
Vectorizing Loops . 11-4
Trang 20Coding Loops in a MEX-File . 11-10
Assigning to Variables . 11-10
Operating on Real Data . 11-11
Using Appropriate Logical Operators . 11-11
Overloading Built-In Functions . 11-12
Functions Are Generally Faster Than Scripts . 11-12
Load and Save Are Faster Than File I/O Functions . 11-12
Avoid Large Background Processes . 11-12
Memory Allocation . 12-2
Memory Allocation for Arrays . 12-2
Data Structures and Memory . 12-7
Memory Management Functions . 12-12
The whos Function . 12-13
Strategies for Efficient Use of Memory . 12-14
Ways to Reduce the Amount of Memory Required . 12-14
Using Appropriate Data Storage . 12-16
How to Avoid Fragmenting Memory . 12-19
Reclaiming Used Memory . 12-21
Resolving “Out of Memory” Errors . 12-22
General Suggestions for Reclaiming Memory . 12-22
Setting the Process Limit . 12-23
Disabling Java VM on Startup . 12-24
Trang 21Programming Tips 13
Introduction . 13-2
Command and Function Syntax . 13-3
Syntax Help . 13-3
Command and Function Syntaxes . 13-3
Command Line Continuation . 13-3
Completing Commands Using the Tab Key . 13-4
Recalling Commands . 13-4
Clearing Commands . 13-5
Suppressing Output to the Screen . 13-5
Help . 13-6
Using the Help Browser . 13-6
Help on Functions from the Help Browser . 13-7
Help on Functions from the Command Window . 13-7
Topical Help . 13-7
Paged Output . 13-8
Writing Your Own Help . 13-8
Help for Subfunctions and Private Functions . 13-9
Help for Methods and Overloaded Functions . 13-9
Development Environment . 13-10
Workspace Browser . 13-10
Using the Find and Replace Utility . 13-10
Commenting Out a Block of Code . 13-11
Creating M-Files from Command History . 13-11
Editing M-Files in EMACS . 13-11
M-File Functions . 13-12
M-File Structure . 13-12
Using Lowercase for Function Names . 13-12
Getting a Function’s Name and Path . 13-13
Trang 22Variable Numbers of Arguments . 13-15
String or Numeric Arguments . 13-16
Passing Arguments in a Structure . 13-16
Passing Arguments in a Cell Array . 13-17
Program Development . 13-18
Planning the Program . 13-18
Using Pseudo-Code . 13-18
Selecting the Right Data Structures . 13-18
General Coding Practices . 13-19
Naming a Function Uniquely . 13-19
The Importance of Comments . 13-19
Coding in Steps . 13-20
Making Modifications in Steps . 13-20
Functions with One Calling Function . 13-20
Testing the Final Program . 13-20
Debugging . 13-21
The MATLAB Debug Functions . 13-21
More Debug Functions . 13-21
The MATLAB Graphical Debugger . 13-22
A Quick Way to Examine Variables . 13-22
Setting Breakpoints from the Command Line . 13-23
Finding Line Numbers to Set Breakpoints . 13-23
Stopping Execution on an Error or Warning . 13-23
Locating an Error from the Error Message . 13-23
Using Warnings to Help Debug . 13-24
Making Code Execution Visible . 13-24
Debugging Scripts . 13-24
Variables . 13-25
Rules for Variable Names . 13-25
Making Sure Variable Names Are Valid . 13-25
Do Not Use Function Names for Variables . 13-26
Checking for Reserved Keywords . 13-26
Avoid Using i and j for Variables . 13-27
Avoid Overwriting Variables in Scripts . 13-27
Trang 23Strings . 13-29
Creating Strings with Concatenation . 13-29
Comparing Methods of Concatenation . 13-29
Store Arrays of Strings in a Cell Array . 13-30
Converting Between Strings and Cell Arrays . 13-30
Search and Replace Using Regular Expressions . 13-31
Evaluating Expressions . 13-32
Find Alternatives to Using eval . 13-32
Assigning to a Series of Variables . 13-32
Short-Circuit Logical Operators . 13-33
Changing the Counter Variable within a for Loop . 13-33
MATLAB Path . 13-34
Precedence Rules . 13-34
File Precedence . 13-35
Adding a Directory to the Search Path . 13-35
Handles to Functions Not on the Path . 13-35
Making Toolbox File Changes Visible to MATLAB . 13-36
Making Nontoolbox File Changes Visible to MATLAB . 13-37
Change Notification on Windows . 13-37
Program Control . 13-38
Using break, continue, and return . 13-38
Using switch Versus if . 13-39
MATLAB case Evaluates Strings . 13-39
Multiple Conditions in a case Statement . 13-39
Implicit Break in switch-case . 13-39
Variable Scope in a switch . 13-40
Catching Errors with try-catch . 13-40
Nested try-catch Blocks . 13-41
Forcing an Early Return from a Function . 13-41
Save and Load . 13-42
Saving Data from the Workspace . 13-42
Loading Data into the Workspace . 13-42
Viewing Variables in a MAT-File . 13-43
Appending to a MAT-File . 13-43
Trang 24Naming Other Files . 13-45
Passing Filenames as Arguments . 13-46
Passing Filenames to ASCII Files . 13-46
Determining Filenames at Run-Time . 13-46
Returning the Size of a File . 13-46
Input/Output . 13-48
File I/O Function Overview . 13-48
Common I/O Functions . 13-48
Readable File Formats . 13-49
Using the Import Wizard . 13-49
Loading Mixed Format Data . 13-49
Reading Files with Different Formats . 13-50
Reading ASCII Data into a Cell Array . 13-50
Interactive Input into Your Program . 13-50
Starting MATLAB . 13-51
Getting MATLAB to Start Up Faster . 13-51
Operating System Compatibility . 13-52
Executing O/S Commands from MATLAB . 13-52
Searching Text with grep . 13-52
Constructing Paths and Filenames . 13-52
Finding the MATLAB Root Directory . 13-53
Temporary Directories and Filenames . 13-53
Demos . 13-54
Demos Available with MATLAB . 13-54
For More Information . 13-55
Trang 25Index
Trang 27Matrices and Arrays
• “Creating and Concatenating Matrices” on page 1-2
• “Matrix Indexing” on page 1-17
• “Getting Information About a Matrix” on page 1-27
• “Resizing and Reshaping Matrices” on page 1-30
• “Shifting and Sorting Matrices” on page 1-40
• “Operating on Diagonal Matrices” on page 1-45
• “Empty Matrices, Scalars, and Vectors” on page 1-47
• “Full and Sparse Matrices” on page 1-53
• “Multidimensional Arrays” on page 1-55
• “Summary of Matrix and Array Functions” on page 1-75
Trang 28Creating and Concatenating Matrices
In this section
“Overview” on page 1-2
“Constructing a Simple Matrix” on page 1-3
“Specialized Matrix Functions” on page 1-4
“Concatenating Matrices” on page 1-7
“Matrix Concatenation Functions” on page 1-8
“Generating a Numeric Sequence” on page 1-10
“Combining Unlike Classes” on page 1-12
Overview
The most basic MATLAB®data structure is the matrix: a two-dimensional,
rectangularly shaped data structure capable of storing multiple elements ofdata in an easily accessible format These data elements can be numbers,characters, logical states oftrueorfalse, or even other MATLAB structuretypes MATLAB uses these two-dimensional matrices to store single numbersand linear series of numbers as well In these cases, the dimensions are 1-by-1and 1-by-n respectively, wherenis the length of the numeric series MATLABalso supports data structures that have more than two dimensions These
data structures are referred to as arrays in the MATLAB documentation.
MATLAB is a matrix-based computing environment All of the data that youenter into MATLAB is stored in the form of a matrix or a multidimensionalarray Even a single numeric value like100is stored as a matrix (in this case,
a matrix having dimensions 1-by-1):
A = 100;
whos A
Trang 29Regardless of the class being used, whether it is numeric, character, or logical
trueorfalsedata, MATLAB stores this data in matrix (or array) form For
example, the string'Hello World'is a 1-by-11 matrix of individual characterelements in MATLAB You can also build matrices composed of more complexclasses, such as MATLAB structures and cell arrays
To create a matrix of basic data elements such as numbers or characters, see
• “Constructing a Simple Matrix” on page 1-3
• “Specialized Matrix Functions” on page 1-4
To build a matrix composed of other matrices, see
• “Concatenating Matrices” on page 1-7
• “Matrix Concatenation Functions” on page 1-8
This section also describes
• “Generating a Numeric Sequence” on page 1-10
• “Combining Unlike Classes” on page 1-12
Constructing a Simple Matrix
The simplest way to create a matrix in MATLAB is to use the matrix
constructor operator,[] Create a row in the matrix by entering elements
(shown asEbelow) within the brackets Separate each element with a comma
or space:
row = [E1, E2, , Em] row = [E1 E2 Em]
For example, to create a one row matrix of five elements, type
A = [12 62 93 -8 22];
To start a new row, terminate the current row with a semicolon:
A = [row1; row2; ; rown]
Trang 30This example constructs a 3 row, 5 column (or 3-by-5) matrix of numbers.Note that all rows must have the same number of elements:
Entering Signed Numbers
When entering signed numbers into a matrix, make sure that the signimmediately precedes the numeric value Note that while the following twoexpressions are equivalent,
Specialized Matrix Functions
MATLAB has a number of functions that create different kinds of matrices.Some create specialized matrices like the Hankel or Vandermonde matrix.The functions shown in the table below create matrices for more general use
Function Description
ones Create a matrix or array of all ones
Trang 31Function Description
zeros Create a matrix or array of all zeros
eye Create a matrix with ones on the diagonal and zeros
elsewhere
accumarray Distribute elements of an input matrix to specified
locations in an output matrix, also allowing foraccumulation
diag Create a diagonal matrix from a vector
magic Create a square matrix with rows, columns, and diagonals
that add up to the same number
rand Create a matrix or array of uniformly distributed random
numbers
randn Create a matrix or array of normally distributed random
numbers and arrays
randperm Create a vector (1-by-n matrix) containing a random
permutation of the specified integers
Most of these functions return matrices of typedouble(double-precision
floating point) However, you can easily build basic arrays of any numeric
type using theones,zeros, andeyefunctions
To do this, specify the MATLAB class name as the last argument:
Trang 32Creating a Magic Square Matrix A magic square is a matrix in which
the sum of the elements in each column, or each row, or each main diagonal
is the same To create a 5-by-5 magic square matrix, use themagicfunction
A = rand(5) * 20
A =19.0026 15.2419 12.3086 8.1141 1.15784.6228 9.1294 15.8387 18.7094 7.057412.1369 0.3701 18.4363 18.3381 16.26339.7196 16.4281 14.7641 8.2054 0.197217.8260 8.8941 3.5253 17.8730 2.7778
The sequence of numbers produced byrandis determined by the internalstate of the generator Setting the generator to the same fixed state enablesyou to repeat computations Examples in this documentation that use the
randfunction are initialized to a state of 0 to make the output consistenteach time they are run:
rand('state', 0);
Creating a Diagonal Matrix Usediagto create a diagonal matrix from avector You can place the vector along the main diagonal of the matrix, or on adiagonal that is above or below the main one, as shown here The-1inputplaces the vector one row below the main diagonal:
Trang 33not only as a matrix constructor, but also as the MATLAB concatenation
operator The expressionC = [A B]horizontally concatenates matricesAand
B The expressionC = [A; B]vertically concatenates them
This example constructs a new matrixCby concatenating matricesAandB
in a vertical direction:
A = ones(2, 5) * 6; % 2-by-5 matrix of 6's
B = rand(3, 5); % 3-by-5 matrix of random values
C = [A; B] % Vertically concatenate A and B
C =
6.0000 6.0000 6.0000 6.0000 6.00006.0000 6.0000 6.0000 6.0000 6.00000.9501 0.4860 0.4565 0.4447 0.92180.2311 0.8913 0.0185 0.6154 0.73820.6068 0.7621 0.8214 0.7919 0.1763
Keeping Matrices Rectangular
You can construct matrices, or even multidimensional arrays, using
concatenation as long as the resulting matrix does not have an irregular
shape (as in the second illustration shown below) If you are building a matrixhorizontally, then each component matrix must have the same number of
Trang 34rows When building vertically, each component must have the same number
of columns
This diagram shows two matrices of the same height (i.e., same number ofrows) being combined horizontally to form a new matrix
The next diagram illustrates an attempt to horizontally combine two matrices
of unequal height MATLAB does not allow this
Matrix Concatenation Functions
The following functions combine existing matrices to form a new matrix
Function Description
cat Concatenate matrices along the specified dimension
horzcat Horizontally concatenate matrices
vertcat Vertically concatenate matrices
repmat Create a new matrix by replicating and tiling existing
Trang 35Concatenating Matrices and Arrays An alternative to using the[]
operator for concatenation are the three functionscat,horzcat, andvertcat.With these functions, you can construct matrices (or multidimensional arrays)along a specified dimension Either of the following commands accomplish thesame task as the commandC = [A; B]used in the section on “ConcatenatingMatrices” on page 1-7:
C = cat(1, A, B); % Concatenate along the first dimension
C = vertcat(A, B); % Concatenate vertically
Replicating a Matrix Use therepmatfunction to create a matrix composed
of copies of an existing matrix When you enter
Creating a Block Diagonal Matrix Theblkdiagfunction combines
matrices in a diagonal direction, creating what is called a block diagonal
matrix All other elements of the newly created matrix are set to zero:
A = magic(3);
B = [-5 -6 -9; -4 -4 -2];
C = eye(2) * 8;
Trang 36Generating a Numeric Sequence
Because numeric sequences can often be useful in constructing and indexinginto matrices and arrays, MATLAB provides a special operator to assist increating them
This section covers
• “The Colon Operator” on page 1-10
• “Using the Colon Operator with a Step Value” on page 1-11
The Colon Operator
The colon operator (first:last) generates a 1-by-n matrix (or vector) of
sequential numbers from thefirstvalue to thelast The default sequence ismade up of incremental values, each 1 greater than the previous one:
By default, MATLAB always increments by exactly 1 when creating thesequence, even if the ending value is not an integral distance from the start:
Trang 37A = 1:6.3
A =
Also, the default series generated by the colon operator always increments
rather than decrementing The operation shown in this example attempts to
increment from 9 to 1 and thus MATLAB returns an empty matrix:
A = 9:1
A =
Empty matrix: 1-by-0
The next section explains how to generate a nondefault numeric series
Using the Colon Operator with a Step Value
To generate a series that does not use the default of incrementing by 1,
specify an additional value with the colon operator (first:step:last) In
between the starting and ending value is astepvalue that tells MATLAB
how much to increment (or decrement, ifstepis negative) between each
Trang 38For more information on how the colon operator works, seehttp://www.mathworks.com/support/solutions/data/1-4FLI96.html?solution=1-4FLI96.
Combining Unlike Classes
Matrices and arrays can be composed of elements of most any MATLAB datatype as long as all elements in the matrix are of the same type If you doinclude elements of unlike classes when constructing a matrix, MATLABconverts some elements so that all elements of the resulting matrix are of thesame type (See Chapter 2, “Classes (Data Types)” for information on any ofthe MATLAB classes discussed here.)
Data type conversion is done with respect to a preset precedence of classes
The following table shows the five classes you can concatenate with an unliketype without generating an error (that is, with the exception of characterand logical)
TYPE character integer single double logical character character character character character invalid
integer character integer integer integer integer
single character integer single single single
double character integer single double double
logical invalid integer single double logical
For example, concatenating adoubleandsinglematrix always yields amatrix of typesingle MATLAB converts thedoubleelement tosingletoaccomplish this
Combining Unlike Integer Types
If you combine different integer types in a matrix (e.g., signed with unsigned,
or 8-bit integers with 16-bit integers), MATLAB returns a matrix in which allelements are of one common type MATLAB sets all elements of the resultingmatrix to the data type of the left-most element in the input matrix Forexample, the result of the following concatenation is a vector of three 16-bitsigned integers:
Trang 39A = [int16(450) uint8(250) int32(1000000)]
MATLAB also displays a warning to inform you that the result may not be
what you had expected:
A = [int16(450) uint8(250) int32(1000000)];
Warning: Concatenation with dominant (left-most) integer classmay overflow other operands on conversion to return class
You can disable this warning by entering the following two commands directlyafter the operation that caused the warning The first command retrieves
the message identifier associated with the most recent warning issued by
MATLAB The second command uses this identifier to disable any further
warnings of that type from being issued:
Example of Combining Unlike Integer Sizes After disabling the integer
concatenation warnings as shown above, concatenate the following two
numbers once, and then switch their order The return value depends on the
order in which the integers are concatenated The left-most type determines
the data type for all elements in the vector:
Trang 40The first operation returns a vector of 16-bit integers The second returns avector of 8-bit integers The elementint16(5000)is set to127, the maximumvalue for an 8-bit signed integer.
The same rules apply to vertical concatenation:
C = [int8(50); int16(5000)]
C =50127
Note You can find the maximum or minimum values for any MATLAB
integer type using theintmaxandintminfunctions For floating-point types,userealmaxandrealmin
Example of Combining Signed with Unsigned Now do the same exercise
with signed and unsigned integers Again, the left-most element determinesthe data type for all elements in the resulting matrix:
A = [int8(-100) uint8(100)]
A =-100 100
B = [uint8(100) int8(-100)]
B =
100 0
The elementint8(-100)is set to zero because it is no longer signed
MATLAB evaluates each element prior to concatenating them into a combined
array In other words, the following statement evaluates to an 8-bit signedinteger (equal to 50) and an 8-bit unsigned integer (unsigned -50 is set tozero) before the two elements are combined Following the concatenation, thesecond element retains its zero value but takes on the unsignedint8type:
A = [int8(50), uint8(-50)]
A =