Matlab编程基础.pdf
http://www.100md.com
2020年11月11日
![]() |
| 第1页 |
![]() |
| 第8页 |
![]() |
| 第18页 |
![]() |
| 第28页 |
![]() |
| 第31页 |
![]() |
| 第128页 |
参见附件(2397KB,651页)。
Matlab编程基础版
Matlab:美国MathWorks公司出品的商业数学软件,用于算法开发、数据可视化、数据分析以及数值计算的高级技术计算语言和交互式环境,主要包括Matlab和Simulink两大部分Matlab应用非常之广泛,小编给大家准备了Matlab编程基础版,欢迎
相关内容部分预览







matlab编程入门的教程
Matlab:美国MathWorks公司出品的商业数学软件,用于算法开发、数据可视化、数据分析以及数值计算的高级技术计算语言和交互式环境,主要包括Matlab和Simulink两大部分Matlab应用非常之广泛
,Matlab是matrix&(取地址符)laboratory两个词的组合,意为矩阵工厂(矩阵实验室),Matlab和Mathematica、Maple并称为三大数学软件,它在数学类科技应用软件中在数值计算方面首屈一指。
对于新手入门首先要了解的是Matlab的安装及组成,理论知识,也要具有一定的编程能力,小编在自学Matlab时也是有点摸不着头脑这里我讲解下Matlab的入门,希望能给你们有点帮助。
书籍及一些命令符说明
新手我推荐看:《MATLAB语言及应用》 国防工业出版社出版 作者:原思聪
《MATLAB从零到进阶》 北京航空航天大学出版社 作者:谢中华、李国栋等
《高等应用数学问题的MATLAB求解》 清华大学出版社 作者:薛定宇、陈阳泉
《MATLAB数值计算》机械工业出版社 作者: Cleve Moler
看完这四本书我相信您已经走出新手的行列。
初学 Matlab 要如何开始?
我当时也在网上找了很久,各种教程也大概稍微看过,学了几次都没有很好学完(基础),学下来。然后遇到了这个教程
Introduction to MATLAB
我对比了其他几个教程,觉得这个教程最精髓,不会让人感觉太基础(不会在简单的问题上花费非常多的时间来讲,很多网上教程就是在简单的问题上浪费时间,搞得人非常没有耐心),而且该涉及的重要内容(都是非常常用有用的,所谓best practice)都涉及到了,最后一个章节,还延伸了下。
总得来说,这个教程把该讲的技巧都讲了,最常用的,最好用的都说了。而不像其他教程,要不就是没有选择性的把所有问题讲一遍(很多根本不好用,或者类似,但却反复讲,非常烦,浪费时间)。
学完这个教程,matlab基础就差不多了(matlab本来就不能说是一个难的东西,难的不在语言)。然后就是进入专业领域问题,学会toolbox或者后面的数学,模型之类的。
Matlab编程基础版截图




MATLAB? 7
Programming FundamentalsHow to Contact The MathWorks
www.mathworks.com Web
comp.soft-sys.matlab Newsgroup
www.mathworks.comcontact_TS.html Technical Support
suggest@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–2010 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
theuse,modification,reproduction,release,performance,display,anddisclosureoftheProgramand
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.comtrademarks 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.compatents for more information.Revision History
June 2004 First printing New for MATLAB 7.0 (Release 14)
October 2004 Online only Revised for MATLAB 7.0.1 (Release 14SP1)
March 2005 Online only Revised for MATLAB 7.0.4 (Release 14SP2)
June 2005 Second printing Minor revision for MATLAB 7.0.4
September 2005 Online only Revised for MATLAB 7.1 (Release 14SP3)
March 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)
March 2009 Online only Revised for Version 7.8 (Release 2009a)
September 2009 Online only Revised for Version 7.9 (Release 2009b)
March 2010 Online only Revised for Version 7.10 (Release 2010a)Contents
Classes (Data Types)
1
Overview of MATLAB Classes ....................... 1-2
Fundamental MATLAB Classes ...................... 1-2
HowtoUsetheDifferentClasses .................... 1-4
Numeric Classes ................................... 1-6
Overview ........................................ 1-6
Integers ......................................... 1-6
Floating-Point Numbers ............................ 1-10
Complex Numbers ................................. 1-20
Infinity and NaN .................................. 1-21
Identifying Numeric Classes ........................ 1-23
Display Format for Numeric Values .................. 1-23
Function Summary ................................ 1-25
The Logical Class .................................. 1-29
Overview of the Logical Class ....................... 1-29
Identifying Logical Arrays .......................... 1-30
Functions that Return a Logical Result ................ 1-31
Using Logical Arrays in Conditional Statements ........ 1-33
Using Logical Arrays in Indexing .................... 1-34
Characters and Strings ............................. 1-35
Creating Character Arrays .......................... 1-35
Cell Arrays of Strings .............................. 1-40
Formatting Strings ................................ 1-42
String Comparisons ............................... 1-56
Searching and Replacing ........................... 1-59
Converting from Numeric to String ................... 1-60
Converting from String to Numeric ................... 1-62
Function Summary ................................ 1-64
Structures ........................................ 1-67
What Is a Structure? ............................... 1-67
Creating a Structure ............................... 1-69
vStructure Fields .................................. 1-76
Concatenating Structures ........................... 1-79
Indexing into a Struct Array ........................ 1-80
Returning Data from a Struct Array .................. 1-82
Using Structures with Functions ..................... 1-86
Converting Between Struct Array and Cell Array ....... 1-89
Organizing Data in Structure Arrays ................. 1-91
Operator Summary ................................ 1-97
Function Summary ................................ 1-98
Cell Arrays ........................................ 1-101
What Is a Cell Array? .............................. 1-101
Cell Array Operations .............................. 1-103
Creating a Cell Array .............................. 1-103
Concatenating Cell Arrays .......................... 1-108
Indexing into a Cell Array .......................... 1-109
Assigning Values to a Cell Array ..................... 1-113
Returning Data from a Cell Array .................... 1-114
Using Cell Arrays with Functions .................... 1-118
Converting Between Cell Array and Struct Array ....... 1-121
Operator Summary ................................ 1-122
Function Summary ................................ 1-124
Function Handles .................................. 1-127
Overview ........................................ 1-127
Creating a Function Handle ......................... 1-127
Calling a Function By Means of Its Handle ............ 1-131
Preserving Data from the Workspace ................. 1-133
Applications of Function Handles .................... 1-136
Saving and Loading Function Handles ................ 1-142
Advanced Operations on Function Handles ............ 1-142
Functions That Operate on Function Handles .......... 1-148
Map Containers ................................... 1-150
Overview of the Map Data Structure .................. 1-150
Description of the Map Class ........................ 1-151
Creating a Map Object ............................. 1-153
Examining the Contents of the Map .................. 1-156
Reading and Writing Using a Key Index ............... 1-157
Modifying Keys and Values in the Map ................ 1-160
Mapping to Different Value Types .................... 1-163
vi ContentsCombining Unlike Classes .......................... 1-165
Combining Unlike Integer Types ..................... 1-166
Combining Integer and Noninteger Data .............. 1-168
Empty Matrices ................................... 1-168
Concatenation Examples ........................... 1-168
Defining Your Own Classes ......................... 1-171
Basic Program Components
2
MATLAB Commands ............................... 2-2
Basic Command Syntax ............................ 2-2
Entering More Than One Command on a Line .......... 2-3
Assigning to Multiple Outputs ....................... 2-3
Commands that Call MATLAB Functions .............. 2-5
Expressions ....................................... 2-6
String Evaluation ................................. 2-6
Shell Escape Functions ............................. 2-7
Variables ......................................... 2-8
Types of Variables ................................. 2-8
Naming Variables ................................. 2-12
Guidelines to Using Variables ....................... 2-16
Scope of a Variable ................................ 2-16
Lifetime of a Variable .............................. 2-18
Keywords ......................................... 2-19
Special Values ..................................... 2-20
Operators ......................................... 2-22
Arithmetic Operators .............................. 2-22
Relational Operators ............................... 2-23
Logical Operators ................................. 2-24
Operator Precedence ............................... 2-31
viiComma-Separated Lists ............................ 2-33
What Is a Comma-Separated List? ................... 2-33
Generating a Comma-Separated List ................. 2-33
Assigning Output from a Comma-Separated List ........ 2-35
Assigning to a Comma-Separated List ................ 2-36
How to Use the Comma-Separated Lists ............... 2-37
Fast Fourier Transform Example .................... 2-39
Program Control Statements ....................... 2-41
Conditional Control — if, switch ..................... 2-41
Loop Control — for, while, continue, break ............. 2-45
Error Control — try, catch .......................... 2-48
Program Termination — return ...................... 2-49
Dates and Times ................................... 2-50
Overview ........................................ 2-50
Types of Date Formats ............................. 2-50
Conversions Between Date Formats .................. 2-52
Date String Formats ............................... 2-53
Output Formats ................................... 2-54
Current Date and Time ............................. 2-54
Function Summary ................................ 2-55
Regular Expressions ............................... 2-57
Overview ........................................ 2-57
Calling Regular Expression Functions from MATLAB .... 2-59
Parsing Strings with Regular Expressions ............. 2-63
Other Benefits of Using Regular Expressions ........... 2-67
Metacharacters and Operators ....................... 2-68
Character Type Operators .......................... 2-69
Character Representation ........................... 2-73
Grouping Operators ............................... 2-74
Nonmatching Operators ............................ 2-76
Positional Operators ............................... 2-77
Lookaround Operators ............................. 2-78
Quantifiers ....................................... 2-84
Tokens .......................................... 2-87
Named Capture ................................... 2-92
Conditional Expressions ............................ 2-94
Dynamic Regular Expressions ....................... 2-96
String Replacement ................................ 2-105
Handling Multiple Strings .......................... 2-107
viii ContentsFunction, Mode Options, Operator, Return Value
Summaries .................................... 2-110
Symbol Reference ................................. 2-119
Asterisk — ..................................... 2-120
At — @ .......................................... 2-120
Colon — : ........................................ 2-121
Comma — , ...................................... 2-122
Curly Braces — { } ................................. 2-123
Dot — . .......................................... 2-123
Dot-Dot — .. ...................................... 2-124
Dot-Dot-Dot (Ellipsis) — ... .......................... 2-124
Dot-Parentheses — .( ) ............................. 2-126
Exclamation Point — ! ............................. 2-126
Parentheses — ( ) ................................. 2-126
Percent — % ..................................... 2-127
Percent-Brace — %{ %} ............................. 2-128
Plus — + ......................................... 2-128
Semicolon — ; .................................... 2-128
Single Quotes — ................................. 2-129
Space Character .................................. 2-130
Slash and Backslash — \ .......................... 2-130
Square Brackets — [ ] .............................. 2-131
Tilde — ~ ........................................ 2-131
Functions and Scripts
3
Program Development ............................. 3-2
Overview ........................................ 3-2
Creating a Program ................................ 3-2
Getting the Bugs Out .............................. 3-4
Cleaning Up the Program ........................... 3-5
Improving Performance ............................ 3-5
Checking It In .................................... 3-6
Protecting Your Source Code ........................ 3-6
Working with Functions in Files .................... 3-9
Overview ........................................ 3-9
Types of Program Files ............................. 3-9
ixBasic Parts of a Program File ........................ 3-10
Creating a Program File ............................ 3-15
Providing Help for Your Program .................... 3-18
CleaningUptheFileWhenDone ..................... 3-18
Scripts and Functions .............................. 3-21
Scripts .......................................... 3-21
Functions ........................................ 3-22
Types of Functions ................................ 3-23
Organizing Your Functions ......................... 3-24
Identifying Dependencies ........................... 3-25
Calling Functions .................................. 3-27
Command vs. Function Syntax ...................... 3-27
What Happens When You Call a Function ............. 3-36
Determining Which Function Gets Called .............. 3-36
Calling External Functions ......................... 3-40
Running External Programs ........................ 3-40
Function Arguments ............................... 3-41
Overview ........................................ 3-41
Input Arguments .................................. 3-41
Output Arguments ................................ 3-43
Passing Arguments in Structures or Cell Arrays ........ 3-46
Passing Optional Arguments ........................ 3-48
Validating Inputs with Input Parser ................. 3-60
What Is the Input Parser? .......................... 3-60
Working with the Example Function .................. 3-61
The inputParser Class ............................. 3-62
Validating Data Passed to a Function ................. 3-63
Substituting Default Values for Arguments Not Passed .. 3-70
Handling Unmatched Inputs ........................ 3-71
Interpreting Arguments Passed as Structures .......... 3-72
Other Features of the Input Parser ................... 3-75
Summary of inputParser Methods and Properties ....... 3-78
Functions Provided By MATLAB .................... 3-81
Overview ........................................ 3-81
Functions ........................................ 3-81
Built-In Functions ................................. 3-82
Overloaded MATLAB Functions ..................... 3-83
x ContentsInternal Utility Functions .......................... 3-84
Types of Functions
4
Overview of MATLAB Function Types ............... 4-2
Anonymous Functions ............................. 4-3
Constructing an Anonymous Function ................ 4-3
Arrays of Anonymous Functions ..................... 4-6
Outputs from Anonymous Functions .................. 4-7
Variables Used in the Expression .................... 4-8
Examples of Anonymous Functions ................... 4-11
Primary Functions ................................. 4-15
Nested Functions .................................. 4-16
Writing Nested Functions ........................... 4-16
Calling Nested Functions ........................... 4-18
Variable Scope in Nested Functions .................. 4-19
Using Function Handles with Nested Functions ........ 4-21
Restrictions on Assigning to Variables ................ 4-26
Examples of Nested Functions ....................... 4-27
Subfunctions ...................................... 4-33
Overview ........................................ 4-33
Calling Subfunctions ............................... 4-34
Accessing Help for a Subfunction ..................... 4-34
Private Functions ................................. 4-35
Overview ........................................ 4-35
Private Folders ................................... 4-35
Accessing Help for a Private Function ................. 4-36
Overloaded Functions .............................. 4-37
xiUsing Objects
5
MATLAB Objects .................................. 5-2
Getting Oriented .................................. 5-2
Getting Comfortable with Objects .................... 5-2
What Are Objects and Why Use Them? ................ 5-2
Accessing Objects ................................. 5-3
Objects In the MATLAB Language ................... 5-4
Other Kinds of Objects Used by MATLAB ............. 5-4
General Purpose Vs. Specialized Arrays ............. 5-5
How They Differ .................................. 5-5
Using General-Purpose Data Structures ............... 5-5
Using Specialized Objects ........................... 5-6
Key Object Concepts ............................... 5-8
Basic Concepts .................................... 5-8
Classes Describe How to Create Objects ............... 5-8
Properties Contain Data ............................ 5-8
Methods Implement Operations ...................... 5-9
Creating Objects ................................... 5-11
Class Constructor ................................. 5-11
When to Use Package Names ........................ 5-11
Accessing Object Data ............................. 5-14
Listing Public Properties ........................... 5-14
Getting Property Values ............................ 5-14
Setting Property Values ............................ 5-15
Calling Object Methods ............................ 5-16
What Operations Can You Perform ................... 5-16
Method Syntax ................................... 5-16
Class of Objects Returned by Methods ................ 5-18
Desktop Tools Are Object Aware .................... 5-19
Tab Completion Works with Objects .................. 5-19
Editing Objects with the Variable Editor .............. 5-19
xii ContentsGetting Information About Objects .................. 5-21
The Class of Workspace Variables .................... 5-21
Information About Class Members ................... 5-23
Logical Tests for Objects ............................ 5-23
Displaying Objects ................................ 5-24
Getting Help for MATLAB Objects ................... 5-25
Copying Objects ................................... 5-26
Two Copy Behaviors ............................... 5-26
Value Object Copy Behavior ......................... 5-26
Handle Object Copy Behavior ....................... 5-27
Testing for Handle or Value Class .................... 5-30
Destroying Objects ................................ 5-31
Object Lifecycle ................................... 5-31
Difference Between clear and delete .................. 5-31
Error Handling
6
Error Reporting in a MATLAB Application ........... 6-2
Overview ........................................ 6-2
Getting an Exception at the Command Line ............ 6-2
GettinganExceptioninYourProgramCode ........... 6-3
Generating a New Exception ........................ 6-4
Capturing Information About the Error ............. 6-5
Overview ........................................ 6-5
The MException Class ............................. 6-5
Properties of the MException Class ................... 6-7
Methods of the MException Class .................... 6-14
Throwing an Exception ............................ 6-16
Responding to an Exception ........................ 6-17
Overview ........................................ 6-17
The try-catch Statement ............................ 6-17
Suggestions on How to Handle an Exception ........... 6-19
xiiiWarnings ......................................... 6-22
Reporting a Warning ............................... 6-22
Identifying the Cause .............................. 6-23
Warning Control ................................... 6-24
Overview ........................................ 6-24
Warning Statements ............................... 6-25
Warning Control Statements ........................ 6-26
Output from Control Statements ..................... 6-28
Saving and Restoring State ......................... 6-31
Backtrace and Verbose Modes ....................... 6-32
Debugging Errors and Warnings .................... 6-35
Program Scheduling
7
Using a MATLAB Timer Object ..................... 7-2
Overview ........................................ 7-2
Example: Displaying a Message ..................... 7-3
Creating Timer Objects ............................ 7-5
Creating the Object ................................ 7-5
Naming the Object ................................ 7-6
Working with Timer Object Properties .............. 7-7
Retrieving the Value of Timer Object Properties ........ 7-7
Setting the Value of Timer Object Properties ........... 7-8
Starting and Stopping Timers ...................... 7-10
Starting a Timer .................................. 7-10
Starting a Timer at a Specified Time .................. 7-10
Stopping Timer Objects ............................ 7-11
Blocking the MATLAB Command Line ................ 7-12
Creating and Executing Callback Functions ......... 7-14
Associating Commands with Timer Object Events ....... 7-14
Creating Callback Functions ........................ 7-15
xiv ContentsSpecifying the Value of Callback Function Properties .... 7-17
Timer Object Execution Modes ..................... 7-19
Executing a Timer Callback Function Once ............ 7-19
Executing a Timer Callback Function Multiple Times .... 7-20
Handling Callback Function Queuing Conflicts ......... 7-21
Deleting Timer Objects from Memory ............... 7-23
Deleting One or More Timer Objects .................. 7-23
Testing the Validity of a Timer Object ................. 7-23
Finding Timer Objects in Memory ................... 7-24
Finding All Timer Objects .......................... 7-24
Finding Invisible Timer Objects ...................... 7-24
Performance
8
Analyzing Your Program’s Performance ............. 8-2
Overview ........................................ 8-2
The Profiler Utility ................................ 8-2
Stopwatch Timer Functions ......................... 8-2
Techniques for Improving Performance ............. 8-4
Preallocating Arrays ............................... 8-4
Use Distributed Arrays for Large Datasets ............. 8-5
When Possible, Replace for with parfor (Parallel for) ..... 8-6
Limiting Size and Complexity ....................... 8-6
Assigning to Variables ............................. 8-6
Using Appropriate Logical Operators ................. 8-7
Overloading Built-In Functions ...................... 8-8
Functions Are Generally Faster Than Scripts .......... 8-8
Load and Save Are Faster Than File IO Functions ...... 8-8
Vectorizing Loops ................................. 8-8
Avoid Large Background Processes ................... 8-11
xvMemory Usage
9
Memory Allocation ................................. 9-2
Memory Allocation for Arrays ....................... 9-2
Data Structures and Memory ........................ 9-7
Memory Management Functions .................... 9-12
The whos Function ................................ 9-13
Strategies for Efficient Use of Memory .............. 9-15
Ways to Reduce the Amount of Memory Required ....... 9-15
Using Appropriate Data Storage ..................... 9-17
How to Avoid Fragmenting Memory .................. 9-20
Reclaiming Used Memory ........................... 9-22
Resolving “Out of Memory” Errors .................. 9-23
General Suggestions for Reclaiming Memory ........... 9-23
Setting the Process Limit ........................... 9-24
Disabling Java VM on Startup ...................... 9-25
Increasing System Swap Space ...................... 9-26
Using the 3GB Switch on Windows Systems ............ 9-27
Freeing Up System Resources on Windows Systems ..... 9-27
Programming Tips
10
Introduction ...................................... 10-2
Command and Function Syntax ..................... 10-3
Syntax Help ...................................... 10-3
Command and Function Syntaxes .................... 10-3
Command Line Continuation ........................ 10-3
Completing Commands Using the Tab Key ............. 10-4
Recalling Commands .............................. 10-4
Clearing Commands ............................... 10-5
Suppressing Output to the Screen .................... 10-5
xvi ContentsHelp .............................................. 10-6
Using the Help Browser ............................ 10-6
Help on Functions from the Help Browser ............. 10-6
Help on Functions from the Command Window ......... 10-7
Topical Help ...................................... 10-7
Paged Output .................................... 10-8
Writing Your Own Help ............................ 10-8
Help for Subfunctions and Private Functions ........... 10-9
Help for Methods and Overloaded Functions ........... 10-9
Development Environment ......................... 10-10
Workspace Browser ................................ 10-10
Using the Find and Replace Utility ................... 10-10
Commenting Out a Block of Code .................... 10-11
Creating Functions from Command History ............ 10-11
Editing Functions in EMACS ........................ 10-11
Functions ......................................... 10-12
Function Structure ................................ 10-12
Using Lowercase for Function Names ................. 10-12
Getting a Function’s Name and Path .................. 10-13
What Files Does a Function Use? .................... 10-13
Dependent Functions, Built-Ins, Classes ............... 10-14
Function Arguments ............................... 10-15
Getting the Input and Output Arguments ............. 10-15
Variable Numbers of Arguments ..................... 10-15
String or Numeric Arguments ....................... 10-16
Passing Arguments in a Structure .................... 10-16
Passing Arguments in a Cell Array ................... 10-17
Program Development ............................. 10-18
Planning the Program .............................. 10-18
Using Pseudo-Code ................................ 10-18
Selecting the Right Data Structures .................. 10-18
General Coding Practices ........................... 10-19
Naming a Function Uniquely ........................ 10-19
The Importance of Comments ....................... 10-19
Coding in Steps ................................... 10-20
Making Modifications in Steps ....................... 10-20
Functions with One Calling Function ................. 10-20
Testing the Final Program .......................... 10-20
xviiDebugging ........................................ 10-21
The MATLAB Debug Functions ...................... 10-21
More Debug Functions ............................. 10-21
The MATLAB Graphical Debugger ................... 10-22
A Quick Way to Examine Variables ................... 10-22
Setting Breakpoints from the Command Line .......... 10-22
Finding Line Numbers to Set Breakpoints ............. 10-23
Stopping Execution on an Error or Warning ............ 10-23
Locating an Error from the Error Message ............. 10-23
Using Warnings to Help Debug ...................... 10-24
Making Code Execution Visible ...................... 10-24
Debugging Scripts ................................. 10-24
Variables ......................................... 10-25
Rules for Variable Names ........................... 10-25
Making Sure Variable Names Are Valid ............... 10-25
Do Not Use Function Names for Variables ............. 10-26
Checking for Reserved Keywords ..................... 10-26
Avoid Using i and j for Variables ..................... 10-27
Avoid Overwriting Variables in Scripts ................ 10-27
Persistent Variables ............................... 10-27
Protecting Persistent Variables ...................... 10-27
Global Variables .................................. 10-28
Strings ........................................... 10-29
Creating Strings with Concatenation ................. 10-29
Comparing Methods of Concatenation ................. 10-29
Store Arrays of Strings in a Cell Array ................ 10-30
Converting Between Strings and Cell Arrays ........... 10-30
Search and Replace Using Regular Expressions ......... 10-30
Evaluating Expressions ............................ 10-32
Find Alternatives to Using eval ...................... 10-32
Assigning to a Series of Variables .................... 10-32
Short-Circuit Logical Operators ...................... 10-33
Changing the Counter Variable within a for Loop ....... 10-33
MATLAB Path ..................................... 10-34
Precedence Rules .................................. 10-34
File Precedence ................................... 10-35
Adding a Folder to the Search Path ................... 10-35
Handles to Functions Not on the Path ................. 10-35
xviii ContentsMaking Toolbox File Changes Visible to MATLAB ....... 10-36
Making Nontoolbox File Changes Visible to MATLAB .... 10-37
Change Notification on Windows ..................... 10-37
Program Control .................................. 10-38
Using break, continue, and return .................... 10-38
Using switch Versus if ............................. 10-39
MATLAB case Evaluates Strings ..................... 10-39
Multiple Conditions in a case Statement ............... 10-39
Implicit Break in switch-case ........................ 10-39
Variable Scope in a switch .......................... 10-40
Catching Errors with try-catch ...................... 10-40
Nested try-catch Blocks ............................ 10-41
Forcing an Early Return from a Function .............. 10-41
Save and Load ..................................... 10-42
Saving Data from the Workspace ..................... 10-42
Loading Data into the Workspace .................... 10-42
Viewing Variables in a MAT-File ..................... 10-43
Appending to a MAT-File ........................... 10-43
SaveandLoadonStartuporQuit .................... 10-44
Saving to an ASCII File ............................ 10-44
Files and Filenames ................................ 10-45
Naming Functions ................................. 10-45
Naming Other Files ............................... 10-45
Passing Filenames as Arguments .................... 10-46
Passing Filenames to ASCII Files .................... 10-46
Determining Filenames at Run-Time ................. 10-46
Returning the Size of a File ......................... 10-46
InputOutput ...................................... 10-48
File IO Function Overview ......................... 10-48
Common IO Functions ............................. 10-48
Readable File Formats ............................. 10-48
Using the Import Wizard ........................... 10-49
Loading Mixed Format Data ........................ 10-49
Reading Files with Different Formats ................. 10-49
Interactive Input into Your Program .................. 10-50
Starting MATLAB .................................. 10-51
Getting MATLAB to Start Up Faster ................. 10-51
xixOperating System Compatibility .................... 10-52
Executing OS Commands from MATLAB ............. 10-52
Searching Text with grep ........................... 10-52
Constructing Paths and Filenames ................... 10-52
Finding the MATLAB Root Folder .................... 10-53
Temporary Directories and Filenames ................ 10-53
Demos ............................................ 10-54
Demos Available with MATLAB ..................... 10-54
For More Information .............................. 10-55
Current CSSM .................................... 10-55
Archived CSSM ................................... 10-55
MATLAB Technical Support ........................ 10-55
Tech Notes ....................................... 10-55
MATLAB Central ................................. 10-55
MATLAB Newsletters (Digest, News Notes) .......... 10-55
MATLAB Documentation ........................... 10-56
MATLAB Index of Examples ........................ 10-56
Index
xx Contents1
Classes (Data Types)
· “Overview of MATLAB Classes” on page 1-2
· “Numeric Classes” on page 1-6
· “The Logical Class” on page 1-29
· “Characters and Strings” on page 1-35
· “Structures” on page 1-67
· “Cell Arrays” on page 1-101
· “Function Handles” on page 1-127
· “Map Containers” on page 1-150
· “Combining Unlike Classes” on page 1-165
· “Defining Your Own Classes” on page 1-1711 Classes (Data Types)
Overview of MATLAB Classes
In this section...
“Fundamental MATLAB Classes” on page 1-2
“How to Use the Different Classes” on page 1-4
Fundamental MATLAB Classes
There are many different data types, or classes,thatyoucanworkwithinthe
MATLAB? software. You can build matrices and arrays of floating-point
and integer data, characters and strings, and logical true and false states.
Function handles connect your code with any MATLAB function regardless
of the current scope. Structures and cell arrays, provide a way to store
dissimilar types of data in the same array.
There are 15 fundamental classes in MATLAB. Each of these classes is in the
form of a matrix or array. This matrix or array is a minimum of 0-by-0 in size
and can grow to an n-dimensional array of any size.
All of the fundamental MATLAB classes are circled in the diagram below:
1-2Overview of MATLAB? Classes
Numeric classes in the MATLAB software include signed and unsigned
integers, and single- and double-precision floating-point numbers. By
default, MATLAB stores all numeric values as double-precision floating
point. (You cannot change the default type and precision.) You can choose
to store any number, or array of numbers, as integers or as single-precision.
Integer and single-precision arrays offer more memory-efficient storage than
double-precision.
All numeric types support basic array operations, such as subscripting and
reshaping. All numeric types except for int64 and uint64 can be used in
mathematical operations.
You can create two-dimensional double and logical matrices using one of
two storage formats: full or sparse. For matrices with mostly zero-valued
elements, a sparse matrix requires a fraction of the storage space required
1-31 Classes (Data Types)
for an equivalent full matrix. Sparse matrices invoke methods especially
tailored to solve sparse problems
Theseclassesrequiredifferentamounts of storage, the smallest being a
logical value or 8–bit integer which requires only 1 byte. It is important to
keep this minimum size in mind if you work on data in files that were written
using a precision smaller than 8 bits.
How to Use the Different Classes
The following table describes these classes in more detail.
Class Name Documentation Intended Use
double, single Floating-Point
Numbers
· Required for fractional numeric data.
· Double and Single precision.
· Use realmin and realmax to show range of values.
· Two-dimensional arrays can be sparse.
· Default numeric type in MATLAB.
int8, uint8,int16,uint16,int32,uint32,int64, uint64
Integers ? Use for signed and unsigned whole numbers.
· More efficient use of memory.
· Use intmin and intmax to show range of values.
· Choose from 4 sizes (8, 16, 32, and 64 bits).
· Use all but 64-bit in mathematics operations.
char “Characters and
Strings” on page
1-35
· Required for text.
· Native or unicode.
· Converts tofrom numeric.
· Use with regular expressions.
· For multiple strings, use cell arrays.
1-4Overview of MATLAB? Classes
Class Name Documentation Intended Use
logical Logical Class ? Use in relational conditions or to test state.
· Can have one of two values: true or false.
· Also useful in array indexing.
· Two-dimensional arrays can be sparse.
function_handle “Function
Handles” on page
1-127
· Pointer to a function.
· Enables passing a function to another function
· Can also call functions outside usual scope.
· Useful in Handle Graphics callbacks.
· Save to MAT-file and restore later.
struct Structures ? Fields store arrays of varying classes and sizes.
· Access multiple fieldsindices in single operation.
· Field names identify contents.
· Simple method of passing function arguments.
· Use in comma-separated lists for efficiency.
· More memory required for overhead
cell Cell Arrays ? Cells store arrays of varying classes and sizes.
· Allows freedom to package data as you want.
· Manipulation of elements is similar to arrays.
· Simple method of passing function arguments.
· Use in comma-separated lists for efficiency.
· More memory required for overhead
1-51 Classes (Data Types)
Numeric Classes
In this section...
“Overview” on page 1-6
“Integers” on page 1-6
“Floating-Point Numbers” on page 1-10
“Complex Numbers” on page 1-20
“Infinity and NaN” on page 1-21
“Identifying Numeric Classes” on page 1-23
“Display Format for Numeric Values” on page 1-23
“Function Summary” on page 1-25
Overview
Numeric classes in the MATLAB software include signed and unsigned
integers, and single- and double-precision floating-point numbers. By
default, MATLAB stores all numeric values as double-precision floating
point. (You cannot change the default type and precision.) You can choose
to store any number, or array of numbers, as integers or as single-precision.
Integer and single-precision arrays offer more memory-efficient storage than
double-precision.
All numeric types support basic array operations, such as subscripting and
reshaping. All numeric types except for int64 and uint64 can be used in
mathematical operations.
Integers
MATLAB has four signed and four unsigned integer classes. Signed types
enable you to work with negative integers as well as positive, but cannot
represent as wide a range of numbers as the unsigned types because one bit
is used to designate a positive or negative sign for the number. Unsigned
types give you a wider range of numbers, but these numbers can only be
zero or positive.
This section covers:
1-6Numeric Classes
· “Creating Integer Data” on page 1-7
· “Arithmetic Operations on Integer Classes” on page 1-9
· “Largest and Smallest Values for Integer Classes” on page 1-9
· “Integer Functions” on page 1-10
MATLAB supports 1-, 2-, 4-, and 8-byte storage for integer data. You can
save memory and execution time for your programs if you use the smallest
integer type that accommodates your data. For example, you do not need a
32-bit integer to store the value 100.
Here are the eight integer classes, the range of values you can store with each
type, and the MATLAB conversion function required to create that type:
Class Range of Values Conversion Function
Signed 8-bit integer -27 to 27-1 int8
Signed 16-bit integer -215 to 215-1 int16
Signed 32-bit integer -231 to 231-1 int32
Signed 64-bit integer -263 to 263-1 int64
Unsigned 8-bit integer 0to28-1 uint8
Unsigned 16-bit integer 0to216-1 uint16
Unsigned 32-bit integer 0to232-1 uint32
Unsigned 64-bit integer 0to264-1 uint64
Creating Integer Data
MATLAB stores numeric data as double-precision floating point (double)
by default. To store data as an integer, you need to convert from double to
the desired integer type. Use one of the conversion functions shown in the
table above.
For example, to store 325 as a 16-bit signed integer assigned to variable x,type
x = int16(325);
1-71 Classes (Data Types)
If the number being converted to an integer has a fractional part, MATLAB
rounds to the nearest integer. If the fractional part is exactly 0.5,thenfrom
the two equally nearby integers, MATLAB chooses the one for which the
absolute value is larger in magnitude:
x = 325.499; x = x + .001;
int16(x) int16(x)
ans = ans =
325 326
If you need to round a number using a rounding scheme other than the
default, MATLAB provides four rounding functions: round, fix, floor,and
ceil. In this example, the fix function enables you to override the default
and round towards zero when the fractional part of a number is .5:
x = 325.5;
int16(fix(x))
ans =
325
Arithmetic operations that involve both integers and floating-point always
result in an integer data type. MATLAB rounds the result, when necessary,according to the default rounding algorithm. The example below yields an
exact answer of 1426.75 which MATLAB then rounds to the next highest
integer:
int16(325) 4.39
ans =
1427
The integer conversion functions are also useful when converting other
classes, such as strings, to integers:
str = 'Hello World';
int8(str)
ans =
72 101 108 108 111 32 87 111 114 108 100
1-8Numeric Classes
Arithmetic Operations on Integer Classes
MATLAB can perform integer arithmetic on the following types of data:
· Integers or integer arrays of the same integer data type. This yields a
result that has the same data type as the operands:
x = uint32([132 347 528]) . uint32(75);
· Integers or integer arrays and scalar double-precision floating-point
numbers. This yields a result that has the same data type as the integer
operands:
x = uint32([132 347 528]) . 75.49;
For all binary operations in which one operand is an array of integer data
type and the other is a scalar double, MATLAB computes the operation using
elementwise double-precision arithmetic, and then converts the result back to
the original integer data type.
For a list of the operations that support integer classes, see Nondouble Data
Type Support in the arithmetic operators reference page.
Largest and Smallest Values for Integer Classes
For each integer data type, there is a largest and smallest number that you
can represent with that type. The table shown under “Integers” on page 1-6
lists the largest and smallest values for each integer data type in the “Range
of Values” column.
You can also obtain these values with the intmax and intmin functions:
intmax('int8') intmin('int8')
ans = ans =
127 -128
If you convert a number that is larger than the maximum value of an integer
data type to that type, MATLAB sets it to the maximum value. Similarly, if
you convert a number that is smaller than the minimum value of the integer
data type, MATLAB sets it to the minimum value. For example,x = int8(300) x = int8(-300)
1-91 Classes (Data Types)
x= x=
127 -128
Also, when the result of an arithmetic operation involving integers exceeds
the maximum (or minimum) value of the data type, MATLAB sets it to the
maximum (or minimum) value:
x = int8(100) 3 x = int8(-100) 3
x= x=
127 -128
You can make MATLAB return a warning when your input is outside the
range an integer data type. This is described in the next section.
Integer Functions
See Integer Functions on page 1-26 for a list of functions most commonly used
with integers in MATLAB.
Floating-Point Numbers
MATLAB represents floating-point numbers in either double-precision or
single-precision format. The default is double precision, but you can make
any number single precision with a simple conversion function.
This section covers:
· “Double-Precision Floating Point” on page 1-11
· “Single-Precision Floating Point” on page 1-11
· “Creating Floating-Point Data” on page 1-11
· “Arithmetic Operations on Floating-Point Numbers” on page 1-13
· “Largest and Smallest Values for Floating-Point Classes” on page 1-14
· “Accuracy of Floating-Point Data” on page 1-15
· “Avoiding Common Problems with Floating-Point Arithmetic” on page 1-17
· “Floating-Point Functions” on page 1-19
· “References” on page 1-19
1-10Numeric Classes
Double-Precision Floating Point
MATLAB constructs the double-precision (or double) data type according
to IEEE? Standard 754 for double precision. Any value stored as a double
requires 64 bits, formatted as shown in the table below:
Bits Usage
63 Sign (0 =positive, 1 =negative)
62 to 52 Exponent, biased by 1023
51 to 0 Fraction f of the number 1.f
Single-Precision Floating Point
MATLAB constructs the single-precision (or single) data type according
to IEEE Standard 754 for single precision. Any value stored as a single
requires 32 bits, formatted as shown in the table below:
Bits Usage
31 Sign (0 =positive, 1 =negative)
30 to 23 Exponent, biased by 127
22 to 0 Fraction f of the number 1.f
Because MATLAB stores numbers of type single using 32 bits, they require
less memory than numbers of type double, which use 64 bits. However,because they are stored with fewer bits, numbers of type single are
represented to less precision than numbers of type double.
Creating Floating-Point Data
Use double-precision to store values greater than approximately 3.4 x 1038
or less than approximately -3.4 x 1038. For numbers that lie between these
two limits, you can use either double- or single-precision, but single requires
less memory.
Creating Double-Precision Data. Because the default numeric type
for MATLAB is double, you can create a double with a simple assignment
statement:
1-111 Classes (Data Types)
x = 25.783;
The whos function shows that MATLAB has created a 1-by-1 array of type
double for the value you just stored in x:
whos x
Name Size Bytes Class
x 1x1 8 double
Use isfloat ifyoujustwanttoverifythat x is a floating-point number. This
function returns logical 1 (true) if the input is a floating-point number, and
logical 0 (false)otherwise:
isfloat(x)
ans =
1
You can convert other numeric data, characters or strings, and logical data to
double precision using the MATLAB function, double. This example converts
a signed integer to double-precision floating point:
y = int64(-589324077574); % Create a 64-bit integer
x = double(y) % Convert to double
x=
-5.8932e+011
Creating Single-Precision Data. Because MATLAB stores numeric data as
a double by default, you need to use the single conversion function to create
a single-precision number:
x = single(25.783);
The whos function returns the attributes of variable x in a structure. The
bytes field of this structure shows that when x is stored as a single, it requires
just 4 bytes compared with the 8 bytes to store it as a double:
xAttrib = whos('x');
xAttrib.bytes
ans =
1-12Numeric Classes
4
You can convert other numeric data, characters or strings, and logical data to
single precision using the single function. This example converts a signed
integer to single-precision floating point:
y = int64(-589324077574); % Create a 64-bit integer
x = single(y) % Convert to single
x=
-5.8932e+011
Arithmetic Operations on Floating-Point Numbers
This section describes which classes you can use in arithmetic operations
with floating-point numbers.
Double-Precision Operations. You can perform basic arithmetic operations
with double and any of the following other classes. When one or more
operands is an integer (scalar or array), the double operand must be a scalar.
The result is of type double, except where noted otherwise:
· single — The result is of type single
· double
· int or uint — The result has the same data type as the integer operand
· char
· logical
This example performs arithmetic on data of types char and double.The
result is of type double:
c = 'uppercase' - 32;
class(c)
ans =
double
char(c)
1-131 Classes (Data Types)
ans =
UPPERCASE
Single-Precision Operations. You can perform basic arithmetic operations
with single and any of the following other classes. The result is always
single:
· single
· double
· char
· logical
In this example, 7.5 defaults to type double,andtheresultisoftype single:
x = single([1.32 3.47 5.28]) . 7.5;
class(x)
ans =
single
Largest and Smallest Values for Floating-Point Classes
For the double and single classes, there is a largest and smallest number
that you can represent with that type.
Largest and Smallest Double-Precision Values. The MATLAB functions
realmax and realmin return the maximum and minimum values that you
can represent with the double data type:
str = 'The range for double is:\n\t%g to %g and\n\t %g to %g';
sprintf(str, -realmax, -realmin, realmin, realmax)
ans =
The range for double is:
-1.79769e+308 to -2.22507e-308 and
2.22507e-308 to 1.79769e+308
1-14Numeric Classes
Numbers larger than realmax or smaller than -realmax are assigned the
values of positive and negative infinity, respectively:
realmax + .0001e+308
ans =
Inf
-realmax - .0001e+308
ans =
-Inf
Largest and Smallest Single-Precision Values. The MATLAB functions
realmax and realmin, when called with the argument 'single',returnthe
maximum and minimum values that you can represent with the single data
type:
str = 'The range for single is:\n\t%g to %g and\n\t %g to %g';
sprintf(str, -realmax('single'), -realmin('single'), ...
realmin('single'), realmax('single'))
ans =
The range for single is:
-3.40282e+038 to -1.17549e-038 and
1.17549e-038 to 3.40282e+038
Numbers larger than realmax(’single’) or smaller than -realmax (’single’) are
assigned the values of positive and negative infinity, respectively:
realmax('single') + .0001e+038
ans =
Inf
-realmax('single') - .0001e+038
ans =
-Inf
Accuracy of Floating-Point Data
If the result of a floating-point arithmetic computation is not as precise as
you had expected, it is likely caused by the limitations of your computer’s
1-151 Classes (Data Types)
hardware. Probably, your result was a little less exact because the hardware
had insufficient bits to represent the result with perfect accuracy; therefore, it
truncated the resulting value.
Double-Precision Accuracy. Because there are only a finite number
of double-precision numbers, you cannot represent all numbers in
double-precision storage. On any computer, there is a small gap between each
double-precision number and the next larger double-precision number. You
can determine the size of this gap, which limits the precision of your results,using the eps function. For example, to find the distance between 5 and the
next larger double-precision number, enter
format long
eps(5)
ans =
8.881784197001252e-016
This tells you that there are no double-precision numbers between 5 and
5 + eps(5). If a double-precision computation returns the answer 5, the
result is only accurate to within eps(5).
The value of eps(x) depends on x.Thisexampleshowsthat,as x gets larger,so does eps(x):
eps(50)
ans =
7.105427357601002e-015
If you enter eps with no input argument, MATLAB returns the value of
eps(1),thedistancefrom 1 to the next larger double-precision number.
Single-Precision Accuracy. Similarly, there are gaps between any two
single-precision numbers. If x has type single, eps(x) returns the distance
between x and the next larger single-precision number. For example,x = single(5);
eps(x)
returns
1-16Numeric Classes
ans =
4.7684e-007
Note that this result is larger than eps(5). Because there are fewer
single-precision numbers than double-precision numbers, the gaps
between the single-precision numbers are larger than the gaps between
double-precision numbers. This means that results in single-precision
arithmetic are less precise than in double-precision arithmetic.
For a number x of type double, eps(single(x)) gives you an upper bound
for the amount that x is rounded when you convert it from double to single.
For example, when you convert the double-precision number 3.14 to single,it is rounded by
double(single(3.14) - 3.14)
ans =
1.0490e-007
The amount that 3.14 is rounded is less than
eps(single(3.14))
ans =
2.3842e-007
Avoiding Common Problems with Floating-Point Arithmetic
Almost all operations in MATLAB are performed in double-precision
arithmetic conforming to the IEEE standard 754. Because computers only
represent numbers to a finite precision (double precision calls for 52 mantissa
bits), computations sometimes yield mathematically nonintuitive results. It is
important to note that these results are not bugs in MATLAB.
Use the following examples to help you identify these cases:
Example 1 — Round-Off or What You Get Is Not What You Expect.
The decimal number 43 is not exactly representable as a binary fraction. For
this reason, the following calculation does not give zero, but rather reveals
the quantity eps.
e = 1 - 3(43 - 1)
1-171 Classes (Data Types)
e=
2.2204e-016
Similarly, 0.1 is not exactly representable as a binary number. Thus, you get
the following nonintuitive behavior:
a = 0.0;
for i = 1:10
a = a + 0.1;
end
a==1
ans =
0
Note that the order of operations can matter in the computation:
b = 1e-16 + 1 - 1e-16;
c = 1e-16 - 1e-16 + 1;
b==c
ans =
0
There are gaps between floating-point numbers. As the numbers get larger,so do the gaps, as evidenced by:
(2^53 + 1) - 2^53
ans =
0
Since pi is not really pi, it is not surprising that sin(pi) is not exactly zero:
sin(pi)
ans =
1.224646799147353e-016
1-18Numeric Classes
Example 2 — Catastrophic Cancellation. When subtractions are
performed with nearly equal operands, sometimes cancellation can occur
unexpectedly. The following is an example of a cancellation caused by
swamping (loss of precision that makes the addition insignificant).
sqrt(1e-16 + 1) - 1
ans =
0
Some functions in MATLAB, such as expm1 and log1p, may be used to
compensate for the effects of catastrophic cancellation.
Example 3 — Floating-Point Operations and Linear Algebra.
Round-off, cancellation, and other traits of floating-point arithmetic combine
to produce startling computations when solving the problems of linear
algebra. MATLAB warns that the following matrix A is ill-conditioned, and
therefore the system Ax = b may be sensitive to small perturbations:
A = diag([2 eps]);
b = [2; eps];
y = A\b;
Warning: Matrix is close to singular or badly scaled.
Results may be inaccurate. RCOND = 1.110223e-016.
These are only a few of the examples showing how IEEE floating-point
arithmetic affects computations in MATLAB. Note that all computations
performed in IEEE 754 arithmetic are affected, this includes applications
written in C or FORTRAN, as well as MATLAB. For more examples
and information, see Technical Note 1108 Common Problems with
Floating-Point Arithmetic.
Floating-Point Functions
See Floating-Point Functions on page 1-26 for a list of functions most
commonly used with floating-point numbers in MATLAB.
References
The following references provide more information about floating-point
arithmetic.
1-191 Classes (Data Types)
[1] Moler, Cleve, “Floating Points,” MATLAB News and Notes,Fall,1996. A PDF version is available on the MathWorks Web site at
http:www.mathworks.comcompanynewslettersnews_notespdfFall96Cleve.pdf
[2] Moler, Cleve, Numerical Computing with MATLAB, S.I.A.M.
A PDF version is available on the MathWorks Web site at
http:www.mathworks.commoler.
Complex Numbers
Complex numbers consist of two separate parts: a real part and an imaginary
part. The basic imaginary unit is equal to the square root of -1.Thisis
represented in MATLAB by either of two letters: i or j.
Creating Complex Numbers
The following statement shows one way of creating a complex value in
MATLAB. The variable x is assigned a complex number with a real part of 2
and an imaginary part of 3:
x=2+3i;
Another way to create a complex number is using the complex function. This
function combines two numeric inputs into a complex output, making the first
input real and the second imaginary:
x = rand(3) 5;
y = rand(3) -8;
z = complex(x, y)
z=
4.7842 -1.0921i 0.8648 -1.5931i 1.2616 -2.2753i
2.6130 -0.0941i 4.8987 -2.3898i 4.3787 -3.7538i
4.4007 -7.1512i 1.3572 -5.2915i 3.6865 -0.5182i
You can separate a complex number into its real and imaginary parts using
the real and imag functions:
zr = real(z)
zr =
4.7842 0.8648 1.2616
1-20Numeric Classes
2.6130 4.8987 4.3787
4.4007 1.3572 3.6865
zi = imag(z)
zi =
-1.0921 -1.5931 -2.2753
-0.0941 -2.3898 -3.7538
-7.1512 -5.2915 -0.5182
Complex Number Functions
See Complex Number Functions on page 1-27 for a list of functions most
commonly used with MATLAB complex numbers in MATLAB.
Infinity and NaN
MATLAB uses the special values inf, -inf,and NaN to represent values that
are positive and negative infinity, and not a number respectively.
Infinity
MATLAB represents infinity by the special value inf. Infinity results from
operations like division by zero and overflow, which lead to results too large
to represent as conventional floating-point values. MATLAB also provides
afunctioncalled inf that returns the IEEE arithmetic representation for
positive infinity as a double scalar value.
Several examples of statements that return positive or negative infinity in
MATLAB are shown here.
x = 10
x=
Inf
x = 1.e1000
x=
Inf
x = exp(1000)
x=
Inf
x = log(0)
x=
-Inf
Use the isinf function to verify that x is positive or negative infinity:
1-211 Classes (Data Types)
x = log(0);
isinf(x)
ans =
1
NaN
MATLAB represents values that are not real or complex numbers with a
special value called NaN, which stands for Not a Number. Expressions like 00
and infinf result in NaN, as do any arithmetic operations involving a NaN:
x=00
x=
NaN
Use the isnan function to verify that the real part of x is NaN:
isnan(x)
ans =
1
MATLAB also provides a function called NaN that returns the IEEE arithmetic
representation for NaN as a double scalar value:
x = NaN;
whos x
Name Size Bytes Class
x 1x1 8 double
Logical Operations on NaN. Because two NaNs are not equal to each
other, logical operations involving NaN always return false, except for a test
for inequality, (NaN ~= NaN):
NaN > NaN
ans =
0
1-22Numeric Classes
NaN ~= NaN
ans =
1
Infinity and NaN Functions
See Infinity and NaN Functions on page 1-27 for a list of functions most
commonly used with inf and NaN in MATLAB.
Identifying Numeric Classes
You can check the data type of a variable x using any of these commands.
Command Operation
whos x Display the data type of x.
xType = class(x); Assignthedatatypeof x to a variable.
isnumeric(x) Determine if x is a numeric type.
isa(x, 'integer')
isa(x, 'uint64')
isa(x, 'float')
isa(x, 'double')
isa(x, 'single')
Determine if x is the specified numeric type.
(Examples for any integer, unsigned 64-bit integer,any floating point, double precision, and single
precision are shown here).
isreal(x) Determine if x is real or complex.
isnan(x) Determine if x is Not a Number (NaN).
isinf(x) Determine if x is infinite.
isfinite(x) Determine if x is finite.
Display Format for Numeric Values
By default, MATLAB displays numeric output as 5-digit scaled, fixed-point
values. You can change the way numeric values are displayed to any of the
following:
· 5-digit scaled fixed point, floating point, or the best of the two
· 15-digit scaled fixed point, floating point, or the best of the two
1-231 Classes (Data Types)
· A ratio of small integers
· Hexadecimal (base 16)
· Bank notation
All available formats are listed on the format reference page.
To change the numeric display setting, use either the format function or
the Preferences dialog box (accessible from the MATLAB File menu). The
format function changes the display of numeric values for the duration of a
single MATLAB session, while your Preferences settings remain active from
one session to the next. These settings affect only how numbers are displayed,not how MATLAB computes or saves them.
Display Format Examples
Here are a few examples of the various formats and the output produced from
the following two-element vector x, with components of different magnitudes.
Check the current ......
Programming FundamentalsHow to Contact The MathWorks
www.mathworks.com Web
comp.soft-sys.matlab Newsgroup
www.mathworks.comcontact_TS.html Technical Support
suggest@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–2010 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
theuse,modification,reproduction,release,performance,display,anddisclosureoftheProgramand
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.comtrademarks 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.compatents for more information.Revision History
June 2004 First printing New for MATLAB 7.0 (Release 14)
October 2004 Online only Revised for MATLAB 7.0.1 (Release 14SP1)
March 2005 Online only Revised for MATLAB 7.0.4 (Release 14SP2)
June 2005 Second printing Minor revision for MATLAB 7.0.4
September 2005 Online only Revised for MATLAB 7.1 (Release 14SP3)
March 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)
March 2009 Online only Revised for Version 7.8 (Release 2009a)
September 2009 Online only Revised for Version 7.9 (Release 2009b)
March 2010 Online only Revised for Version 7.10 (Release 2010a)Contents
Classes (Data Types)
1
Overview of MATLAB Classes ....................... 1-2
Fundamental MATLAB Classes ...................... 1-2
HowtoUsetheDifferentClasses .................... 1-4
Numeric Classes ................................... 1-6
Overview ........................................ 1-6
Integers ......................................... 1-6
Floating-Point Numbers ............................ 1-10
Complex Numbers ................................. 1-20
Infinity and NaN .................................. 1-21
Identifying Numeric Classes ........................ 1-23
Display Format for Numeric Values .................. 1-23
Function Summary ................................ 1-25
The Logical Class .................................. 1-29
Overview of the Logical Class ....................... 1-29
Identifying Logical Arrays .......................... 1-30
Functions that Return a Logical Result ................ 1-31
Using Logical Arrays in Conditional Statements ........ 1-33
Using Logical Arrays in Indexing .................... 1-34
Characters and Strings ............................. 1-35
Creating Character Arrays .......................... 1-35
Cell Arrays of Strings .............................. 1-40
Formatting Strings ................................ 1-42
String Comparisons ............................... 1-56
Searching and Replacing ........................... 1-59
Converting from Numeric to String ................... 1-60
Converting from String to Numeric ................... 1-62
Function Summary ................................ 1-64
Structures ........................................ 1-67
What Is a Structure? ............................... 1-67
Creating a Structure ............................... 1-69
vStructure Fields .................................. 1-76
Concatenating Structures ........................... 1-79
Indexing into a Struct Array ........................ 1-80
Returning Data from a Struct Array .................. 1-82
Using Structures with Functions ..................... 1-86
Converting Between Struct Array and Cell Array ....... 1-89
Organizing Data in Structure Arrays ................. 1-91
Operator Summary ................................ 1-97
Function Summary ................................ 1-98
Cell Arrays ........................................ 1-101
What Is a Cell Array? .............................. 1-101
Cell Array Operations .............................. 1-103
Creating a Cell Array .............................. 1-103
Concatenating Cell Arrays .......................... 1-108
Indexing into a Cell Array .......................... 1-109
Assigning Values to a Cell Array ..................... 1-113
Returning Data from a Cell Array .................... 1-114
Using Cell Arrays with Functions .................... 1-118
Converting Between Cell Array and Struct Array ....... 1-121
Operator Summary ................................ 1-122
Function Summary ................................ 1-124
Function Handles .................................. 1-127
Overview ........................................ 1-127
Creating a Function Handle ......................... 1-127
Calling a Function By Means of Its Handle ............ 1-131
Preserving Data from the Workspace ................. 1-133
Applications of Function Handles .................... 1-136
Saving and Loading Function Handles ................ 1-142
Advanced Operations on Function Handles ............ 1-142
Functions That Operate on Function Handles .......... 1-148
Map Containers ................................... 1-150
Overview of the Map Data Structure .................. 1-150
Description of the Map Class ........................ 1-151
Creating a Map Object ............................. 1-153
Examining the Contents of the Map .................. 1-156
Reading and Writing Using a Key Index ............... 1-157
Modifying Keys and Values in the Map ................ 1-160
Mapping to Different Value Types .................... 1-163
vi ContentsCombining Unlike Classes .......................... 1-165
Combining Unlike Integer Types ..................... 1-166
Combining Integer and Noninteger Data .............. 1-168
Empty Matrices ................................... 1-168
Concatenation Examples ........................... 1-168
Defining Your Own Classes ......................... 1-171
Basic Program Components
2
MATLAB Commands ............................... 2-2
Basic Command Syntax ............................ 2-2
Entering More Than One Command on a Line .......... 2-3
Assigning to Multiple Outputs ....................... 2-3
Commands that Call MATLAB Functions .............. 2-5
Expressions ....................................... 2-6
String Evaluation ................................. 2-6
Shell Escape Functions ............................. 2-7
Variables ......................................... 2-8
Types of Variables ................................. 2-8
Naming Variables ................................. 2-12
Guidelines to Using Variables ....................... 2-16
Scope of a Variable ................................ 2-16
Lifetime of a Variable .............................. 2-18
Keywords ......................................... 2-19
Special Values ..................................... 2-20
Operators ......................................... 2-22
Arithmetic Operators .............................. 2-22
Relational Operators ............................... 2-23
Logical Operators ................................. 2-24
Operator Precedence ............................... 2-31
viiComma-Separated Lists ............................ 2-33
What Is a Comma-Separated List? ................... 2-33
Generating a Comma-Separated List ................. 2-33
Assigning Output from a Comma-Separated List ........ 2-35
Assigning to a Comma-Separated List ................ 2-36
How to Use the Comma-Separated Lists ............... 2-37
Fast Fourier Transform Example .................... 2-39
Program Control Statements ....................... 2-41
Conditional Control — if, switch ..................... 2-41
Loop Control — for, while, continue, break ............. 2-45
Error Control — try, catch .......................... 2-48
Program Termination — return ...................... 2-49
Dates and Times ................................... 2-50
Overview ........................................ 2-50
Types of Date Formats ............................. 2-50
Conversions Between Date Formats .................. 2-52
Date String Formats ............................... 2-53
Output Formats ................................... 2-54
Current Date and Time ............................. 2-54
Function Summary ................................ 2-55
Regular Expressions ............................... 2-57
Overview ........................................ 2-57
Calling Regular Expression Functions from MATLAB .... 2-59
Parsing Strings with Regular Expressions ............. 2-63
Other Benefits of Using Regular Expressions ........... 2-67
Metacharacters and Operators ....................... 2-68
Character Type Operators .......................... 2-69
Character Representation ........................... 2-73
Grouping Operators ............................... 2-74
Nonmatching Operators ............................ 2-76
Positional Operators ............................... 2-77
Lookaround Operators ............................. 2-78
Quantifiers ....................................... 2-84
Tokens .......................................... 2-87
Named Capture ................................... 2-92
Conditional Expressions ............................ 2-94
Dynamic Regular Expressions ....................... 2-96
String Replacement ................................ 2-105
Handling Multiple Strings .......................... 2-107
viii ContentsFunction, Mode Options, Operator, Return Value
Summaries .................................... 2-110
Symbol Reference ................................. 2-119
Asterisk — ..................................... 2-120
At — @ .......................................... 2-120
Colon — : ........................................ 2-121
Comma — , ...................................... 2-122
Curly Braces — { } ................................. 2-123
Dot — . .......................................... 2-123
Dot-Dot — .. ...................................... 2-124
Dot-Dot-Dot (Ellipsis) — ... .......................... 2-124
Dot-Parentheses — .( ) ............................. 2-126
Exclamation Point — ! ............................. 2-126
Parentheses — ( ) ................................. 2-126
Percent — % ..................................... 2-127
Percent-Brace — %{ %} ............................. 2-128
Plus — + ......................................... 2-128
Semicolon — ; .................................... 2-128
Single Quotes — ................................. 2-129
Space Character .................................. 2-130
Slash and Backslash — \ .......................... 2-130
Square Brackets — [ ] .............................. 2-131
Tilde — ~ ........................................ 2-131
Functions and Scripts
3
Program Development ............................. 3-2
Overview ........................................ 3-2
Creating a Program ................................ 3-2
Getting the Bugs Out .............................. 3-4
Cleaning Up the Program ........................... 3-5
Improving Performance ............................ 3-5
Checking It In .................................... 3-6
Protecting Your Source Code ........................ 3-6
Working with Functions in Files .................... 3-9
Overview ........................................ 3-9
Types of Program Files ............................. 3-9
ixBasic Parts of a Program File ........................ 3-10
Creating a Program File ............................ 3-15
Providing Help for Your Program .................... 3-18
CleaningUptheFileWhenDone ..................... 3-18
Scripts and Functions .............................. 3-21
Scripts .......................................... 3-21
Functions ........................................ 3-22
Types of Functions ................................ 3-23
Organizing Your Functions ......................... 3-24
Identifying Dependencies ........................... 3-25
Calling Functions .................................. 3-27
Command vs. Function Syntax ...................... 3-27
What Happens When You Call a Function ............. 3-36
Determining Which Function Gets Called .............. 3-36
Calling External Functions ......................... 3-40
Running External Programs ........................ 3-40
Function Arguments ............................... 3-41
Overview ........................................ 3-41
Input Arguments .................................. 3-41
Output Arguments ................................ 3-43
Passing Arguments in Structures or Cell Arrays ........ 3-46
Passing Optional Arguments ........................ 3-48
Validating Inputs with Input Parser ................. 3-60
What Is the Input Parser? .......................... 3-60
Working with the Example Function .................. 3-61
The inputParser Class ............................. 3-62
Validating Data Passed to a Function ................. 3-63
Substituting Default Values for Arguments Not Passed .. 3-70
Handling Unmatched Inputs ........................ 3-71
Interpreting Arguments Passed as Structures .......... 3-72
Other Features of the Input Parser ................... 3-75
Summary of inputParser Methods and Properties ....... 3-78
Functions Provided By MATLAB .................... 3-81
Overview ........................................ 3-81
Functions ........................................ 3-81
Built-In Functions ................................. 3-82
Overloaded MATLAB Functions ..................... 3-83
x ContentsInternal Utility Functions .......................... 3-84
Types of Functions
4
Overview of MATLAB Function Types ............... 4-2
Anonymous Functions ............................. 4-3
Constructing an Anonymous Function ................ 4-3
Arrays of Anonymous Functions ..................... 4-6
Outputs from Anonymous Functions .................. 4-7
Variables Used in the Expression .................... 4-8
Examples of Anonymous Functions ................... 4-11
Primary Functions ................................. 4-15
Nested Functions .................................. 4-16
Writing Nested Functions ........................... 4-16
Calling Nested Functions ........................... 4-18
Variable Scope in Nested Functions .................. 4-19
Using Function Handles with Nested Functions ........ 4-21
Restrictions on Assigning to Variables ................ 4-26
Examples of Nested Functions ....................... 4-27
Subfunctions ...................................... 4-33
Overview ........................................ 4-33
Calling Subfunctions ............................... 4-34
Accessing Help for a Subfunction ..................... 4-34
Private Functions ................................. 4-35
Overview ........................................ 4-35
Private Folders ................................... 4-35
Accessing Help for a Private Function ................. 4-36
Overloaded Functions .............................. 4-37
xiUsing Objects
5
MATLAB Objects .................................. 5-2
Getting Oriented .................................. 5-2
Getting Comfortable with Objects .................... 5-2
What Are Objects and Why Use Them? ................ 5-2
Accessing Objects ................................. 5-3
Objects In the MATLAB Language ................... 5-4
Other Kinds of Objects Used by MATLAB ............. 5-4
General Purpose Vs. Specialized Arrays ............. 5-5
How They Differ .................................. 5-5
Using General-Purpose Data Structures ............... 5-5
Using Specialized Objects ........................... 5-6
Key Object Concepts ............................... 5-8
Basic Concepts .................................... 5-8
Classes Describe How to Create Objects ............... 5-8
Properties Contain Data ............................ 5-8
Methods Implement Operations ...................... 5-9
Creating Objects ................................... 5-11
Class Constructor ................................. 5-11
When to Use Package Names ........................ 5-11
Accessing Object Data ............................. 5-14
Listing Public Properties ........................... 5-14
Getting Property Values ............................ 5-14
Setting Property Values ............................ 5-15
Calling Object Methods ............................ 5-16
What Operations Can You Perform ................... 5-16
Method Syntax ................................... 5-16
Class of Objects Returned by Methods ................ 5-18
Desktop Tools Are Object Aware .................... 5-19
Tab Completion Works with Objects .................. 5-19
Editing Objects with the Variable Editor .............. 5-19
xii ContentsGetting Information About Objects .................. 5-21
The Class of Workspace Variables .................... 5-21
Information About Class Members ................... 5-23
Logical Tests for Objects ............................ 5-23
Displaying Objects ................................ 5-24
Getting Help for MATLAB Objects ................... 5-25
Copying Objects ................................... 5-26
Two Copy Behaviors ............................... 5-26
Value Object Copy Behavior ......................... 5-26
Handle Object Copy Behavior ....................... 5-27
Testing for Handle or Value Class .................... 5-30
Destroying Objects ................................ 5-31
Object Lifecycle ................................... 5-31
Difference Between clear and delete .................. 5-31
Error Handling
6
Error Reporting in a MATLAB Application ........... 6-2
Overview ........................................ 6-2
Getting an Exception at the Command Line ............ 6-2
GettinganExceptioninYourProgramCode ........... 6-3
Generating a New Exception ........................ 6-4
Capturing Information About the Error ............. 6-5
Overview ........................................ 6-5
The MException Class ............................. 6-5
Properties of the MException Class ................... 6-7
Methods of the MException Class .................... 6-14
Throwing an Exception ............................ 6-16
Responding to an Exception ........................ 6-17
Overview ........................................ 6-17
The try-catch Statement ............................ 6-17
Suggestions on How to Handle an Exception ........... 6-19
xiiiWarnings ......................................... 6-22
Reporting a Warning ............................... 6-22
Identifying the Cause .............................. 6-23
Warning Control ................................... 6-24
Overview ........................................ 6-24
Warning Statements ............................... 6-25
Warning Control Statements ........................ 6-26
Output from Control Statements ..................... 6-28
Saving and Restoring State ......................... 6-31
Backtrace and Verbose Modes ....................... 6-32
Debugging Errors and Warnings .................... 6-35
Program Scheduling
7
Using a MATLAB Timer Object ..................... 7-2
Overview ........................................ 7-2
Example: Displaying a Message ..................... 7-3
Creating Timer Objects ............................ 7-5
Creating the Object ................................ 7-5
Naming the Object ................................ 7-6
Working with Timer Object Properties .............. 7-7
Retrieving the Value of Timer Object Properties ........ 7-7
Setting the Value of Timer Object Properties ........... 7-8
Starting and Stopping Timers ...................... 7-10
Starting a Timer .................................. 7-10
Starting a Timer at a Specified Time .................. 7-10
Stopping Timer Objects ............................ 7-11
Blocking the MATLAB Command Line ................ 7-12
Creating and Executing Callback Functions ......... 7-14
Associating Commands with Timer Object Events ....... 7-14
Creating Callback Functions ........................ 7-15
xiv ContentsSpecifying the Value of Callback Function Properties .... 7-17
Timer Object Execution Modes ..................... 7-19
Executing a Timer Callback Function Once ............ 7-19
Executing a Timer Callback Function Multiple Times .... 7-20
Handling Callback Function Queuing Conflicts ......... 7-21
Deleting Timer Objects from Memory ............... 7-23
Deleting One or More Timer Objects .................. 7-23
Testing the Validity of a Timer Object ................. 7-23
Finding Timer Objects in Memory ................... 7-24
Finding All Timer Objects .......................... 7-24
Finding Invisible Timer Objects ...................... 7-24
Performance
8
Analyzing Your Program’s Performance ............. 8-2
Overview ........................................ 8-2
The Profiler Utility ................................ 8-2
Stopwatch Timer Functions ......................... 8-2
Techniques for Improving Performance ............. 8-4
Preallocating Arrays ............................... 8-4
Use Distributed Arrays for Large Datasets ............. 8-5
When Possible, Replace for with parfor (Parallel for) ..... 8-6
Limiting Size and Complexity ....................... 8-6
Assigning to Variables ............................. 8-6
Using Appropriate Logical Operators ................. 8-7
Overloading Built-In Functions ...................... 8-8
Functions Are Generally Faster Than Scripts .......... 8-8
Load and Save Are Faster Than File IO Functions ...... 8-8
Vectorizing Loops ................................. 8-8
Avoid Large Background Processes ................... 8-11
xvMemory Usage
9
Memory Allocation ................................. 9-2
Memory Allocation for Arrays ....................... 9-2
Data Structures and Memory ........................ 9-7
Memory Management Functions .................... 9-12
The whos Function ................................ 9-13
Strategies for Efficient Use of Memory .............. 9-15
Ways to Reduce the Amount of Memory Required ....... 9-15
Using Appropriate Data Storage ..................... 9-17
How to Avoid Fragmenting Memory .................. 9-20
Reclaiming Used Memory ........................... 9-22
Resolving “Out of Memory” Errors .................. 9-23
General Suggestions for Reclaiming Memory ........... 9-23
Setting the Process Limit ........................... 9-24
Disabling Java VM on Startup ...................... 9-25
Increasing System Swap Space ...................... 9-26
Using the 3GB Switch on Windows Systems ............ 9-27
Freeing Up System Resources on Windows Systems ..... 9-27
Programming Tips
10
Introduction ...................................... 10-2
Command and Function Syntax ..................... 10-3
Syntax Help ...................................... 10-3
Command and Function Syntaxes .................... 10-3
Command Line Continuation ........................ 10-3
Completing Commands Using the Tab Key ............. 10-4
Recalling Commands .............................. 10-4
Clearing Commands ............................... 10-5
Suppressing Output to the Screen .................... 10-5
xvi ContentsHelp .............................................. 10-6
Using the Help Browser ............................ 10-6
Help on Functions from the Help Browser ............. 10-6
Help on Functions from the Command Window ......... 10-7
Topical Help ...................................... 10-7
Paged Output .................................... 10-8
Writing Your Own Help ............................ 10-8
Help for Subfunctions and Private Functions ........... 10-9
Help for Methods and Overloaded Functions ........... 10-9
Development Environment ......................... 10-10
Workspace Browser ................................ 10-10
Using the Find and Replace Utility ................... 10-10
Commenting Out a Block of Code .................... 10-11
Creating Functions from Command History ............ 10-11
Editing Functions in EMACS ........................ 10-11
Functions ......................................... 10-12
Function Structure ................................ 10-12
Using Lowercase for Function Names ................. 10-12
Getting a Function’s Name and Path .................. 10-13
What Files Does a Function Use? .................... 10-13
Dependent Functions, Built-Ins, Classes ............... 10-14
Function Arguments ............................... 10-15
Getting the Input and Output Arguments ............. 10-15
Variable Numbers of Arguments ..................... 10-15
String or Numeric Arguments ....................... 10-16
Passing Arguments in a Structure .................... 10-16
Passing Arguments in a Cell Array ................... 10-17
Program Development ............................. 10-18
Planning the Program .............................. 10-18
Using Pseudo-Code ................................ 10-18
Selecting the Right Data Structures .................. 10-18
General Coding Practices ........................... 10-19
Naming a Function Uniquely ........................ 10-19
The Importance of Comments ....................... 10-19
Coding in Steps ................................... 10-20
Making Modifications in Steps ....................... 10-20
Functions with One Calling Function ................. 10-20
Testing the Final Program .......................... 10-20
xviiDebugging ........................................ 10-21
The MATLAB Debug Functions ...................... 10-21
More Debug Functions ............................. 10-21
The MATLAB Graphical Debugger ................... 10-22
A Quick Way to Examine Variables ................... 10-22
Setting Breakpoints from the Command Line .......... 10-22
Finding Line Numbers to Set Breakpoints ............. 10-23
Stopping Execution on an Error or Warning ............ 10-23
Locating an Error from the Error Message ............. 10-23
Using Warnings to Help Debug ...................... 10-24
Making Code Execution Visible ...................... 10-24
Debugging Scripts ................................. 10-24
Variables ......................................... 10-25
Rules for Variable Names ........................... 10-25
Making Sure Variable Names Are Valid ............... 10-25
Do Not Use Function Names for Variables ............. 10-26
Checking for Reserved Keywords ..................... 10-26
Avoid Using i and j for Variables ..................... 10-27
Avoid Overwriting Variables in Scripts ................ 10-27
Persistent Variables ............................... 10-27
Protecting Persistent Variables ...................... 10-27
Global Variables .................................. 10-28
Strings ........................................... 10-29
Creating Strings with Concatenation ................. 10-29
Comparing Methods of Concatenation ................. 10-29
Store Arrays of Strings in a Cell Array ................ 10-30
Converting Between Strings and Cell Arrays ........... 10-30
Search and Replace Using Regular Expressions ......... 10-30
Evaluating Expressions ............................ 10-32
Find Alternatives to Using eval ...................... 10-32
Assigning to a Series of Variables .................... 10-32
Short-Circuit Logical Operators ...................... 10-33
Changing the Counter Variable within a for Loop ....... 10-33
MATLAB Path ..................................... 10-34
Precedence Rules .................................. 10-34
File Precedence ................................... 10-35
Adding a Folder to the Search Path ................... 10-35
Handles to Functions Not on the Path ................. 10-35
xviii ContentsMaking Toolbox File Changes Visible to MATLAB ....... 10-36
Making Nontoolbox File Changes Visible to MATLAB .... 10-37
Change Notification on Windows ..................... 10-37
Program Control .................................. 10-38
Using break, continue, and return .................... 10-38
Using switch Versus if ............................. 10-39
MATLAB case Evaluates Strings ..................... 10-39
Multiple Conditions in a case Statement ............... 10-39
Implicit Break in switch-case ........................ 10-39
Variable Scope in a switch .......................... 10-40
Catching Errors with try-catch ...................... 10-40
Nested try-catch Blocks ............................ 10-41
Forcing an Early Return from a Function .............. 10-41
Save and Load ..................................... 10-42
Saving Data from the Workspace ..................... 10-42
Loading Data into the Workspace .................... 10-42
Viewing Variables in a MAT-File ..................... 10-43
Appending to a MAT-File ........................... 10-43
SaveandLoadonStartuporQuit .................... 10-44
Saving to an ASCII File ............................ 10-44
Files and Filenames ................................ 10-45
Naming Functions ................................. 10-45
Naming Other Files ............................... 10-45
Passing Filenames as Arguments .................... 10-46
Passing Filenames to ASCII Files .................... 10-46
Determining Filenames at Run-Time ................. 10-46
Returning the Size of a File ......................... 10-46
InputOutput ...................................... 10-48
File IO Function Overview ......................... 10-48
Common IO Functions ............................. 10-48
Readable File Formats ............................. 10-48
Using the Import Wizard ........................... 10-49
Loading Mixed Format Data ........................ 10-49
Reading Files with Different Formats ................. 10-49
Interactive Input into Your Program .................. 10-50
Starting MATLAB .................................. 10-51
Getting MATLAB to Start Up Faster ................. 10-51
xixOperating System Compatibility .................... 10-52
Executing OS Commands from MATLAB ............. 10-52
Searching Text with grep ........................... 10-52
Constructing Paths and Filenames ................... 10-52
Finding the MATLAB Root Folder .................... 10-53
Temporary Directories and Filenames ................ 10-53
Demos ............................................ 10-54
Demos Available with MATLAB ..................... 10-54
For More Information .............................. 10-55
Current CSSM .................................... 10-55
Archived CSSM ................................... 10-55
MATLAB Technical Support ........................ 10-55
Tech Notes ....................................... 10-55
MATLAB Central ................................. 10-55
MATLAB Newsletters (Digest, News Notes) .......... 10-55
MATLAB Documentation ........................... 10-56
MATLAB Index of Examples ........................ 10-56
Index
xx Contents1
Classes (Data Types)
· “Overview of MATLAB Classes” on page 1-2
· “Numeric Classes” on page 1-6
· “The Logical Class” on page 1-29
· “Characters and Strings” on page 1-35
· “Structures” on page 1-67
· “Cell Arrays” on page 1-101
· “Function Handles” on page 1-127
· “Map Containers” on page 1-150
· “Combining Unlike Classes” on page 1-165
· “Defining Your Own Classes” on page 1-1711 Classes (Data Types)
Overview of MATLAB Classes
In this section...
“Fundamental MATLAB Classes” on page 1-2
“How to Use the Different Classes” on page 1-4
Fundamental MATLAB Classes
There are many different data types, or classes,thatyoucanworkwithinthe
MATLAB? software. You can build matrices and arrays of floating-point
and integer data, characters and strings, and logical true and false states.
Function handles connect your code with any MATLAB function regardless
of the current scope. Structures and cell arrays, provide a way to store
dissimilar types of data in the same array.
There are 15 fundamental classes in MATLAB. Each of these classes is in the
form of a matrix or array. This matrix or array is a minimum of 0-by-0 in size
and can grow to an n-dimensional array of any size.
All of the fundamental MATLAB classes are circled in the diagram below:
1-2Overview of MATLAB? Classes
Numeric classes in the MATLAB software include signed and unsigned
integers, and single- and double-precision floating-point numbers. By
default, MATLAB stores all numeric values as double-precision floating
point. (You cannot change the default type and precision.) You can choose
to store any number, or array of numbers, as integers or as single-precision.
Integer and single-precision arrays offer more memory-efficient storage than
double-precision.
All numeric types support basic array operations, such as subscripting and
reshaping. All numeric types except for int64 and uint64 can be used in
mathematical operations.
You can create two-dimensional double and logical matrices using one of
two storage formats: full or sparse. For matrices with mostly zero-valued
elements, a sparse matrix requires a fraction of the storage space required
1-31 Classes (Data Types)
for an equivalent full matrix. Sparse matrices invoke methods especially
tailored to solve sparse problems
Theseclassesrequiredifferentamounts of storage, the smallest being a
logical value or 8–bit integer which requires only 1 byte. It is important to
keep this minimum size in mind if you work on data in files that were written
using a precision smaller than 8 bits.
How to Use the Different Classes
The following table describes these classes in more detail.
Class Name Documentation Intended Use
double, single Floating-Point
Numbers
· Required for fractional numeric data.
· Double and Single precision.
· Use realmin and realmax to show range of values.
· Two-dimensional arrays can be sparse.
· Default numeric type in MATLAB.
int8, uint8,int16,uint16,int32,uint32,int64, uint64
Integers ? Use for signed and unsigned whole numbers.
· More efficient use of memory.
· Use intmin and intmax to show range of values.
· Choose from 4 sizes (8, 16, 32, and 64 bits).
· Use all but 64-bit in mathematics operations.
char “Characters and
Strings” on page
1-35
· Required for text.
· Native or unicode.
· Converts tofrom numeric.
· Use with regular expressions.
· For multiple strings, use cell arrays.
1-4Overview of MATLAB? Classes
Class Name Documentation Intended Use
logical Logical Class ? Use in relational conditions or to test state.
· Can have one of two values: true or false.
· Also useful in array indexing.
· Two-dimensional arrays can be sparse.
function_handle “Function
Handles” on page
1-127
· Pointer to a function.
· Enables passing a function to another function
· Can also call functions outside usual scope.
· Useful in Handle Graphics callbacks.
· Save to MAT-file and restore later.
struct Structures ? Fields store arrays of varying classes and sizes.
· Access multiple fieldsindices in single operation.
· Field names identify contents.
· Simple method of passing function arguments.
· Use in comma-separated lists for efficiency.
· More memory required for overhead
cell Cell Arrays ? Cells store arrays of varying classes and sizes.
· Allows freedom to package data as you want.
· Manipulation of elements is similar to arrays.
· Simple method of passing function arguments.
· Use in comma-separated lists for efficiency.
· More memory required for overhead
1-51 Classes (Data Types)
Numeric Classes
In this section...
“Overview” on page 1-6
“Integers” on page 1-6
“Floating-Point Numbers” on page 1-10
“Complex Numbers” on page 1-20
“Infinity and NaN” on page 1-21
“Identifying Numeric Classes” on page 1-23
“Display Format for Numeric Values” on page 1-23
“Function Summary” on page 1-25
Overview
Numeric classes in the MATLAB software include signed and unsigned
integers, and single- and double-precision floating-point numbers. By
default, MATLAB stores all numeric values as double-precision floating
point. (You cannot change the default type and precision.) You can choose
to store any number, or array of numbers, as integers or as single-precision.
Integer and single-precision arrays offer more memory-efficient storage than
double-precision.
All numeric types support basic array operations, such as subscripting and
reshaping. All numeric types except for int64 and uint64 can be used in
mathematical operations.
Integers
MATLAB has four signed and four unsigned integer classes. Signed types
enable you to work with negative integers as well as positive, but cannot
represent as wide a range of numbers as the unsigned types because one bit
is used to designate a positive or negative sign for the number. Unsigned
types give you a wider range of numbers, but these numbers can only be
zero or positive.
This section covers:
1-6Numeric Classes
· “Creating Integer Data” on page 1-7
· “Arithmetic Operations on Integer Classes” on page 1-9
· “Largest and Smallest Values for Integer Classes” on page 1-9
· “Integer Functions” on page 1-10
MATLAB supports 1-, 2-, 4-, and 8-byte storage for integer data. You can
save memory and execution time for your programs if you use the smallest
integer type that accommodates your data. For example, you do not need a
32-bit integer to store the value 100.
Here are the eight integer classes, the range of values you can store with each
type, and the MATLAB conversion function required to create that type:
Class Range of Values Conversion Function
Signed 8-bit integer -27 to 27-1 int8
Signed 16-bit integer -215 to 215-1 int16
Signed 32-bit integer -231 to 231-1 int32
Signed 64-bit integer -263 to 263-1 int64
Unsigned 8-bit integer 0to28-1 uint8
Unsigned 16-bit integer 0to216-1 uint16
Unsigned 32-bit integer 0to232-1 uint32
Unsigned 64-bit integer 0to264-1 uint64
Creating Integer Data
MATLAB stores numeric data as double-precision floating point (double)
by default. To store data as an integer, you need to convert from double to
the desired integer type. Use one of the conversion functions shown in the
table above.
For example, to store 325 as a 16-bit signed integer assigned to variable x,type
x = int16(325);
1-71 Classes (Data Types)
If the number being converted to an integer has a fractional part, MATLAB
rounds to the nearest integer. If the fractional part is exactly 0.5,thenfrom
the two equally nearby integers, MATLAB chooses the one for which the
absolute value is larger in magnitude:
x = 325.499; x = x + .001;
int16(x) int16(x)
ans = ans =
325 326
If you need to round a number using a rounding scheme other than the
default, MATLAB provides four rounding functions: round, fix, floor,and
ceil. In this example, the fix function enables you to override the default
and round towards zero when the fractional part of a number is .5:
x = 325.5;
int16(fix(x))
ans =
325
Arithmetic operations that involve both integers and floating-point always
result in an integer data type. MATLAB rounds the result, when necessary,according to the default rounding algorithm. The example below yields an
exact answer of 1426.75 which MATLAB then rounds to the next highest
integer:
int16(325) 4.39
ans =
1427
The integer conversion functions are also useful when converting other
classes, such as strings, to integers:
str = 'Hello World';
int8(str)
ans =
72 101 108 108 111 32 87 111 114 108 100
1-8Numeric Classes
Arithmetic Operations on Integer Classes
MATLAB can perform integer arithmetic on the following types of data:
· Integers or integer arrays of the same integer data type. This yields a
result that has the same data type as the operands:
x = uint32([132 347 528]) . uint32(75);
· Integers or integer arrays and scalar double-precision floating-point
numbers. This yields a result that has the same data type as the integer
operands:
x = uint32([132 347 528]) . 75.49;
For all binary operations in which one operand is an array of integer data
type and the other is a scalar double, MATLAB computes the operation using
elementwise double-precision arithmetic, and then converts the result back to
the original integer data type.
For a list of the operations that support integer classes, see Nondouble Data
Type Support in the arithmetic operators reference page.
Largest and Smallest Values for Integer Classes
For each integer data type, there is a largest and smallest number that you
can represent with that type. The table shown under “Integers” on page 1-6
lists the largest and smallest values for each integer data type in the “Range
of Values” column.
You can also obtain these values with the intmax and intmin functions:
intmax('int8') intmin('int8')
ans = ans =
127 -128
If you convert a number that is larger than the maximum value of an integer
data type to that type, MATLAB sets it to the maximum value. Similarly, if
you convert a number that is smaller than the minimum value of the integer
data type, MATLAB sets it to the minimum value. For example,x = int8(300) x = int8(-300)
1-91 Classes (Data Types)
x= x=
127 -128
Also, when the result of an arithmetic operation involving integers exceeds
the maximum (or minimum) value of the data type, MATLAB sets it to the
maximum (or minimum) value:
x = int8(100) 3 x = int8(-100) 3
x= x=
127 -128
You can make MATLAB return a warning when your input is outside the
range an integer data type. This is described in the next section.
Integer Functions
See Integer Functions on page 1-26 for a list of functions most commonly used
with integers in MATLAB.
Floating-Point Numbers
MATLAB represents floating-point numbers in either double-precision or
single-precision format. The default is double precision, but you can make
any number single precision with a simple conversion function.
This section covers:
· “Double-Precision Floating Point” on page 1-11
· “Single-Precision Floating Point” on page 1-11
· “Creating Floating-Point Data” on page 1-11
· “Arithmetic Operations on Floating-Point Numbers” on page 1-13
· “Largest and Smallest Values for Floating-Point Classes” on page 1-14
· “Accuracy of Floating-Point Data” on page 1-15
· “Avoiding Common Problems with Floating-Point Arithmetic” on page 1-17
· “Floating-Point Functions” on page 1-19
· “References” on page 1-19
1-10Numeric Classes
Double-Precision Floating Point
MATLAB constructs the double-precision (or double) data type according
to IEEE? Standard 754 for double precision. Any value stored as a double
requires 64 bits, formatted as shown in the table below:
Bits Usage
63 Sign (0 =positive, 1 =negative)
62 to 52 Exponent, biased by 1023
51 to 0 Fraction f of the number 1.f
Single-Precision Floating Point
MATLAB constructs the single-precision (or single) data type according
to IEEE Standard 754 for single precision. Any value stored as a single
requires 32 bits, formatted as shown in the table below:
Bits Usage
31 Sign (0 =positive, 1 =negative)
30 to 23 Exponent, biased by 127
22 to 0 Fraction f of the number 1.f
Because MATLAB stores numbers of type single using 32 bits, they require
less memory than numbers of type double, which use 64 bits. However,because they are stored with fewer bits, numbers of type single are
represented to less precision than numbers of type double.
Creating Floating-Point Data
Use double-precision to store values greater than approximately 3.4 x 1038
or less than approximately -3.4 x 1038. For numbers that lie between these
two limits, you can use either double- or single-precision, but single requires
less memory.
Creating Double-Precision Data. Because the default numeric type
for MATLAB is double, you can create a double with a simple assignment
statement:
1-111 Classes (Data Types)
x = 25.783;
The whos function shows that MATLAB has created a 1-by-1 array of type
double for the value you just stored in x:
whos x
Name Size Bytes Class
x 1x1 8 double
Use isfloat ifyoujustwanttoverifythat x is a floating-point number. This
function returns logical 1 (true) if the input is a floating-point number, and
logical 0 (false)otherwise:
isfloat(x)
ans =
1
You can convert other numeric data, characters or strings, and logical data to
double precision using the MATLAB function, double. This example converts
a signed integer to double-precision floating point:
y = int64(-589324077574); % Create a 64-bit integer
x = double(y) % Convert to double
x=
-5.8932e+011
Creating Single-Precision Data. Because MATLAB stores numeric data as
a double by default, you need to use the single conversion function to create
a single-precision number:
x = single(25.783);
The whos function returns the attributes of variable x in a structure. The
bytes field of this structure shows that when x is stored as a single, it requires
just 4 bytes compared with the 8 bytes to store it as a double:
xAttrib = whos('x');
xAttrib.bytes
ans =
1-12Numeric Classes
4
You can convert other numeric data, characters or strings, and logical data to
single precision using the single function. This example converts a signed
integer to single-precision floating point:
y = int64(-589324077574); % Create a 64-bit integer
x = single(y) % Convert to single
x=
-5.8932e+011
Arithmetic Operations on Floating-Point Numbers
This section describes which classes you can use in arithmetic operations
with floating-point numbers.
Double-Precision Operations. You can perform basic arithmetic operations
with double and any of the following other classes. When one or more
operands is an integer (scalar or array), the double operand must be a scalar.
The result is of type double, except where noted otherwise:
· single — The result is of type single
· double
· int or uint — The result has the same data type as the integer operand
· char
· logical
This example performs arithmetic on data of types char and double.The
result is of type double:
c = 'uppercase' - 32;
class(c)
ans =
double
char(c)
1-131 Classes (Data Types)
ans =
UPPERCASE
Single-Precision Operations. You can perform basic arithmetic operations
with single and any of the following other classes. The result is always
single:
· single
· double
· char
· logical
In this example, 7.5 defaults to type double,andtheresultisoftype single:
x = single([1.32 3.47 5.28]) . 7.5;
class(x)
ans =
single
Largest and Smallest Values for Floating-Point Classes
For the double and single classes, there is a largest and smallest number
that you can represent with that type.
Largest and Smallest Double-Precision Values. The MATLAB functions
realmax and realmin return the maximum and minimum values that you
can represent with the double data type:
str = 'The range for double is:\n\t%g to %g and\n\t %g to %g';
sprintf(str, -realmax, -realmin, realmin, realmax)
ans =
The range for double is:
-1.79769e+308 to -2.22507e-308 and
2.22507e-308 to 1.79769e+308
1-14Numeric Classes
Numbers larger than realmax or smaller than -realmax are assigned the
values of positive and negative infinity, respectively:
realmax + .0001e+308
ans =
Inf
-realmax - .0001e+308
ans =
-Inf
Largest and Smallest Single-Precision Values. The MATLAB functions
realmax and realmin, when called with the argument 'single',returnthe
maximum and minimum values that you can represent with the single data
type:
str = 'The range for single is:\n\t%g to %g and\n\t %g to %g';
sprintf(str, -realmax('single'), -realmin('single'), ...
realmin('single'), realmax('single'))
ans =
The range for single is:
-3.40282e+038 to -1.17549e-038 and
1.17549e-038 to 3.40282e+038
Numbers larger than realmax(’single’) or smaller than -realmax (’single’) are
assigned the values of positive and negative infinity, respectively:
realmax('single') + .0001e+038
ans =
Inf
-realmax('single') - .0001e+038
ans =
-Inf
Accuracy of Floating-Point Data
If the result of a floating-point arithmetic computation is not as precise as
you had expected, it is likely caused by the limitations of your computer’s
1-151 Classes (Data Types)
hardware. Probably, your result was a little less exact because the hardware
had insufficient bits to represent the result with perfect accuracy; therefore, it
truncated the resulting value.
Double-Precision Accuracy. Because there are only a finite number
of double-precision numbers, you cannot represent all numbers in
double-precision storage. On any computer, there is a small gap between each
double-precision number and the next larger double-precision number. You
can determine the size of this gap, which limits the precision of your results,using the eps function. For example, to find the distance between 5 and the
next larger double-precision number, enter
format long
eps(5)
ans =
8.881784197001252e-016
This tells you that there are no double-precision numbers between 5 and
5 + eps(5). If a double-precision computation returns the answer 5, the
result is only accurate to within eps(5).
The value of eps(x) depends on x.Thisexampleshowsthat,as x gets larger,so does eps(x):
eps(50)
ans =
7.105427357601002e-015
If you enter eps with no input argument, MATLAB returns the value of
eps(1),thedistancefrom 1 to the next larger double-precision number.
Single-Precision Accuracy. Similarly, there are gaps between any two
single-precision numbers. If x has type single, eps(x) returns the distance
between x and the next larger single-precision number. For example,x = single(5);
eps(x)
returns
1-16Numeric Classes
ans =
4.7684e-007
Note that this result is larger than eps(5). Because there are fewer
single-precision numbers than double-precision numbers, the gaps
between the single-precision numbers are larger than the gaps between
double-precision numbers. This means that results in single-precision
arithmetic are less precise than in double-precision arithmetic.
For a number x of type double, eps(single(x)) gives you an upper bound
for the amount that x is rounded when you convert it from double to single.
For example, when you convert the double-precision number 3.14 to single,it is rounded by
double(single(3.14) - 3.14)
ans =
1.0490e-007
The amount that 3.14 is rounded is less than
eps(single(3.14))
ans =
2.3842e-007
Avoiding Common Problems with Floating-Point Arithmetic
Almost all operations in MATLAB are performed in double-precision
arithmetic conforming to the IEEE standard 754. Because computers only
represent numbers to a finite precision (double precision calls for 52 mantissa
bits), computations sometimes yield mathematically nonintuitive results. It is
important to note that these results are not bugs in MATLAB.
Use the following examples to help you identify these cases:
Example 1 — Round-Off or What You Get Is Not What You Expect.
The decimal number 43 is not exactly representable as a binary fraction. For
this reason, the following calculation does not give zero, but rather reveals
the quantity eps.
e = 1 - 3(43 - 1)
1-171 Classes (Data Types)
e=
2.2204e-016
Similarly, 0.1 is not exactly representable as a binary number. Thus, you get
the following nonintuitive behavior:
a = 0.0;
for i = 1:10
a = a + 0.1;
end
a==1
ans =
0
Note that the order of operations can matter in the computation:
b = 1e-16 + 1 - 1e-16;
c = 1e-16 - 1e-16 + 1;
b==c
ans =
0
There are gaps between floating-point numbers. As the numbers get larger,so do the gaps, as evidenced by:
(2^53 + 1) - 2^53
ans =
0
Since pi is not really pi, it is not surprising that sin(pi) is not exactly zero:
sin(pi)
ans =
1.224646799147353e-016
1-18Numeric Classes
Example 2 — Catastrophic Cancellation. When subtractions are
performed with nearly equal operands, sometimes cancellation can occur
unexpectedly. The following is an example of a cancellation caused by
swamping (loss of precision that makes the addition insignificant).
sqrt(1e-16 + 1) - 1
ans =
0
Some functions in MATLAB, such as expm1 and log1p, may be used to
compensate for the effects of catastrophic cancellation.
Example 3 — Floating-Point Operations and Linear Algebra.
Round-off, cancellation, and other traits of floating-point arithmetic combine
to produce startling computations when solving the problems of linear
algebra. MATLAB warns that the following matrix A is ill-conditioned, and
therefore the system Ax = b may be sensitive to small perturbations:
A = diag([2 eps]);
b = [2; eps];
y = A\b;
Warning: Matrix is close to singular or badly scaled.
Results may be inaccurate. RCOND = 1.110223e-016.
These are only a few of the examples showing how IEEE floating-point
arithmetic affects computations in MATLAB. Note that all computations
performed in IEEE 754 arithmetic are affected, this includes applications
written in C or FORTRAN, as well as MATLAB. For more examples
and information, see Technical Note 1108 Common Problems with
Floating-Point Arithmetic.
Floating-Point Functions
See Floating-Point Functions on page 1-26 for a list of functions most
commonly used with floating-point numbers in MATLAB.
References
The following references provide more information about floating-point
arithmetic.
1-191 Classes (Data Types)
[1] Moler, Cleve, “Floating Points,” MATLAB News and Notes,Fall,1996. A PDF version is available on the MathWorks Web site at
http:www.mathworks.comcompanynewslettersnews_notespdfFall96Cleve.pdf
[2] Moler, Cleve, Numerical Computing with MATLAB, S.I.A.M.
A PDF version is available on the MathWorks Web site at
http:www.mathworks.commoler.
Complex Numbers
Complex numbers consist of two separate parts: a real part and an imaginary
part. The basic imaginary unit is equal to the square root of -1.Thisis
represented in MATLAB by either of two letters: i or j.
Creating Complex Numbers
The following statement shows one way of creating a complex value in
MATLAB. The variable x is assigned a complex number with a real part of 2
and an imaginary part of 3:
x=2+3i;
Another way to create a complex number is using the complex function. This
function combines two numeric inputs into a complex output, making the first
input real and the second imaginary:
x = rand(3) 5;
y = rand(3) -8;
z = complex(x, y)
z=
4.7842 -1.0921i 0.8648 -1.5931i 1.2616 -2.2753i
2.6130 -0.0941i 4.8987 -2.3898i 4.3787 -3.7538i
4.4007 -7.1512i 1.3572 -5.2915i 3.6865 -0.5182i
You can separate a complex number into its real and imaginary parts using
the real and imag functions:
zr = real(z)
zr =
4.7842 0.8648 1.2616
1-20Numeric Classes
2.6130 4.8987 4.3787
4.4007 1.3572 3.6865
zi = imag(z)
zi =
-1.0921 -1.5931 -2.2753
-0.0941 -2.3898 -3.7538
-7.1512 -5.2915 -0.5182
Complex Number Functions
See Complex Number Functions on page 1-27 for a list of functions most
commonly used with MATLAB complex numbers in MATLAB.
Infinity and NaN
MATLAB uses the special values inf, -inf,and NaN to represent values that
are positive and negative infinity, and not a number respectively.
Infinity
MATLAB represents infinity by the special value inf. Infinity results from
operations like division by zero and overflow, which lead to results too large
to represent as conventional floating-point values. MATLAB also provides
afunctioncalled inf that returns the IEEE arithmetic representation for
positive infinity as a double scalar value.
Several examples of statements that return positive or negative infinity in
MATLAB are shown here.
x = 10
x=
Inf
x = 1.e1000
x=
Inf
x = exp(1000)
x=
Inf
x = log(0)
x=
-Inf
Use the isinf function to verify that x is positive or negative infinity:
1-211 Classes (Data Types)
x = log(0);
isinf(x)
ans =
1
NaN
MATLAB represents values that are not real or complex numbers with a
special value called NaN, which stands for Not a Number. Expressions like 00
and infinf result in NaN, as do any arithmetic operations involving a NaN:
x=00
x=
NaN
Use the isnan function to verify that the real part of x is NaN:
isnan(x)
ans =
1
MATLAB also provides a function called NaN that returns the IEEE arithmetic
representation for NaN as a double scalar value:
x = NaN;
whos x
Name Size Bytes Class
x 1x1 8 double
Logical Operations on NaN. Because two NaNs are not equal to each
other, logical operations involving NaN always return false, except for a test
for inequality, (NaN ~= NaN):
NaN > NaN
ans =
0
1-22Numeric Classes
NaN ~= NaN
ans =
1
Infinity and NaN Functions
See Infinity and NaN Functions on page 1-27 for a list of functions most
commonly used with inf and NaN in MATLAB.
Identifying Numeric Classes
You can check the data type of a variable x using any of these commands.
Command Operation
whos x Display the data type of x.
xType = class(x); Assignthedatatypeof x to a variable.
isnumeric(x) Determine if x is a numeric type.
isa(x, 'integer')
isa(x, 'uint64')
isa(x, 'float')
isa(x, 'double')
isa(x, 'single')
Determine if x is the specified numeric type.
(Examples for any integer, unsigned 64-bit integer,any floating point, double precision, and single
precision are shown here).
isreal(x) Determine if x is real or complex.
isnan(x) Determine if x is Not a Number (NaN).
isinf(x) Determine if x is infinite.
isfinite(x) Determine if x is finite.
Display Format for Numeric Values
By default, MATLAB displays numeric output as 5-digit scaled, fixed-point
values. You can change the way numeric values are displayed to any of the
following:
· 5-digit scaled fixed point, floating point, or the best of the two
· 15-digit scaled fixed point, floating point, or the best of the two
1-231 Classes (Data Types)
· A ratio of small integers
· Hexadecimal (base 16)
· Bank notation
All available formats are listed on the format reference page.
To change the numeric display setting, use either the format function or
the Preferences dialog box (accessible from the MATLAB File menu). The
format function changes the display of numeric values for the duration of a
single MATLAB session, while your Preferences settings remain active from
one session to the next. These settings affect only how numbers are displayed,not how MATLAB computes or saves them.
Display Format Examples
Here are a few examples of the various formats and the output produced from
the following two-element vector x, with components of different magnitudes.
Check the current ......
您现在查看是摘要介绍页, 详见PDF附件(2397KB,651页)。





