Programming and Data Types    

M-File Programming

MATLAB Programming: A Quick Start

Kinds of M-Files

What's in an M-File?

Providing Help for Your Programs

Creating M-Files: Accessing Text Editors

Scripts

Simple Script Example

Functions

Simple Function Example

Basic Parts of a Function M-File

How Functions Work

Checking the Number of Function Arguments

Passing Variable Numbers of Arguments

Subfunctions

Private Functions

Variables

Naming Variables

Local Variables

Global Variables

Persistent Variables

Special Values

Data Types

Operators

Arithmetic Operators

Relational Operators

Logical Operators

Operator Precedence

Keywords

Flow Control

if, else, and elseif

switch

while

for

continue

break

try ... catch

return

String Evaluation

eval

feval

Dates and Times

Date Formats

Current Date and Time

Calling Functions

Function Syntax

Command Syntax

Passing Arguments

Obtaining User Input

Prompting for Keyboard Input

Pausing During Execution

Subscripting and Indexing

Subscripting

Advanced Indexing

Empty Matrices

Operating on an Empty Matrix

Using Empty Matrices with If or While

Errors and Warnings

Checking for Errors with try-catch

Handling and Recovering from an Error

Warnings

Message Identifiers

Using Message Identifiers with lasterr

Warning Control

Debugging Errors and Warnings

Shell Escape Functions

Using MATLAB Timers

Creating and Deleting Timer Objects

Timer Object Properties

Starting and Stopping Timers

Timer Object Execution Modes

Creating Timer Callback Functions

Character Arrays (Strings)

Function Summary

Character Arrays

Creating Character Arrays

Creating Two-Dimensional Character Arrays

Converting Characters to Numeric Values

Cell Arrays of Strings

Converting to a Cell Array of Strings

String/Numeric Conversion

String Comparisons

Comparing Strings For Equality

Comparing for Equality Using Operators

Categorizing Characters Within a String

Searching and Replacing

Regular Expressions

Metacharacters

Logical Operators

Quantifiers

Searching with Tokens

Numeric/String Conversion

Array/String Conversion

Multidimensional Arrays

Function Summary

Multidimensional Arrays

Creating Multidimensional Arrays

Accessing Multidimensional Array Properties

Indexing

Reshaping

Permuting Array Dimensions

Computing with Multidimensional Arrays

Operating on Vectors

Operating Element-by-Element

Operating on Planes and Matrices

Organizing Data in Multidimensional Arrays

Multidimensional Cell Arrays

Multidimensional Structure Arrays

Applying Functions to Multidimensional Structure Arrays

Structures and Cell Arrays

Function Summary

Structures

Building Structure Arrays

Accessing Data in Structure Arrays

Finding the size of Structure Arrays

Adding Fields to Structures

Deleting Fields from Structures

Applying Functions and Operators

Writing Functions to Operate on Structures

Organizing Data in Structure Arrays

Nesting Structures

Cell Arrays

Creating Cell Arrays

Obtaining Data from Cell Arrays

Deleting Cells

Reshaping Cell Arrays

Replacing Lists of Variables with Cell Arrays

Applying Functions and Operators

Organizing Data in Cell Arrays

Nesting Cell Arrays

Converting Between Cell and Numeric Arrays

Cell Arrays of Structures

Function Handles

Overview

Benefits of Using Function Handles

A Simple Function Handle

Constructing a Function Handle

Maximum Length of a Function Name

Evaluating a Function Through Its Handle

Function Evaluation and Overloading

Examples of Function Handle Evaluation

Displaying Function Handle Information

Fields Returned by the Functions Command

Types of Function Handles

Function Handle Operations

Converting Function Handles to Function Names

Converting Function Names to Function Handles

Testing for Data Type

Testing for Equality

Saving and Loading Function Handles

Handling Error Conditions

Handles to Nonexistent Functions

Including Path In the Function Handle Constructor

Evaluating a Nonscalar Function Handle

Historical Note - Evaluating Function Names

MATLAB Classes and Objects

Classes and Objects: An Overview

Features of Object-Oriented Programming

MATLAB Data Class Hierarchy

Creating Objects

Invoking Methods on Objects

Private Methods

Helper Functions

Debugging Class Methods

Setting Up Class Directories

Data Structure

Tips for C++ and Java Programmers

Designing User Classes in MATLAB

The MATLAB Canonical Class

The Class Constructor Method

Examples of Constructor Methods

Identifying Objects Outside the Class Directory

The display Method

Accessing Object Data

The set and get Methods

Indexed Reference Using subsref and subsasgn

Handling Subscripted Reference

Handling Subscripted Assignment

Object Indexing Within Methods

Defining end Indexing for an Object

Indexing an Object with Another Object

Converter Methods

Overloading Operators and Functions

Overloading Operators

Overloading Functions

Example -- A Polynomial Class

Polynom Data Structure

Polynom Methods

The Polynom Constructor Method

Converter Methods for the Polynom Class

The Polynom display Method

The Polynom subsref Method

Overloading Arithmetic Operators for polynom

Overloading Functions for the Polynom Class

Listing Class Methods

Building on Other Classes

Simple Inheritance

Multiple Inheritance

Aggregation

Example - Assets and Asset Subclasses

Inheritance Model for the Asset Class

Asset Class Design

Other Asset Methods

The Asset Constructor Method

The Asset get Method

The Asset set Method

The Asset subsref Method

The Asset subsasgn Method

The Asset display Method

The Asset fieldcount Method

Designing the Stock Class

The Stock Constructor Method

The Stock get Method

The Stock set Method

The Stock subsref Method

The Stock subsasgn Method

The Stock display Method

Example -- The Portfolio Container

Designing the Portfolio Class

The Portfolio Constructor Method

The Portfolio display Method

The Portfolio pie3 Method

Creating a Portfolio

Saving and Loading Objects

Modifying Objects During Save or Load

Example -- Defining saveobj and loadobj for Portfolio

Summary of Code Changes

The saveobj Method

The loadobj Method

Changing the Portfolio Constructor

The Portfolio subsref Method

Object Precedence

Specifying Precedence of User-Defined Classes

How MATLAB Determines Which Method to Call

Selecting a Method

Querying Which Method MATLAB Will Call

Maximizing MATLAB Performance

Techniques for Improving Performance

Analyzing Your Program's Performance

Vectorizing Loops

Preallocating Arrays

Other Ways to Speed Up Performance

Performance Acceleration

What MATLAB Accelerates

What MATLAB Does Not Accelerate

How Vectorizing and Preallocation Fit In

What to Avoid When Running MATLAB

Operating System Considerations

Sample Accelerated Programs

Program 1 -- Bayes' Rule

Program 2 -- Relaxation Algorithm

Program 3a -- Vector Comparison, with Loop

Program 3b -- Vector Comparison, Vectorized

Program 4 -- Tic-Tac-Toe

Measuring Performance

What Is Profiling?

The Profiler

The profile Function

Making Efficient Use of Memory

Memory Management Functions

Ways to Conserve Memory

"Out of Memory" Errors

Platform-Specific Memory Topics

MATLAB Programming Tips

Command and Function Syntax

Syntax Help

Command and Function Syntaxes

Command Line Continuation

Completing Commands Using the Tab Key

Recalling Commands

Clearing Commands

Suppressing Output to the Screen

Help

Using the Help Browser

Help on Functions from the Help Browser

Help on Functions from the Command Window

Topical Help

Paged Output

Writing Your Own Help

Help for Subfunctions and Private Functions

Help for Methods and Overloaded Functions

Development Environment

Workspace Browser

Using the Find and Replace Utility

Commenting Out a Block of Code

Creating M-Files from Command History

Editing M-Files in EMACS

M-File Functions

M-File Structure

Using Lowercase for Function Names

Getting a Function's Name and Path

What M-Files Does a Function Use?

Dependent Functions, Built-Ins, Classes

Function Arguments

Getting the Input and Output Arguments

Variable Numbers of Arguments

String or Numeric Arguments

Passing Arguments in a Structure

Passing Arguments in a Cell Array

Program Development

Planning the Program

Using Pseudo-Code

Selecting the Right Data Structures

General Coding Practices

Naming a Function Uniquely

The Importance of Comments

Coding in Steps

Making Modifications in Steps

Functions with One Calling Function

Testing the Final Program

Debugging

The MATLAB Debug Functions

More Debug Functions

The MATLAB Graphical Debugger

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

Locating an Error from the Error Message

Using Warnings to Help Debug

Making Code Execution Visible

Debugging Scripts

Variables

Rules for Variable Names

Making Sure Variable Names Are Valid

Don't Use Function Names for Variables

Checking for Reserved Keywords

Avoid Using i and j for Variables

Avoid Overwriting Variables in Scripts

Persistent Variables

Protecting Persistent Variables

Global Variables

Strings

Creating Strings with Concatenation

Comparing Methods of Concatenation

Store Arrays of Strings in a Cell Array

Search and Replace Using Regular Expressions

Converting Between Strings and Cell Arrays

Evaluating Expressions

Find Alternatives to Using eval

Assigning to a Series of Variables

Short-Circuit Logical Operators

Changing the Counter Variable within a for Loop

MATLAB Path

Precedence Rules

File Precedence

Adding a Directory to the Search Path

Handles to Functions Not on the Path

Making Toolbox File Changes Visible to MATLAB

Making Nontoolbox File Changes Visible to MATLAB

Change Notification on Windows

Program Control

Using break, continue, and return

Using switch Versus if

MATLAB case Evaluates Strings

Multiple Conditions in a case Statement

Implicit Break in switch/case

Variable Scope in a switch

Catching Errors with try/catch

Nested try/catch Blocks

Forcing an Early Return from a Function

Save and Load

Saving Data from the Workspace

Loading Data into the Workspace

Viewing Variables in a MAT-File

Appending to a MAT-File

Save and Load on Startup or Quit

Saving to an ASCII File

Files and Filenames

Naming M-files

Naming Other Files

Passing Filenames as Arguments

Passing Filenames to ASCII Files

Determining Filenames at Runtime

Returning the Size of a File

Input/Output

File I/O Function Overview

Common I/O Functions

Readable File Formats

Using the Import Wizard

Loading Mixed Format Data

Reading Files with Different Formats

Reading ASCII Data into a Cell Array

Interactive Input into Your Program

Managing Memory

Useful Functions for Managing Memory

Compressing Data in Memory

Clearing Unused Variables from Memory

Conserving Memory with Large Amounts of Data

Matrix Manipulation with Sparse Matrices

Structure of Arrays Rather Than Array of Structures

Preallocating Is Better Than Growing an Array

Use repmat When You Need to Grow Arrays

Preallocating a Nondouble Matrix

System-Specific Ways to Use Less Memory

Out of Memory Errors on UNIX

Reclaiming Memory on UNIX

Out of Memory Errors and the JVM

Memory Requirements for Cell Arrays

Memory Required for Cell Arrays and Structures

Preallocating Cell Arrays to Save Memory

Optimizing for Speed

Finding Bottlenecks with the Profiler

Measuring Execution Time with tic and toc

Measuring Smaller Programs

Speeding Up MATLAB Performance

Vectorizing Your Code

Functions Used in Vectorizing

Coding Loops in a MEX-File for Speed

Preallocate to Improve Performance

Functions Are Faster Than Scripts

Avoid Large Background Processes

Load and Save Are Faster Than File I/O Functions

Conserving Both Time and Memory

Starting MATLAB

Getting MATLAB to Start Up Faster

Operating System Compatibility

Executing O/S Commands from MATLAB

Searching Text with grep

Constructing Path and File Names

Finding the MATLAB Root Directory

Temporary Directories and Filenames

Demos

Demos Available with MATLAB

For More Information


  Programming and Data Types M-File Programming