| Contents | Index |
• Desktop Tools and Development Environment
• Exporting to Text Data Files
• Exporting to Excel Spreadsheets
• Exporting to Scientific Data Files
• Exporting to Audio and Video
Constructing the Object with Default Property Values
Setting the Start of the Mapped Region
Identifying the Contents of the Mapped Region
Example 1 - Reading a Single Data Type
Example 2 - Formatting File Data as a Matrix
Example 3 - Reading Multiple Data Types
Example 4 - Modifying Map Parameters
Writing Matrices to a Mapped File
Selecting Appropriate Data Types
Matrix Concatenation Functions
Functions That Control Indexing Style
Using Logicals in Array Indexing
Single-Colon Indexing with Different Array Types
Data Structures Used in the Matrix
Diminishing the Size of a Matrix
Shifting the Location of Matrix Elements
Sorting the Data in Each Column
Constructing a Matrix from a Diagonal Vector
Returning a Triangular Portion of a Matrix
Concatenating Matrices Diagonally
Creating Multidimensional Arrays
Accessing Multidimensional Array Properties
Indexing Multidimensional Arrays
Reshaping Multidimensional Arrays
Computing with Multidimensional Arrays
Organizing Data in Multidimensional Arrays
Multidimensional Structure Arrays
Adding and Subtracting Matrices
Using Multithreaded Computation with Linear Algebra Functions
Using Multithreaded Computation with Systems of Linear Equations
Iterative Methods for Solving Systems of Linear Equations
Using Multithreaded Computation for Factorization
Choosing a Random Number Generator
Initializing the Generator with an Integer Seed
Initializing the Generator with a State Vector
If You Are Unable to Upgrade from Former Syntax
Functions That Do Not Support Sparse Matrices
Functions with Sparse Alternatives
Indexing in Sparse Matrix Operations
Eigenvalues and Singular Values
Triangulation Face-Vertex Format
Querying Triangulations Using TriRep
Creating Delaunay Triangulations
Triangulation of Point Sets Containing Duplicate Locations
Searching Non-Delaunay Triangulations
Interpolation with the interp Family of Functions
Interpolation with the griddedInterpolant Class
Interpolating Scattered Data Using griddata and griddatan
Interpolating Scattered Data Using the TriScatteredInterp Class
Interpolation of Complex Scattered Data
Addressing Problems in Scattered Data Interpolation
Minimizing Functions of Several Variables
Creating and Using an Output Function
Structure of the Output Function
Importing Data into the Workspace
Exporting Data from the Workspace
Example: Loading and Plotting Data
Representing Missing Data Values
Example: Moving Average Filter
Example: Removing Linear Trends from Data
Example: Using MATLAB Data Statistics
Using Data Tips to Explore Graphs
Example - Visually Exploring Demographic Statistics
Fitting Data with Curve Fitting Toolbox Functions
Example: Using Basic Fitting GUI
Linear Model with Nonpolynomial Terms
Example: Time Series Objects and Methods
Time Series Collection Constructor
Editing Data, Time, Attributes, and Events
Store Text in Character Strings
Enter Multiple Statements on One Line
Continue Long Statements on Multiple Lines
How MATLAB Recognizes Command Syntax
Calling Regular Expression Functions from MATLAB
Parsing Strings with Regular Expressions
What Is a Comma-Separated List?
Generating a Comma-Separated List
Assigning Output from a Comma-Separated List
Assigning to a Comma-Separated List
How to Use the Different Classes
• Integers
Double-Precision Floating Point
Single-Precision Floating Point
Arithmetic Operations on Floating-Point Numbers
Largest and Smallest Values for Floating-Point Classes
Accuracy of Floating-Point Data
• Display Format for Numeric Values
• Functions that Return a Logical Result
Using Logical Arrays in Conditional Statements
Using Logical Arrays in Indexing
Functions that Use Format Strings
Constructing the Formatting Operator
• Converting from Numeric to String
• Converting from String to Numeric
Access Data in a Structure Array
Generate Field Names from Variables
Access Data in Nested Structures
Access Multiple Elements of a Nonscalar Struct Array
• Ways to Organize Data in Structure Arrays
Memory Requirements for a Structure Array
Pass Contents of Cell Arrays to Functions
Preallocate Memory for a Cell Array
Multilevel Indexing to Access Parts of Cells
Maximum Length of a Function Name
The Role of Scope, Precedence, and Overloading When Creating a Function Handle
Obtaining Permissions from Class Methods
• Calling a Function By Means of Its Handle
• Preserving Data from the Workspace
• Applications of Function Handles
Example of Passing a Function Handle
Pass a Function to Another Function
Capture Data Values For Later Use By a Function
Call Functions Outside of Their Normal Scope
Save the Handle in a MAT-File for Use in a Later MATLAB Session
• Saving and Loading Function Handles
• Advanced Operations on Function Handles
Functions That Operate on Function Handles
• Description of the Map Class
Examining the Contents of the Map
• Reading and Writing Using a Key Index
• Modifying Keys and Values in the Map
• Mapping to Different Value Types
• Combining Unlike Integer Types
Combining Integer and Noninteger Data
Combining Cell Arrays with Non-Cell Arrays
Combining Single and Double Types
Combining Integer and Double Types
• General Purpose Vs. Specialized Arrays
• Desktop Tools Are Object Aware
• Getting Information About Objects
• Working with Functions in Files
• Share Data Between Workspaces
• Functions Provided By MATLAB
Constructing an Anonymous Function
Outputs from Anonymous Functions
Variable Scope in Nested Functions
Using Function Handles with Nested Functions
Support Variable Number of Inputs
Support Variable Number of Outputs
Validate Number of Function Arguments
Argument Checking in Nested Functions
Check Function Inputs with validateattributes
Input Parser Validation Functions
• Help
Help on Functions from the Help Browser
Help on Functions from the Command Window
Using Lowercase for Function Names
Getting a Function's Name and Path
A Quick Way to Examine Variables
Setting Breakpoints from the Command Line
Finding Line Numbers to Set Breakpoints
Stopping Execution on an Error or Warning
Making Sure Variable Names Are Valid
Do Not Use Function Names for Variables
Checking for Reserved Keywords
Avoid Using i and j for Variables
Avoid Overwriting Variables in Scripts
• Strings
Creating Strings with Concatenation
Comparing Methods of Concatenation
Store Arrays of Strings in a Cell Array
Adding a Folder to the Search Path
Handles to Functions Not on the Path
Making Toolbox File Changes Visible to MATLAB
Using break, continue, and return
Multiple Conditions in a case Statement
Saving Data from the Workspace
Loading Data into the Workspace
Viewing Variables in a MAT-File
• Operating System Compatibility
• Error Reporting in a MATLAB Application
Getting an Exception at the Command Line
• Capturing Information About the Error
• Warnings
• Working with Timer Object Properties
• Starting and Stopping Timers
• Creating and Executing Callback Functions
• Timer Object Execution Modes
• Deleting Timer Objects from Memory
• Finding Timer Objects in Memory
• Techniques for Improving Performance
Using Appropriate Logical Operators
Overloading Built-In Functions
Functions Are Generally Faster Than Scripts
• Strategies for Efficient Use of Memory
Ways to Reduce the Amount of Memory Required
Using Appropriate Data Storage
• Resolving "Out of Memory" Errors
• Add Help for Your Program Files
• Add Documentation to the Help Browser
Types of Documentation You Can Provide
Learning to Add Help from Examples
Summary of Creating and Installing HTML Help Files
Creating Function Reference Pages
Creating Function and Block Category Listings
MATLAB Programmer Without Object-Oriented Programming Experience
MATLAB Programmer with Object-Oriented Programming Experience
Approaches to Writing MATLAB Programs
When Should You Start Creating Object-Oriented Programs
Learning Object-Oriented Programming
Implementing the BankAccount Class
Implementing the AccountManager Class
Performing a Task with an Object
Defining the TensileData Class
Creating an Instance and Assigning Data
Restricting Properties to Specific Values
Simplifying the Interface with a Constructor
Displaying TensileData Objects
A Method to Plot Stress vs. Strain
Important Concepts Demonstrated
Why a Handle Class for Doubly Linked Lists?
Grouping Classes with Package Folders
More Information on Class Folders
How to Initialize Property Values
Assigning Property Values from Within the Constructor
Initializing Properties to Unique Values
Referencing Object Properties Using Variables
More Detailed Information On Methods
Defining Class-Related Functions
Overloading Functions and Operators
Simpler Syntax for true/false Attributes
Warnings Caused by Variable/Property Name Conflicts
Exception to Variable/Property Name Rule
Using Switch/Case Statements with Objects
New Features Introduced with Version 7.6
Common Object-Oriented Techniques
Where to Use Expressions in Class Definitions
How MATLAB Evaluates Expressions
Access to Functions Defined in Private Folders
Class Precedence and MATLAB Path
Referencing Package Members Within Packages
Referencing Package Members from Outside the Package
Behavior of MATLAB Built-In Classes
Behavior of User-Defined Classes
Syntax of Class Destructor Method
When to Define a Destructor Method
Destructors in Class Hierarchies
Restrict Explicit Object Deletion
Finding Handle Object Properties
Specifying Property Attributes
Set and Get Methods for Dependent Properties
Set and Get Method Execution and Property Events
Access Methods and Subscripted Reference and Assignment
Performing Additional Steps with Property Access Methods
Responding to Dynamic-Property Events
Defining Property Access Methods for Dynamic Properties
Dynamic Properties and ConstructOnLoad
Determining Which Method Is Invoked
Invoking Superclass Methods in Subclass Methods
Examples of Class Constructors
Initializing the Object Within a Constructor
Errors During Class Construction
Basic Structure of Constructor Methods
Rules for Naming to Avoid Conflicts
Object Scope and Anonymous Functions
Example - Class Method as a Slider Callback
Initializing Arrays of Value Objects
Initial Value of Object Properties
Initializing Arrays of Handle Objects
Referencing Property Values in Object Arrays
Object Arrays with Dynamic Properties
Converting to the Dominant Class
Implementing Converter Methods
What You Need to Know to Use Events
Defining Listener Callback Functions
Property Event and Listener Classes
Aborting Set When Value Does Not Change
Access Fully Commented Example Code
Techniques Demonstrated in This Example
Methods Inherited from Handle Class
Using the fcneval and fcnview Classes
Implementing the UpdateGraph Event and Listener
Implementing the PostSet Property Event and Listener
Enabling and Disabling the Listeners
Implementation and Interface Inheritance
Initializing Superclasses from Subclasses
Constructor Arguments and Object Initialization
Call Only Direct Superclass from Constructor
Sequence of Constructor Calls in a Class Hierarchy
Using a Subclass to Create an Alias for an Existing Class
Modifying Superclass Properties
Private Local Property Takes Precedence in Method
Why Control Allowed Subclasses
Define a Sealed Hierarchy of Classes
Applications for Access Control Lists
Specify Access to Class Members
Abstract Methods with Access Lists
Defining Handle-Compatible Classes
Subclassing Handle-Compatible Classes
Methods for Handle Compatible Classes
Handle-Compatible Classes and Heterogeneous Arrays
Behavior of Built-In Functions with Subclass Objects
Example - A Class to Manage uint8 Data
Example - Adding Properties to a Built-In Subclass
Example - A Class to Represent Hardware
Interfaces and Abstract Classes
Example - Interface for Classes Implementing Graphs
When to Modify Object Saving and Loading
Processing Objects During Load
Avoiding Property Initialization Order Dependency
When to Use Transient Properties
Calling Constructor When Loading
Defining Methods in Enumeration Classes
Defining Properties in Enumeration Classes
Restrictions Applied to Enumeration Classes
Techniques for Defining Enumerations
Why Derive Enumeration Class from Built-In Classes
Superclass Constructor Returns Underlying Value
Selecting Handle- or Value-Based Enumerations
Value-Based Enumeration Classes
Handle-Based Enumeration Classes
Example - Using Enumerations to Represent a State
Built-In and Value-Based Enumeration Classes
Simple and Handle-Based Enumeration Classes
What Causes Loading as a Struct Instead of an Object
Setting Constant Property Default
Metaclass EnumeratedValues Property
Find Class Members with Attribute Settings
Example - Find Properties with Specific Attributes
Which Methods Control Which Behaviors
Overloading and Overriding Functions and Methods
When to Overload MATLAB Functions
Caution When Overloading MATLAB Functions
Default Indexed Reference and Assignment
subsref and subsasgn Within Class Methods - Built-In Called
Understanding Indexed Reference
Avoid Overriding Access Attributes
Understanding Indexed Assignment
A Class with Modified Indexing
Defining end Indexing for an Object
MATLAB Operators and Associated Functions
Summary of the DocPolynom Class
The DocPolynom Constructor Method
Removing Irrelevant Coefficients
Converting DocPolynom Objects to Other Types
Defining Arithmetic Operators for DocPolynom
Overloading MATLAB Functions for the DocPolynom Class
Designing a Class for Financial Assets
The DocAsset Constructor Method
Designing a Class for Stock Assets
Designing a Class for Bond Assets
Designing a Class for Savings Assets
Summary of the DocSavings Class
Designing the DocPortfolio Class
Summary of the DocPortfolio Class
• Graphics
Plotting Tools Interface Overview
Accessing Object Properties with the Property Inspector
Identifying Workspace Data to Plot
Data Sources for Multiobject Graphs
Using Functions to Edit Graphs
Cutting, Copying, and Pasting Plot Objects
Undo/Redo - Eliminating Mistakes
Saving to a Different Format - Exporting Figures
Generating a MATLAB File to Recreate a Graph
Colors, Line Styles, and Markers
Specifying the Color and Size of Lines
Adding Plots to an Existing Graph
Line Styles for Black and White Output
Combining Linear and Logarithmic Axes
Example - Specifying Ticks and Tick Labels
Displaying Multiple Plots per Figure
Display Style - Datatip or Cursor Window
Selection Style - Select Data Points or Interpolate Points on Graph
Exporting Data Value to Workspace Variable
Rotation Style for Complex Graphs
Undo/Redo - Eliminating Mistakes
Example - Programming the Mouse Scroll Wheel to Explore Graphics in Figures
Enclosing Regions of a Graph in a Rectangle or an Ellipse
Pinning - Attaching to a Point in the Graph
Example - Vertical Distribute, Horizontal Align
Snap to Grid - Aligning Objects on a Grid
Using the Title Option on the Insert Menu
Using the Property Editor to Add a Title
Using the Label Options on the Insert Menu
Using the Property Editor to Add Axis Labels
Creating Text Annotations with the text or gtext Function
Mathematical Symbols, Greek Letters, and TeX Characters
Using Character and Numeric Variables in Text
Example - Using LaTeX to Format Math Equations
Editing Arrows and Line Annotations
Coloring 2-D Bars According to Height
Coloring 3-D Bars According to Height
Stacked Bar Graphs to Show Contributing Amounts
Overlaying Other Plots on Bar Graphs
Comparing Data Sets with Area Graphs
Removing a Piece from a Pie Chart
Histograms in Cartesian Coordinates
Histograms in Polar Coordinates
Using Data Cursors with Histograms
Combining Stem Plots with Line Plots
Three-Dimensional Quiver Plots
Changing the Offset of a Contour
Displaying Contours in Polar Coordinates
Example - Visualizing an FFT as a Movie
Updating Plot Object Axis and Color Data
Functions for Reading, Writing, and Displaying Images
8-Bit and 16-Bit Intensity Images
Mathematical Operations Support for uint8 and uint16
Other 8-Bit and 16-Bit Array Support
Converting an 8-Bit RGB Image to Grayscale
Summary of Image Types and Numeric Classes
Subsetting a Graphics Image (Cropping)
Obtaining Information About Graphics Files
Controlling Aspect Ratio and Display Size
Additional Techniques for Fast Image Updating
Specifying Parameters and Options
Default Settings and How to Change Them
Exporting to the Windows or Macintosh Clipboard
Printing with a Specific Paper Size
Exporting in a Specific Graphics Format
Exporting in EPS Format with a TIFF Preview
Exporting a Figure to the Clipboard
Setting the Figure Size and Position
Setting the Paper Size or Type
Setting the Axes Ticks and Limits
Setting Line and Text Characteristics
Setting the Line and Text Color
Specifying a Colorspace for Printing and Exporting
Excluding User Interface Controls form Printed Output
Frequently Used Graphics Formats
Factors to Consider in Choosing a Format
Properties Affected by Choice of Format
Impact of Rendering Method on the Output
Description of Selected Graphics Formats
How to Specify a Format for Exporting
Factors to Consider in Choosing a Driver
How to Specify the Printer Driver to Use
Information on Specific Graphics Objects
Figures Used for Graphing Data
Root Object - The Figure Parent
Example - Creating Core Graphics Objects
High-Level Versus Low-Level Functions
Identifying Plot Objects Programmatically
Plot Objects and Backward Compatibility
Changing the Size of Data Variables
Example - Enclosing Subplots with an Annotation Rectangle
Order Dependence of Setting Property Values
Properties Common to All Objects
How MATLAB Searches for Default Values
Examples - Setting Default Line Styles
The Current Figure, Axes, and Object
Searching for Objects by Property Values - findobj
Specifying the Target for Graphics Output
Preparing Figures and Axes for Graphics
Targeting Graphics Output with newplot
Quitting the MATLAB Environment
Errors in the Close Request Function
Overriding the Close Request Function
Redefining the CloseRequestFcn
Example - Translating Grouped Objects
Properties for Controlling Legend Content
Example - Excluding a Particular Object From a Legend
Example - One Legend Entry for a Group of Objects
Example - Showing Children of Group Objects in Legend
Example - Grouping Objects to Reduce the Legend Entries
User Interface Object Callbacks
Why Use Function Handle Callbacks
Example - Using Function Handles in GUIs
General Performance Guidelines
Specify Axes with Plotting Function for Better Performance
Performance of Bit-Mapped Images
Performance of Surface Objects
Figure Properties That Affect Docking
Example - Specifying Figure Position
Specifying the Figure Colormap
Creating Axes with Specific Characteristics
Using OuterPosition as the ActivePositionProperty
ActivePositionProperty = OuterPosition
ActivePositionProperty = Position
Multiple Axes for Different Scaling
Basic 3-D Plotting: The plot3 function
Functions for Plotting Data Grids
Functions for Gridding and Interpolating Data
Visualizing Functions of Two Variables
Surface Plots of Nonuniformly Sampled Data
Indexed Color Surfaces - Direct and Scaled Color Mapping
Example - Mapping Surface Curvature to Color
Move Camera Horizontally/Vertically
Move Camera Forward and Backward
Defining the Camera Path as a Stream Line
Moving In and Out on the Scene
Making the Scene Larger or Smaller
Rotation Without Resizing of Graphics Objects
Rotation About the Viewing Axis
Projection Types and Camera Location
Example - axis Command Options
Additional Commands for Setting Aspect Ratio
Default Aspect Ratio Selection
Effects of Setting Aspect Ratio Properties
Example - Displaying Cross-Sections of Surfaces
Example - Displaying Real Objects
Properties That Affect Lighting
Positioning Lights in Data Space
Example - A Transparent Isosurface
Mapping Alpha Data to the Alphamap
Example - Mapping Data to Color or Transparency
Example - Modifying the Alphamap
Behavior of the patch Function
Handling Mixed Data Specification
Coloring Edges with Shared Vertices
Interpolating in Indexed Color Versus Truecolor
Selecting Visualization Techniques
Steps to Create a Volume Visualization
Volume Visualization Functions
Example - Ways to Display MRI Data
Example - Adding Isocaps to an Isosurface
Using Scalar Techniques with Vector Data
Specifying Starting Points for Stream Plots
Accessing Subregions of Volume Data
1. Determine the Range of the Coordinates
2. Add Slice Planes for Visual Context
3. Add Contour Lines to the Slice Planes
4. Define the Starting Points for the Stream Lines
1. Select a Subset of Data to Plot
2. Calculate Curl Angular Velocity and Wind Speed
4. Define the View and Add Lighting
1. Load Data and Calculate Required Values
3. Add Contour Lines to Slice Planes
1. Specify Starting Points of the Data Range to Plot
2. Create Stream Lines to Indicate Particle Paths
4. Calculate the Stream Particle Vertices
2. Add Isocaps to the Isosurface
• Creating Graphical User Interfaces
• About the Simple GUIDE GUI Example
• Lay Out the Simple GUI in GUIDE
• Program the Simple GUIDE GUI
• Use the Completed Simple GUIDE GUI
Create the Simple Programmatic GUI Code File
• Lay Out the Simple Programmatic GUI
• Code the Simple Programmatic GUI
• Use the Completed Simple Programmatic GUI
A Working GUI with Many Components
Add Components to the GUIDE Layout Area
Define User Interface Controls
Define Panels and Button Groups
• Designing for Cross-Platform Compatibility
• Default Callback Properties in GUIDE
• Customizing Callbacks in GUIDE
• Add Code for Components in Callbacks
• Making Multiple GUIs Work Together
Example - Manipulating a Modal Dialog Box for User Input
Example - Individual GUIDE GUIs Cooperating as Icon Manipulation Tools
• GUI for Animating a 3-D View (GUIDE)
About the 3-D Animation Example
View and Run the 3-D Globe GUI
• GUI to Interactively Explore Data in a Table (GUIDE)
• List Box Directory Reader (GUIDE)
• Access Workspace Variables from a List Box (GUIDE)
• A GUI to Set Simulink Model Parameters (GUIDE)
About the Simulink Model Parameters Example
View and Run the Simulink Parameters GUI
How to Use the Simulink Parameters GUI
Program the Slider and Edit Text Components
• An Address Book Reader (GUIDE)
About the Address Book Reader Example
View and Run the Address Book Reader GUI
Run the Address Book Reader GUI
Load an Address Book Into the Reader
The Contact Phone Number Callback
Page Through Address Book - Prev/Next
• Use a Modal Dialog Box to Confirm an Operation (GUIDE)
About the Modal Dialog Example
View and Run the Modal Dialog Box GUIs
Set Up the Close Confirmation Dialog
Set Up the GUI with the Close Button
• Time Data Updates from a GUI (GUIDE)
• Create and Run a Programmatic GUI
Create Figures for Programmatic GUIs
• Add Components to a Programmatic GUI
• Compose and Code GUIs with Interactive Tools
• Set Tab Order in a Programmatic GUI
• Create Menus for a Programmatic GUI
• Create Toolbars for Programmatic GUIs
• Design Programmatic GUIs for Cross-Platform Compatibility
• Initialize a Programmatic GUI
• Examples: Program GUI Components
• Share Data Among a GUI's Callbacks
• GUI with Axes, Menu, and Toolbar
About the Axes, Menu, and Toolbar Example
View and Run the AxesMenuToolbar Code
Generate the Graphing Commands and Data
• GUI that Displays and Graphs Tabular Data
View and Run the tableplot Code
Set Up and Interact with the uitable
Handle Graphics Property Browser
Why Write Custom Applications?
Exchanging Data Files Between Platforms
Overview of matimport.c Example
Declare Variables for External Data
Read External Data into mxArray Data
Creating a MAT-File in Fortran
Examples for Working with mxArrays
Building on Windows Operating Systems
Deploying MAT-File Applications
Limitations to Shared Library Support
Troubleshooting Shared Library Applications
Examples of Passing Data to Shared Libraries
Manually Converting Data Passed to Functions
Constructing a libpointer Object
Creating a Pointer to a Primitive Type
Creating a Pointer to a Structure
Passing a Pointer to the First Element of an Array
Putting a String into a Void Pointer
Memory Allocation for an External Library
Working with Structures Examples
Example of Passing a MATLAB Structure
Using the Structure as an Object
Introduction to Source MEX-Files
Overview of Creating a Binary MEX-File
Using Help Files with MEX-Files
Workspace for MEX-File Functions
Selecting a Compiler on Windows Platforms
Selecting a Compiler on UNIX Platforms
Overview of Building the timestwo MEX-File
Understanding MEX-File Problems
Compiler and Platform-Specific Issues
Custom Building on UNIX Systems
Custom Building on Windows Systems
Creating a MEX-File Using LAPACK and BLAS Functions
Preserving Input Values from Modification
Passing Arguments to Fortran Functions from C/C++ Programs
Passing Arguments to Fortran Functions from Fortran Programs
Handling Complex Numbers in LAPACK and BLAS Functions
Modifying the Function Name on UNIX Systems
MEX Uses 32-Bit API by Default
How to Upgrade MEX-Files to Use the 64-Bit API
Passing Two or More Inputs or Outputs
Passing Structures and Cell Arrays
Handling 8-, 16-, and 32-Bit Data
Manipulating Multidimensional Numerical Arrays
Calling Functions from C/C++ MEX-Files
Using C++ Features in MEX-Files
Debugging on the Microsoft Windows Platforms
Building Cross-Platform Applications
Specifying Constant Literal Values
Replacing fseek and ftell with 64-Bit Functions
Determining the Size of an Open File
Determining the Size of a Closed File
Using the Fortran %val Construct
Passing Two or More Inputs or Outputs
Calling Functions from Fortran MEX-Files
Debugging on Microsoft Windows Platforms
Building Cross-Platform Applications
What You Need to Build Engine Applications
Calling MATLAB Software from a C Application
Calling MATLAB Software from a C++ Application
Calling MATLAB Software from a Fortran Application
Attaching to an Existing MATLAB Session
Building and Running Engine Applications on Windows Operating Systems
Windows Engine Example engwindemo
Building and Running Engine Applications on UNIX Operating Systems
Files Required by Engine Applications
Debugging MATLAB Functions Used in Engine Applications
Benefits of the MATLAB Java Interface
Who Should Use the MATLAB Java Interface
To Learn More About Java Programming Language
Platform Support for JVM Software
Making Java Classes Available in MATLAB Workspace
Loading Java Class Definitions
Locating Native Method Libraries
Java Classes Contained in a JAR File
Saving and Loading Java Objects to MAT-Files
Finding the Public Data Fields of an Object
Accessing Private and Public Data
Determining the Class of an Object
Invoking Static Methods on Java Classes
Obtaining Information About Methods
Java Methods That Affect MATLAB Commands
How MATLAB Software Handles Undefined Methods
How MATLAB Software Handles Java Exceptions
Method Execution in MATLAB Software
How MATLAB Software Represents the Java Array
Creating an Array of Objects in MATLAB Software
Accessing Elements of a Java Array
Creating a New Array Reference
Creating a Copy of a Java Array
Conversion of MATLAB Argument Data
Passing Data to Overloaded Methods
Conversion of Java Return Types
Converting Objects to MATLAB Types
Description of Function phonebook
Description of Function pb_lookup
Description of Function pb_add
Description of Function pb_remove
Description of Function pb_change
Description of Function pb_listall
Description of Function pb_display
Description of Function pb_keyfilter
Benefits of the MATLAB .NET Interface
Why Use the MATLAB .NET Interface?
What's the Difference Between the MATLAB .NET Interface and MATLAB Builder NE?
Using a .NET assembly in MATLAB
To Learn More About the .NET Framework
Loading .NET Assemblies into MATLAB
Building a .NET Application for MATLAB Examples
What Classes Are in a .NET Assembly?
Using the delete Function on a .NET Object
How MATLAB Maps C# Property and Field Access Modifiers
Calling .NET Methods with Optional Arguments
Calling .NET Extension Methods
Call .NET Properties That Take an Argument
How MATLAB Represents .NET Operators
Limitations to Support of .NET Methods
Limitations to Support of .NET Events
Handling Data Returned from a .NET Object
Accessing .NET Array Elements in MATLAB
Converting .NET Arrays to Cell Arrays
Limitations to Support of .NET Arrays
Call a .NET Delegate in MATLAB
Create a Delegate from a .NET Object Method
Create a Delegate Instance Bound to a .NET Method
Use .NET Delegates With the out and ref Type Arguments
Combine and Remove .NET Delegates
Calling a .NET Method Asynchronously
Limitations to Support of .NET Delegates
Iterate Through a .NET Enumeration
Use .NET Enumerations to Test for Conditions
Example - Read Special System Folder Path
Use Bit Flags with .NET Enumerations
Limitations to Support of .NET Enumerations
Work with Microsoft Word Documents Using .NET
Accessing Items in a .NET Collection
Convert a .NET Collection to a MATLAB Array
Create .NET Array of Generic Type
Display .NET Generic Methods Using Reflection
Create .NET Object From Constructor
View Information About .NET Object
Introduction to .NET Data Types
Use .NET Numeric Types in MATLAB
Do Not Use ClassName.PropertyName Syntax for Static Properties
Call .NET Methods That Use the out Keyword
Call .NET Methods That Use the ref Keyword
Call .NET Methods That Use the params Keyword
Create a Cell Array for Each System.Object
Create MATLAB Variables from the .NET Data
Call MATLAB Functions with MATLAB Variables
The MATLAB COM Automation Server
Registering Controls and Servers
Overview of MATLAB COM Client Examples
Example - Using Internet Explorer Program in a MATLAB Figure
Example - Grid ActiveX Control in a Figure
Example - Reading Excel Spreadsheet Data
MATLAB Client and In-Process Server
MATLAB Client and Out-of-Process Server
COM Implementations Supported by MATLAB Software
Client Application and MATLAB Automation Server
Client Application and MATLAB Engine Server
Identifying Objects and Interfaces
Setting the Value of a Property
Using Enumerated Values for Properties
Properties That Take Arguments
Exceptions to Using Implicit Syntax
Specifying Enumerated Parameters
Returning Multiple Output Arguments
Argument Callouts in Error Messages
Functions for Working with Events
Responding to Events - an Overview
Responding to Events - Examples
Writing Event Handlers as MATLAB File Subfunctions
Releasing COM Interfaces and Objects
Handling Data from a COM Object
Passing MATLAB Data to ActiveX Objects
Passing MATLAB SAFEARRAY to COM Object
Reading SAFEARRAY from a COM Object in MATLAB Applications
Displaying MATLAB Syntax for COM Objects
Using a MATLAB Application as an Automation Client
Connecting to an Existing Excel Application
Running a Macro in an Excel Server Application
Using Microsoft Forms 2.0 Controls
Using MATLAB Application as a DCOM Client
MATLAB COM Support Limitations
Connecting to an Existing MATLAB Server
Executing Commands in the MATLAB Server
Exchanging Data with the Server
Terminating the Server Process
Specifying a Shared or Dedicated Server
Using MATLAB Application as a DCOM Server
Example - Viewing Methods from a Visual Basic .NET Client
Example - Calling MATLAB Software from a Web Application
Example - Calling MATLAB Software from a C# Client
What You Need to Use Web Services with MATLAB
Typical Applications Using Web Services with MATLAB
How MATLAB Accesses Web Services
Example - createClassFromWsdl Function
Tools for Creating Web Services
Supported Serial Port Interface Standards
Using the Examples with Your Device
The Serial Port Interface Standard
Connecting Two Devices with a Serial Cable
Serial Port Signals and Pin Assignments
Finding Serial Port Information for Your Platform
Using Virtual USB Serial Ports
Configuring and Returning Properties
Configuring Properties During Object Creation
The Serial Port Object Display
Creating an Array of Serial Port Objects
Example - Introduction to Writing and Reading Data
Controlling Access to the MATLAB Command Line
Example - Writing and Reading Text Data
Example - Parsing Input Data Using textscan
Example - Introduction to Events and Callbacks
Event Types and Callback Properties
Responding To Event Information
Creating and Executing Callback Functions
Enabling Callback Functions After They Error
Example - Using Events and Callbacks
Signaling the Presence of Connected Devices
Controlling the Flow of Data: Handshaking
Example: Introduction to Recording Information
Creating Multiple Record Files
Example: Recording Information to Disk
Using Serial Port Objects on Different Platforms
• Examples
| On this page… |
|---|
Low-Level Functions for Exporting Data Overwriting or Appending to an Existing File Creating a File for Use on a Different System |
Low-level file I/O functions allow the most direct control over reading or writing data to a file. However, these functions require that you specify more detailed information about your file than the easier-to-use high-level functions. For a complete list of high-level functions and the file formats they support, see Supported File Formats.
If the high-level functions cannot export your data, use one of the following:
fprintf, which writes formatted data to a text or ASCII file; that is, a file you can view in a text editor or import into a spreadsheet. For more information, see Writing to Text Data Files with Low-Level I/O.
fwrite, which writes a stream of binary data to a file. For more information, see Writing Binary Data to a File.
Note The low-level file I/O functions are based on functions in the ANSI Standard C Library. However, MATLAB includes vectorized versions of the functions, to read and write data in an array with minimal control loops. |
Use the fwrite function to export a stream of binary data to a file. As with any of the low-level I/O functions, before writing, open or create a file with fopen, and obtain a file identifier. When you finish processing a file, close it with fclose.
By default, fwrite writes values from an array in column order as 8-bit unsigned integers (uint8).
For example, create a file nine.bin with the integers from 1 to 9:
fid = fopen('nine.bin','w');
fwrite(fid, [1:9]);
fclose(fid);If the values in your matrix are not 8-bit unsigned integers, specify the precision of the values. For example, to create a file with double-precision values:
mydata = [pi, 42, 1/3];
fid = fopen('double.bin','w');
fwrite(fid, mydata, 'double');
fclose(fid);For a complete list of precision descriptions, see the fwrite function reference page.
By default, fopen opens files with read access. To change the type of file access, use the permission string in the call to fopen. Possible permission strings include:
r for reading
w for writing, discarding any existing contents of the file
a for appending to the end of an existing file
To open a file for both reading and writing or appending, attach a plus sign to the permission, such as 'w+' or 'a+'. For a complete list of permission values, see the fopen reference page.
Note If you open a file for both reading and writing, you must call fseek or frewind between read and write operations. |
When you open a file, MATLAB creates a pointer to indicate the current position within the file. To read or write selected portions of data, move this pointer to any location in the file. For more information, see Moving within a File.
Create a file magic4.bin as follows, specifying permission to write and read:
fid = fopen('changing.bin','w+');
fwrite(fid,magic(4));
The original magic(4) matrix is:
16 2 3 13
5 11 10 8
9 7 6 12
4 14 15 1
The file contains 16 bytes, 1 for each value in the matrix. Replace the second set of four values (the values in the second column of the matrix) with the vector [44 44 44 44]:
% fseek to the fourth byte after the beginning of the file fseek(fid, 4, 'bof'); %write the four values fwrite(fid,[44 44 44 44]); % read the results from the file into a 4-by-4 matrix frewind(fid); newdata = fread(fid, [4,4]) % close the file fclose(fid);
The newdata in the file changing.bin is:
16 44 3 13
5 44 10 8
9 44 6 12
4 44 15 1
Add the values [55 55 55 55] to the end of the changing.bin file created in the previous example.
% open the file to append and read
fid = fopen('changing.bin','a+');
% write values at end of file
fwrite(fid,[55 55 55 55]);
% read the results from the file into a 4-by-5 matrix
frewind(fid);
appended = fread(fid, [4,5])
% close the file
fclose(fid);The appended data in the file changing.bin is:
16 44 3 13 55
5 44 10 8 55
9 44 6 12 55
4 44 15 1 55
Different operating systems store information differently at the byte or bit level:
Big-endian systems store bytes starting with the largest address in memory (that is, they start with the big end).
Little-endian systems store bytes starting with the smallest address (the little end).
Windows systems use little-endian byte ordering, and UNIX systems use big-endian byte ordering.
To create a file for use on an opposite-endian system, specify the byte ordering for the target system. You can specify the ordering in the call to open the file, or in the call to write the file.
For example, to create a file named myfile.bin on a big-endian system for use on a little-endian system, use one (or both) of the following commands:
Open the file with
fid = fopen('myfile.bin', 'w', 'l')Write the file with
fwrite(fid, mydata, precision, 'l')
where 'l' indicates little-endian ordering.
If you are not sure which byte ordering your system uses, call the computer function:
[cinfo, maxsize, ordering] = computer
The returned ordering is 'L' for little-endian systems, or 'B' for big-endian systems.
Encoding schemes support the characters required for particular alphabets, such as those for Japanese or European languages. Common encoding schemes include US-ASCII or UTF-8.
The encoding scheme determines the number of bytes required to read or write char values. For example, US-ASCII characters always use 1 byte, but UTF-8 characters use up to 4 bytes. MATLAB automatically processes the required number of bytes for each char value based on the specified encoding scheme. However, if you specify a uchar precision, MATLAB processes each byte as uint8, regardless of the specified encoding.
If you do not specify an encoding scheme, fopen opens files for processing using the default encoding for your system. To determine the default, open a file, and call fopen again with the syntax:
[filename, permission, machineformat, encoding] = fopen(fid);
If you specify an encoding scheme when you open a file, the following functions apply that scheme: fscanf, fprintf, fgetl, fgets, fread, and fwrite.
For a complete list of supported encoding schemes, and the syntax for specifying the encoding, see the fopen reference page.
The available precision values for fwrite do not explicitly support complex numbers. To store complex numbers in a file, separate the real and imaginary components and write them separately to the file.
After separating the values, write all real components followed by all imaginary components, or interleave the components. Use the method that allows you to read the data in your target application.
For example, consider the following set of complex numbers:
nrows = 5; ncols = 5; z = complex(rand(nrows, ncols), rand(nrows, ncols)); % Divide into real and imaginary components z_real = real(z); z_imag = imag(z);
One approach: write all the real components, followed by all the imaginary components:
adjacent = [z_real z_imag];
fid = fopen('complex_adj.bin', 'w');
fwrite(fid, adjacent, 'double');
fclose(fid);
% To read these values back in, so that:
% same_real = z_real
% same_imag = z_imag
% same_z = z
fid = fopen('complex_adj.bin');
same_real = fread(fid, [nrows, ncols], 'double');
same_imag = fread(fid, [nrows, ncols], 'double');
fclose(fid);
same_z = complex(same_real, same_imag);An alternate approach: interleave the real and imaginary components for each value. fwrite writes values in column order, so build an array that combines the real and imaginary parts by alternating rows.
% Preallocate the interleaved array
interleaved = zeros(nrows*2, ncols);
% Alternate real and imaginary data
newrow = 1;
for row = 1:nrows
interleaved(newrow,:) = z_real(row,:);
interleaved(newrow + 1,:) = z_imag(row,:);
newrow = newrow + 2;
end
% Write the interleaved values
fid = fopen('complex_int.bin','w');
fwrite(fid, interleaved, 'double');
fclose(fid);
% To read these values back in, so that:
% same_real = z_real
% same_imag = z_imag
% same_z = z
% Use the skip parameter in fread (double = 8 bytes)
fid = fopen('complex_int.bin');
same_real = fread(fid, [nrows, ncols], 'double', 8);
% Return to the first imaginary value in the file
fseek(fid, 8, 'bof');
same_imag = fread(fid, [nrows, ncols], 'double', 8);
fclose(fid);
same_z = complex(same_real, same_imag);
![]() | Exporting to Audio and Video | Creating Temporary Files | ![]() |

Includes the most popular MATLAB recorded presentations with Q&A sessions led by MATLAB experts.
| © 1984-2012- The MathWorks, Inc. - Site Help - Patents - Trademarks - Privacy Policy - Preventing Piracy - RSS |


