100% found this document useful (1 vote)
29 views

MATLAB Guide Third Edition Desmond J. Higham - Download the ebook now to start reading without waiting

The document provides information about the 'MATLAB Guide Third Edition' by Desmond J. Higham and Nicholas J. Higham, including its availability for download at ebookmeta.com. It also lists additional recommended ebooks related to various topics, including mathematics, engineering, and public health. The document contains details about the book's content, authors, and publication information.

Uploaded by

nvsurdev
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
29 views

MATLAB Guide Third Edition Desmond J. Higham - Download the ebook now to start reading without waiting

The document provides information about the 'MATLAB Guide Third Edition' by Desmond J. Higham and Nicholas J. Higham, including its availability for download at ebookmeta.com. It also lists additional recommended ebooks related to various topics, including mathematics, engineering, and public health. The document contains details about the book's content, authors, and publication information.

Uploaded by

nvsurdev
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 68

Read Anytime Anywhere Easy Ebook Downloads at ebookmeta.

com

MATLAB Guide Third Edition Desmond J. Higham

https://ebookmeta.com/product/matlab-guide-third-edition-
desmond-j-higham/

OR CLICK HERE

DOWLOAD EBOOK

Visit and Get More Ebook Downloads Instantly at https://ebookmeta.com


Recommended digital products (PDF, EPUB, MOBI) that
you can download immediately if you are interested.

Handbook of Writing for the Mathematical Sciences 3rd


Edition Nicholas J. Higham

https://ebookmeta.com/product/handbook-of-writing-for-the-
mathematical-sciences-3rd-edition-nicholas-j-higham/

ebookmeta.com

MATLAB Programming for Engineers 6th Edition Stephen J.


Chapman

https://ebookmeta.com/product/matlab-programming-for-engineers-6th-
edition-stephen-j-chapman/

ebookmeta.com

Deep Learning Toolbox Getting Started Guide MATLAB The


Mathworks

https://ebookmeta.com/product/deep-learning-toolbox-getting-started-
guide-matlab-the-mathworks/

ebookmeta.com

Our Sissy Husbands 1st Edition Amiee Allison

https://ebookmeta.com/product/our-sissy-husbands-1st-edition-amiee-
allison/

ebookmeta.com
Behemoths Beneath Nathan Thompson

https://ebookmeta.com/product/behemoths-beneath-nathan-thompson/

ebookmeta.com

Loose leaf Version for Calculus Late Transcendentals 4th


Edition Jon Rogawski

https://ebookmeta.com/product/loose-leaf-version-for-calculus-late-
transcendentals-4th-edition-jon-rogawski/

ebookmeta.com

Oxford Textbook of Global Public Health Roger Detels

https://ebookmeta.com/product/oxford-textbook-of-global-public-health-
roger-detels/

ebookmeta.com

Crisis Communication in the Digital Age: Manage or Rampage


1st Edition Ayse Simin Kara

https://ebookmeta.com/product/crisis-communication-in-the-digital-age-
manage-or-rampage-1st-edition-ayse-simin-kara/

ebookmeta.com

Let's Get IoT-fied!: 30 IoT Projects for All Levels 1st


Edition Shriram K. Vasudevan

https://ebookmeta.com/product/lets-get-iot-fied-30-iot-projects-for-
all-levels-1st-edition-shriram-k-vasudevan/

ebookmeta.com
Cannibalizing Queer Brazilian Cinema from 1970 to 2015 1st
Edition João Nemi Neto

https://ebookmeta.com/product/cannibalizing-queer-brazilian-cinema-
from-1970-to-2015-1st-edition-joao-nemi-neto/

ebookmeta.com
OT150_Higham-Higham_FM.indd 1 11/1/2016 10:43:36 AM
Third Edition

Desmond J. Higham
University of Strathclyde
Glasgow, Scotland

Nicholas J. Higham
University of Manchester
Manchester, England

Society for Industrial and Applied Mathematics


Philadelphia

OT150_Higham-Higham_FM.indd 3 11/1/2016 10:43:37 AM


Copyright © 2017 by the Society for Industrial and Applied Mathematics

10 9 8 7 6 5 4 3 2 1

All rights reserved. Printed in the United States of America. No part of this book may be reproduced,
stored, or transmitted in any manner without the written permission of the publisher. For information,
write to the Society for Industrial and Applied Mathematics, 3600 Market Street, 6th Floor, Philadelphia,
PA 19104-2688 USA.

MATLAB is a registered trademark of The MathWorks, Inc. For MATLAB product information,
please contact The MathWorks, Inc., 3 Apple Hill Drive, Natick, MA 01760-2098 USA, 508-647-7000,
Fax: 508-647-7001, info@mathworks.com, www.mathworks.com.

No warranties, express or implied, are made by the publisher, authors, and their employers that the
programs contained in this volume are free of error. They should not be relied on as the sole basis to
solve a problem whose incorrect solution could result in injury to person or property. If the programs
are employed in such a manner, it is at the user’s own risk and the publisher, authors, and their
employers disclaim all liability for such misuse.

Publisher David Marshall


Acquisitions Editor Elizabeth Greenspan
Developmental Editor Gina Rinelli Harris
Managing Editor Kelly Thomas
Production Editor David Riegelhaupt
Copy Editor Sam Clark, T&T Productions Ltd, London
Production Manager Donna Witzleben
Production Coordinator Cally Shrader
Graphic Designer Lois Sellers

Library of Congress Cataloging-in-Publication Data

Names: Higham, Desmond J., 1964- | Higham, Nicholas J., 1961-


Title: MATLAB guide / Desmond J. Higham, University of Strathclyde, Glasgow,
Scotland, United Kingdom, Nicholas J. Higham, University of Manchester,
Manchester, United Kingdom.
Description: Third edition. | Philadelphia : Society for Industrial and
Applied Mathematics, [2016] | Series: Other titles in applied mathematics
; 150 | Includes bibliographical references and index.
Identifiers: LCCN 2016039121 (print) | LCCN 2016039323 (ebook) | ISBN
9781611974652 (print) | ISBN 9781611974669 (e-book)
Subjects: LCSH: MATLAB. | Numerical analysis--Data processing.
Classification: LCC QA297 .H5217 2016 (print) | LCC QA297 (ebook) | DDC
518.0285/53--dc23
LC record available at https://lccn.loc.gov/2016039121

is a registered trademark.

OT150_Higham-Higham_FM.indd 4 11/1/2016 10:43:37 AM


In memory of our mother and father, Doris and Ken.
Contents

List of Figures xiii

List of Tables xvii

List of Program Files xix

Preface xxi

1 A Brief Tutorial 1

2 Basics 23
2.1 MATLAB Desktop . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
2.2 Interaction and Script Files . . . . . . . . . . . . . . . . . . . . . . . . 23
2.3 More Fundamentals . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
2.4 Help . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
2.5 Variables and the Workspace . . . . . . . . . . . . . . . . . . . . . . . 30

3 Distinctive Features of MATLAB 35


3.1 Automatic Storage Allocation . . . . . . . . . . . . . . . . . . . . . . 35
3.2 Variable Arguments Lists . . . . . . . . . . . . . . . . . . . . . . . . . 35
3.3 Complex Arrays and Arithmetic . . . . . . . . . . . . . . . . . . . . . 37

4 Arithmetic 39
4.1 IEEE Arithmetic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
4.2 Precedence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
4.3 Mathematical Functions . . . . . . . . . . . . . . . . . . . . . . . . . 42
4.4 Other Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42

5 Matrices 47
5.1 Matrix Generation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
5.2 Subscripting and the Colon Notation . . . . . . . . . . . . . . . . . . 54
5.3 Matrix and Array Operations . . . . . . . . . . . . . . . . . . . . . . 57
5.3.1 Implicit Expansion . . . . . . . . . . . . . . . . . . . . . . . . 61
5.4 Empty Matrices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
5.5 Matrix Manipulation . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
5.6 Data Analysis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66

6 Operators and Flow Control 71


6.1 Relational and Logical Operators . . . . . . . . . . . . . . . . . . . . 71
6.2 Flow Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78

vii
viii Contents

7 Program Files 83
7.1 Scripts and Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
7.2 Naming and Editing Program Files . . . . . . . . . . . . . . . . . . . 90
7.3 Working with Program Files and the MATLAB Path . . . . . . . . . 91
7.4 Startup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92
7.5 Command/Function Duality . . . . . . . . . . . . . . . . . . . . . . . 93

8 Graphics 97
8.1 Two-Dimensional Graphics . . . . . . . . . . . . . . . . . . . . . . . . 97
8.1.1 Basic Plots . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
8.1.2 Axes and Annotation . . . . . . . . . . . . . . . . . . . . . . . 102
8.1.3 Multiple Plots in a Figure . . . . . . . . . . . . . . . . . . . . 109
8.2 Three-Dimensional Graphics . . . . . . . . . . . . . . . . . . . . . . . 113
8.3 Specialized Graphs for Displaying Data . . . . . . . . . . . . . . . . . 125
8.4 Saving and Printing Figures . . . . . . . . . . . . . . . . . . . . . . . 129
8.5 On Things Not Treated . . . . . . . . . . . . . . . . . . . . . . . . . . 131

9 Linear Algebra 135


9.1 Matrix Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135
9.2 Norms and Condition Numbers . . . . . . . . . . . . . . . . . . . . . 136
9.3 Linear Equations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138
9.3.1 Square System . . . . . . . . . . . . . . . . . . . . . . . . . . . 138
9.3.2 Overdetermined System . . . . . . . . . . . . . . . . . . . . . 140
9.3.3 Underdetermined System . . . . . . . . . . . . . . . . . . . . . 141
9.4 Inverse, Pseudoinverse, and Determinant . . . . . . . . . . . . . . . . 142
9.5 LU, LDL∗ , and Cholesky Factorizations . . . . . . . . . . . . . . . . . 143
9.6 QR Factorization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145
9.7 Singular Value Decomposition . . . . . . . . . . . . . . . . . . . . . . 146
9.8 Eigenvalue Problems . . . . . . . . . . . . . . . . . . . . . . . . . . . 148
9.8.1 Eigenvalues . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148
9.8.2 More about Eigenvalue Computations . . . . . . . . . . . . . . 150
9.8.3 Generalized Eigenvalues . . . . . . . . . . . . . . . . . . . . . 151
9.9 Iterative Linear Equation and Eigenproblem Solvers . . . . . . . . . . 153
9.10 Functions of a Matrix . . . . . . . . . . . . . . . . . . . . . . . . . . . 156

10 More on Functions 159


10.1 Function Handles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159
10.2 Anonymous Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . 160
10.3 Local Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161
10.4 Default Input Arguments . . . . . . . . . . . . . . . . . . . . . . . . . 163
10.5 Variable Numbers of Arguments . . . . . . . . . . . . . . . . . . . . . 165
10.6 Argument Checking and Parsing . . . . . . . . . . . . . . . . . . . . . 167
10.7 Nested Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168
10.8 Private Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169
10.9 Recursive Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170
10.10 Global and Persistent Variables . . . . . . . . . . . . . . . . . . . . . 173
10.11 Exemplary Functions in MATLAB . . . . . . . . . . . . . . . . . . . 174
Contents ix

11 Numerical Methods: Part I 175


11.1 Polynomials and Data Fitting . . . . . . . . . . . . . . . . . . . . . . 175
11.2 Nonlinear Equations . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180
11.3 Optimization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184
11.4 The Fast Fourier Transform . . . . . . . . . . . . . . . . . . . . . . . 185

12 Numerical Methods: Part II 189


12.1 Numerical Integration . . . . . . . . . . . . . . . . . . . . . . . . . . . 189
12.2 Ordinary Differential Equations . . . . . . . . . . . . . . . . . . . . . 193
12.2.1 Examples with Ode45 . . . . . . . . . . . . . . . . . . . . . . . 193
12.2.2 Case Study: Pursuit Problem with Event Location . . . . . . 201
12.2.3 Stiff Problems, Differential-Algebraic Equations, and the Choice
of Solver . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205
12.3 Boundary-Value Problems . . . . . . . . . . . . . . . . . . . . . . . . 213
12.4 Delay-Differential Equations . . . . . . . . . . . . . . . . . . . . . . . 221
12.5 Partial Differential Equations . . . . . . . . . . . . . . . . . . . . . . 225

13 Input and Output 233


13.1 User Input . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 233
13.2 Output to the Screen . . . . . . . . . . . . . . . . . . . . . . . . . . . 234
13.3 File Input and Output . . . . . . . . . . . . . . . . . . . . . . . . . . 236
13.4 Fine Tuning the Display of Arrays . . . . . . . . . . . . . . . . . . . . 238

14 Troubleshooting 241
14.1 Errors and Assertions . . . . . . . . . . . . . . . . . . . . . . . . . . . 241
14.2 Warnings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 243
14.3 Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 245
14.4 Pitfalls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 246

15 Sparse Matrices 249


15.1 Sparse Matrix Generation . . . . . . . . . . . . . . . . . . . . . . . . 249
15.2 Linear Algebra . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 252

16 More on Coding 257


16.1 Elements of Coding Style . . . . . . . . . . . . . . . . . . . . . . . . . 257
16.2 Cleaning Up . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 258
16.3 Checking and Comparing Code Files . . . . . . . . . . . . . . . . . . 259
16.4 Profiling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 260
16.5 P-Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 261
16.6 Source Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 264
16.7 Live Editor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 264
16.8 Creating a Toolbox . . . . . . . . . . . . . . . . . . . . . . . . . . . . 265
16.9 Distributing Code Files . . . . . . . . . . . . . . . . . . . . . . . . . . 268
16.10 Unit Tests . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 269

17 Advanced Graphics 273


17.1 Objects, Handles, and Properties . . . . . . . . . . . . . . . . . . . . 273
17.2 Root and Default Properties . . . . . . . . . . . . . . . . . . . . . . . 278
17.3 Animation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 279
17.4 Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 281
x Contents

18 Other Data Types and Multidimensional Arrays 291


18.1 Character Vectors and Arrays . . . . . . . . . . . . . . . . . . . . . . 292
18.2 String Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 295
18.3 Multidimensional Arrays . . . . . . . . . . . . . . . . . . . . . . . . . 297
18.4 Categorical Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . 299
18.5 Datetime and Duration Arrays . . . . . . . . . . . . . . . . . . . . . . 300
18.6 Tables and Timetables . . . . . . . . . . . . . . . . . . . . . . . . . . 304
18.7 Structures and Cell Arrays . . . . . . . . . . . . . . . . . . . . . . . . 308

19 Object-Oriented Programming 315


19.1 Max-Plus Algebra Class . . . . . . . . . . . . . . . . . . . . . . . . . 315
19.2 Circulant Matrix Class . . . . . . . . . . . . . . . . . . . . . . . . . . 321
19.3 On Things Not Treated . . . . . . . . . . . . . . . . . . . . . . . . . . 324

20 The Symbolic Math Toolbox 325


20.1 Creating Symbolic Variables and Expressions . . . . . . . . . . . . . . 325
20.2 Equation Solving . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 327
20.3 Calculus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 330
20.3.1 Integration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 330
20.3.2 Differentiation . . . . . . . . . . . . . . . . . . . . . . . . . . . 332
20.3.3 Solving Differentiation Equations . . . . . . . . . . . . . . . . 335
20.3.4 Taylor Expansions . . . . . . . . . . . . . . . . . . . . . . . . . 336
20.4 Linear Algebra . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 337
20.5 Polynomials and Rationals . . . . . . . . . . . . . . . . . . . . . . . . 339
20.6 Variable-Precision Arithmetic . . . . . . . . . . . . . . . . . . . . . . 343
20.7 Other Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 347

21 Graphs 349
21.1 Undirected Graphs . . . . . . . . . . . . . . . . . . . . . . . . . . . . 349
21.2 Directed Graphs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 351

22 Large Data Sets 361


22.1 Datastores . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 361
22.2 MapReduce . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 364
22.3 Tall Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 364

23 Optimizing Codes 369


23.1 Timing Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 369
23.2 Vectorization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 370
23.3 Accessing Matrices by Column . . . . . . . . . . . . . . . . . . . . . . 372
23.4 Preallocating Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . 374
23.5 Miscellaneous Optimizations . . . . . . . . . . . . . . . . . . . . . . . 374
23.6 Illustration: Bifurcation Diagram . . . . . . . . . . . . . . . . . . . . 375
23.7 External Codes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 375

24 Tricks and Tips 379


24.1 Empty Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 379
24.2 Exploiting Infinities . . . . . . . . . . . . . . . . . . . . . . . . . . . . 380
24.3 Permutations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 380
24.4 Rank-1 Matrices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 382
Contents xi

24.5 Set Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 383


24.6 Subscripting Matrices as Vectors . . . . . . . . . . . . . . . . . . . . . 384
24.7 Avoiding If Statements . . . . . . . . . . . . . . . . . . . . . . . . . . 385

25 The Parallel Computing Toolbox 387


25.1 The Parfor Loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 388
25.2 Asynchronous Computing with Parfeval . . . . . . . . . . . . . . . . . 392
25.3 Batch Computations . . . . . . . . . . . . . . . . . . . . . . . . . . . 393
25.4 Single Program, Multiple Data . . . . . . . . . . . . . . . . . . . . . . 395
25.5 Distributed and Codistributed Arrays . . . . . . . . . . . . . . . . . . 397
25.6 GPU Computing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 398
25.7 On Things Not Treated . . . . . . . . . . . . . . . . . . . . . . . . . . 401

26 Case Studies 403


26.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 403
26.2 Brachistochrone . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 403
26.3 Small-World Networks . . . . . . . . . . . . . . . . . . . . . . . . . . 404
26.4 Performance Profiles . . . . . . . . . . . . . . . . . . . . . . . . . . . 409
26.5 Multidimensional Calculus . . . . . . . . . . . . . . . . . . . . . . . . 416
26.6 L-Systems and Turtle Graphics . . . . . . . . . . . . . . . . . . . . . 420
26.7 Black–Scholes Delta Surface . . . . . . . . . . . . . . . . . . . . . . . 422
26.8 Chutes and Ladders . . . . . . . . . . . . . . . . . . . . . . . . . . . . 425
26.9 Pythagorean Sum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 430
26.10 Fisher’s Equation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 432

A The Top 111 MATLAB Functions 439

Glossary 445

Bibliography 447

Index 459
List of Figures

1.1 MATLAB desktop at start of tutorial. . . . . . . . . . . . . . . . . . 2


1.2 Basic 2D picture produced by plot. . . . . . . . . . . . . . . . . . . . 8
1.3 Histogram produced by histogram. . . . . . . . . . . . . . . . . . . . 9
1.4 Growth of a random Fibonacci sequence. . . . . . . . . . . . . . . . . 10
1.5 Plot produced by collatz.m. . . . . . . . . . . . . . . . . . . . . . . 13
1.6 Plot produced by collbar.m. . . . . . . . . . . . . . . . . . . . . . . 14
1.7 Mandelbrot set approximation produced by mandel.m. . . . . . . . . 15
1.8 Phase plane plot from ode45. . . . . . . . . . . . . . . . . . . . . . . 17
1.9 Removal process for the Sierpinski gasket and Sierpinski gasket
approximation from gasket.m. . . . . . . . . . . . . . . . . . . . . . . 17
1.10 Sierpinski gasket approximation from barnsley.m. . . . . . . . . . . 19
1.11 3D picture produced by sweep.m. . . . . . . . . . . . . . . . . . . . . 20

2.1 Help browser. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30


2.2 Workspace browser. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
2.3 Array Editor. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32

7.1 Histogram produced by rouldist. . . . . . . . . . . . . . . . . . . . . 85


7.2 MATLAB Editor/Debugger. . . . . . . . . . . . . . . . . . . . . . . . 91

8.1 Simple x–y plots: default and nondefault. . . . . . . . . . . . . . . . 98


8.2 Default color order for lines and markers. . . . . . . . . . . . . . . . . 98
8.3 Color wheel showing how cyan, magenta, and yellow are obtained by
combining red, green, and blue. . . . . . . . . . . . . . . . . . . . . . 100
8.4 Two nondefault x–y plots. . . . . . . . . . . . . . . . . . . . . . . . . 101
8.5 loglog example. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102
8.6 plot(fft(eye(17))) with four variations of axis. . . . . . . . . . . 103
8.7 Use of ylim to change automatic y-axis limits. . . . . . . . . . . . . . 104
8.8 Epicycloid example. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105
8.9 Legendre polynomial example, using legend. . . . . . . . . . . . . . . 107
8.10 Legendre polynomial example (revised), using legend. . . . . . . . . 108
8.11 Plot with text produced using the MATLAB LATEX interpreter. . . . 110
8.12 Bezier curve and control polygon. . . . . . . . . . . . . . . . . . . . . 111
8.13 Example with subplot and fplot. . . . . . . . . . . . . . . . . . . . 112
8.14 Irregular grid of plots produced with subplot. . . . . . . . . . . . . . 113
8.15 3D plot created with plot3. . . . . . . . . . . . . . . . . . . . . . . . 115
8.16 Contour plots with fcontour and contour. . . . . . . . . . . . . . . 116
8.17 Contour plot labeled using clabel. . . . . . . . . . . . . . . . . . . . 117
8.18 Surface plots with mesh and meshc. . . . . . . . . . . . . . . . . . . . 117
8.19 Surface plots with surf, surfc, and waterfall. . . . . . . . . . . . . 118

xiii
xiv List of Figures

8.20 Surface plot with fsurf. . . . . . . . . . . . . . . . . . . . . . . . . . 119


8.21 3D view of a 2D plot. . . . . . . . . . . . . . . . . . . . . . . . . . . . 120
8.22 Color maps jet and parula. . . . . . . . . . . . . . . . . . . . . . . . 120
8.23 Fractal landscape views. . . . . . . . . . . . . . . . . . . . . . . . . . 123
8.24 surfc plot of matrix containing NaNs. . . . . . . . . . . . . . . . . . 124
8.25 Riemann surface for z 1/3 . . . . . . . . . . . . . . . . . . . . . . . . . . 124
8.26 2D bar plots. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126
8.27 3D bar plots. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127
8.28 Histograms produced with histogram, for a 1000-by-1 data vector. . 128
8.29 Pie charts. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129
8.30 Area graphs. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130
8.31 Three versions of the same plot: original, tuned, and converted to
LATEX. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132
8.32 From the 1964 Gatlinburg Conference on Numerical Algebra. . . . . 133

10.1 Sample output from rosy. . . . . . . . . . . . . . . . . . . . . . . . . 162


10.2 Koch curves created with function koch. . . . . . . . . . . . . . . . . 171
10.3 Koch snowflake created with function koch. . . . . . . . . . . . . . . 172

11.1 Least-squares polynomial fit of degree 3 and cubic spline for data from
1/(x + (1 − x)2 ). . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177
11.2 Interpolation with pchip and spline. . . . . . . . . . . . . . . . . . . 179
11.3 Interpolating a sine curve at five points using interp1. . . . . . . . . 180
11.4 Interpolation with griddata. . . . . . . . . . . . . . . . . . . . . . . . 181
11.5 Plot produced by fplot(@(x)x-tan(x),[-pi,pi]), grid. . . . . . . 182

12.1 Fresnel spiral. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 192


12.2 Scalar ODE example. . . . . . . . . . . . . . . . . . . . . . . . . . . . 194
12.3 Vector field for scalar ODE example. . . . . . . . . . . . . . . . . . . 196
12.4 Pendulum phase plane solutions. . . . . . . . . . . . . . . . . . . . . . 197
12.5 Rössler system phase space solutions. . . . . . . . . . . . . . . . . . . 199
12.6 Attractor reconstruction using deval. . . . . . . . . . . . . . . . . . . 200
12.7 Pursuit example. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 202
12.8 Pursuit example, with capture. . . . . . . . . . . . . . . . . . . . . . 203
12.9 Chemical reaction solutions with ode45 and ode15s. . . . . . . . . . 206
12.10 Zoom of chemical reaction solution from ode45. . . . . . . . . . . . . 206
12.11 Stiff ODE example, with Jacobian information supplied. . . . . . . . 210
12.12 DAE solution components from chemakzo in Listing 12.6. . . . . . . 211
12.13 Water droplet BVP solved by bvp4c. . . . . . . . . . . . . . . . . . . 215
12.14 Liquid crystal BVP solved by bvp4c. . . . . . . . . . . . . . . . . . . 217
12.15 Skipping rope eigenvalue BVP solved by bvp4c. . . . . . . . . . . . . 220
12.16 Predator–prey model with delay and harvesting. . . . . . . . . . . . . 223
12.17 Neural network DDE. . . . . . . . . . . . . . . . . . . . . . . . . . . . 225
12.18 Black–Scholes solution with pdepe. . . . . . . . . . . . . . . . . . . . 227
12.19 Reaction–diffusion system solution with pdepe. . . . . . . . . . . . . 229

15.1 Wathen matrix and its Cholesky factor. . . . . . . . . . . . . . . . . . 254


15.2 Wathen matrix and its Cholesky factor with symmetric reverse Cuthill–
McKee ordering (symrcm). . . . . . . . . . . . . . . . . . . . . . . . . 254
List of Figures xv

15.3 Wathen matrix and its Cholesky factor with symmetric minimum-
degree ordering (symamd). . . . . . . . . . . . . . . . . . . . . . . . . 254

16.1 profile viewer report for membrane example. . . . . . . . . . . . . . 261


16.2 More from profile viewer report for membrane example. . . . . . . 262
16.3 profile viewer report for ops example. . . . . . . . . . . . . . . . . 263
16.4 Calculus example in the Live Editor. . . . . . . . . . . . . . . . . . . 266
16.5 First page of PDF file exported from the live script in Figure 16.4. . 267

17.1 Hierarchical structure of graphics objects (simplified). . . . . . . . . . 274


17.2 Original plot and plot modified by set commands. . . . . . . . . . . 275
17.3 Straightforward use of subplot. . . . . . . . . . . . . . . . . . . . . . 277
17.4 Modified version of Figure 17.3 postprocessed by modifying object
properties. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 277
17.5 One frame from a movie. . . . . . . . . . . . . . . . . . . . . . . . . . 280
17.6 Animated figure upon completion. . . . . . . . . . . . . . . . . . . . . 281
17.7 Plot with default and modified settings. . . . . . . . . . . . . . . . . . 283
17.8 Word frequency bar chart created by script wfreq. . . . . . . . . . . 284
17.9 Selected Chebyshev polynomials Tk (x) on [−1, 1], created by script
cheb3plot. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 285
17.10 Example with superimposed axes created by script garden. . . . . . . 287
17.11 Diagram created by sqrt ex. . . . . . . . . . . . . . . . . . . . . . . 287

18.1 Hierarchy of fundamental MATLAB data types. . . . . . . . . . . . . 292


18.2 Histogram of categorical array. . . . . . . . . . . . . . . . . . . . . . . 301
18.3 Plot of interpolated data with datetime vector on the x-axis. . . . . 304
18.4 cellplot(testmat). . . . . . . . . . . . . . . . . . . . . . . . . . . . 313

20.1 The integrand in (20.1). . . . . . . . . . . . . . . . . . . . . . . . . . 334


20.2 taylortool window. . . . . . . . . . . . . . . . . . . . . . . . . . . . 337
20.3 sin x + arcsin x. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 338
20.4 Jacobi polynomials. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 343

21.1 Undirected graph. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 350


21.2 Weighted undirected graph and a minimum spanning tree. . . . . . . 351
21.3 Random graph from preferential attachment model. . . . . . . . . . . 352
21.4 Shortest path tree for graph in Figure 21.3. . . . . . . . . . . . . . . 352
21.5 Directed graph. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 355
21.6 Neuronal network of C. elegans. . . . . . . . . . . . . . . . . . . . . . 356
21.7 Subnetwork from C. elegans data. . . . . . . . . . . . . . . . . . . . . 356
21.8 Visualization of PageRank centrality in C. elegans subnetwork. . . . 358

22.1 Histograms of days and times of tweets. . . . . . . . . . . . . . . . . . 364


22.2 Histogram of pages of index commands. . . . . . . . . . . . . . . . . . 367

23.1 Approximate Brownian path. . . . . . . . . . . . . . . . . . . . . . . 373


23.2 Numerical bifurcation diagram. . . . . . . . . . . . . . . . . . . . . . 376
R2
25.1 Error for integral function, for integral 1 0.1/((x − λ)2 + 0.01) dx
depending on λ. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 390
xvi List of Figures

26.1 Output from brach. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 406


26.2 Output from the small-world simulations of small world. . . . . . . 407
26.3 Performance profile produced by ode pp. . . . . . . . . . . . . . . . . 413
26.4 Performance profile for fictitious data in 12-by-4 array A. . . . . . . . 417
26.5 Contours and stationary points of camel function (26.4). . . . . . . . 420
26.6 Members of the genus Matlabius Floribundum produced by lsys. . . 421
26.7 Black–Scholes delta picture from bsdelta. . . . . . . . . . . . . . . . 425
26.8 spy plot of transition matrix from chute. . . . . . . . . . . . . . . . . 428
26.9 Probability of finishing chutes and ladders game in exactly n rolls and
at most n rolls. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 428
26.10 Execution time of pythag versus requested accuracy. . . . . . . . . . 433
26.11 Traveling-wave solutions for Fisher’s equation, from fisher. . . . . . 434
26.12 Solution of Fisher’s equation for initial conditions (26.10) in moving
coordinate system, from fisher. . . . . . . . . . . . . . . . . . . . . . 436
List of Tables

0.1 Selected highlights of MATLAB releases. . . . . . . . . . . . . . . . . xxiii

2.1 10*exp(1) displayed in several output formats. . . . . . . . . . . . . 26


2.2 Command line editing keypresses. . . . . . . . . . . . . . . . . . . . . 27
2.3 Information and demonstrations. . . . . . . . . . . . . . . . . . . . . . 27
2.4 MATLAB directory structure (under Windows). . . . . . . . . . . . . 29

4.1 Arithmetic operator precedence. . . . . . . . . . . . . . . . . . . . . . 41


4.2 Elementary and special mathematical functions. . . . . . . . . . . . . 42
4.3 Parameters for single- and double-precision data types. . . . . . . . . 43

5.1 Elementary matrices. . . . . . . . . . . . . . . . . . . . . . . . . . . . 48


5.2 Special matrices. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
5.3 Matrices available through gallery. . . . . . . . . . . . . . . . . . . . 53
5.4 Matrices classified by property. . . . . . . . . . . . . . . . . . . . . . . 55
5.5 Elementary matrix and array operations. . . . . . . . . . . . . . . . . 59
5.6 Matrix manipulation functions. . . . . . . . . . . . . . . . . . . . . . 64
5.7 Basic data analysis functions. . . . . . . . . . . . . . . . . . . . . . . 67

6.1 Selected logical is* functions. . . . . . . . . . . . . . . . . . . . . . . 73


6.2 Logical operators. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74
6.3 Operator precedence. . . . . . . . . . . . . . . . . . . . . . . . . . . . 76

8.1 Options for the plot command. . . . . . . . . . . . . . . . . . . . . . 99


8.2 RGB coordinates for the colors in Table 8.1, as used for setting the
color property. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
8.3 Default values for some properties. . . . . . . . . . . . . . . . . . . . 101
8.4 Some commands for controlling the axes. . . . . . . . . . . . . . . . . 103
8.5 Some of the TEX commands supported in text strings. . . . . . . . . 107
8.6 2D plotting functions. . . . . . . . . . . . . . . . . . . . . . . . . . . . 114
8.7 3D plotting functions. . . . . . . . . . . . . . . . . . . . . . . . . . . . 123

9.1 Logical is* functions for matrices. . . . . . . . . . . . . . . . . . . . . 136


9.2 Some examples of how to set the opts structure in linsolve. . . . . 140
9.3 Iterative linear equation solvers. . . . . . . . . . . . . . . . . . . . . . 155

11.1 Top ten algorithms based on The Princeton Companion to Applied


Mathematics and Dongarra and Sullivan’s list. . . . . . . . . . . . . . 187

12.1 Default values for absolute and relative error tolerances. . . . . . . . 189
12.2 The MATLAB ODE solvers. . . . . . . . . . . . . . . . . . . . . . . . 208

xvii
xviii List of Tables

18.1 Multidimensional array functions. . . . . . . . . . . . . . . . . . . . . 298


18.2 Subset of identifiers supported in the datetime 'Format' and
'InputFormat' specifiers. . . . . . . . . . . . . . . . . . . . . . . . . 302

20.1 Linear algebra functions in the Symbolic Math Toolbox. . . . . . . . 340


20.2 Special polynomials. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 342

21.1 Selected graph functions. . . . . . . . . . . . . . . . . . . . . . . . . . 353

26.1 Data in transpose of array T from ode pp. . . . . . . . . . . . . . . . 413

A.1 Elementary and specialized vectors and matrices. . . . . . . . . . . . 439


A.2 Special variables and functions. . . . . . . . . . . . . . . . . . . . . . 439
A.3 Array information and manipulation. . . . . . . . . . . . . . . . . . . 440
A.4 Logical operators. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 440
A.5 Flow control. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 440
A.6 Basic data analysis. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 440
A.7 Graphics. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 441
A.8 Linear algebra. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 441
A.9 Functions connected with program files. . . . . . . . . . . . . . . . . . 441
A.10 Miscellaneous. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 442
A.11 Data types and conversions. . . . . . . . . . . . . . . . . . . . . . . . 442
A.12 Managing the workspace. . . . . . . . . . . . . . . . . . . . . . . . . . 442
A.13 Input and output. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 442
A.14 Numerical methods. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 443
List of Program Files

1.1 Script rfib.m. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11


1.2 Script collatz.m. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
1.3 Script collbar.m. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
1.4 Script mandel.m. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
1.5 Function lorenz de.m. . . . . . . . . . . . . . . . . . . . . . . . . . . 15
1.6 Script lorenz run.m. . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
1.7 Function gasket.m. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
1.8 Script barnsley.m. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
1.9 Script sweep.m. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20

7.1 Script rouldist. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84


7.2 Function maxentry. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
7.3 Function flogist. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
7.4 Function cheby. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
7.5 Function sqrtn. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
7.6 Function marks2. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90

8.1 Script legendre plot. . . . . . . . . . . . . . . . . . . . . . . . . . . 108


8.2 Function pnorm plot. . . . . . . . . . . . . . . . . . . . . . . . . . . . 110
8.3 Function bezier plot. . . . . . . . . . . . . . . . . . . . . . . . . . . 111
8.4 Function land. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121

10.1 Function fd deriv. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160


10.2 Function poly1err containing local function f. . . . . . . . . . . . . 163
10.3 Function rosy containing local function spiro. . . . . . . . . . . . . 164
10.4 Script test solver containing local function test. . . . . . . . . . . 164
10.5 Function companb. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 166
10.6 Function moments. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 167
10.7 Function arg checks. . . . . . . . . . . . . . . . . . . . . . . . . . . . 169
10.8 Function rational ex containing a nested function r. . . . . . . . . . 170
10.9 Function koch. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 172

12.1 Function rossler ex. . . . . . . . . . . . . . . . . . . . . . . . . . . . 198


12.2 Function rossler attract2. . . . . . . . . . . . . . . . . . . . . . . . 200
12.3 Function fox1. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 202
12.4 Function fox rabbit. . . . . . . . . . . . . . . . . . . . . . . . . . . . 204
12.5 Function rcd. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209
12.6 Function chemakzo. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 212
12.7 Function lcrun. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 218
12.8 Function skiprun. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 219
12.9 Function harvest. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 222

xix
xx List of Program Files

12.10 Script neural. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 224


12.11 Function bs. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 228
12.12 Function mbiol. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 230

13.1 Script print matrix. . . . . . . . . . . . . . . . . . . . . . . . . . . . 239

14.1 Script fib that generates a runtime error. . . . . . . . . . . . . . . . 242

16.1 Script badfun. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 260


16.2 Script ops. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 263
16.3 Script calculus.m. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 265
16.4 Script test acos. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 271

17.1 Script wfreq. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 284


17.2 Script cheb3plot. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 285
17.3 Script garden. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 286
17.4 Script sqrt ex. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 288

19.1 Code file maxplus; version for scalars. . . . . . . . . . . . . . . . . . . 317


19.2 Code file maxplus; version for matrices. . . . . . . . . . . . . . . . . . 319
19.3 Code file circulant. . . . . . . . . . . . . . . . . . . . . . . . . . . . 323

23.1 Script bif1. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 376


23.2 Script bif2. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 377

25.1 Function specrad randn. . . . . . . . . . . . . . . . . . . . . . . . . . 392


25.2 Function parfeval specrad. . . . . . . . . . . . . . . . . . . . . . . . 394

26.1 Function brach. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 405


26.2 Script small world. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 408
26.3 Function perfprof. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 411
26.4 Function ode pp. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 414
26.5 Script camel solve. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 418
26.6 Function lsys. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 423
26.7 Script lsys run. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 424
26.8 Script bsdelta. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 426
26.9 Script chute. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 429
26.10 Function pythag. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 431
26.11 Script fisher. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 435
Preface

MATLAB® 1 is an interactive system for numerical computation. Numerical analyst


Cleve Moler wrote the initial Fortran version of MATLAB in the late 1970s as a
teaching aid. It became popular for both teaching and research and evolved into a
commercial software package written in C. For many years now, MATLAB has been
widely used in universities and industry.
MATLAB has several advantages over more traditional means of numerical com-
puting (e.g., writing Fortran or C programs and calling numerical libraries).

• It allows quick and easy coding in a very high-level language.


• Data structures require minimal attention; in particular, arrays need not be
declared before first use.
• An interactive interface allows rapid experimentation and easy debugging.
• High-quality graphics and visualization facilities are available.
• MATLAB programs are completely portable across a wide range of platforms.
• Toolboxes can be added to extend the system, giving, for example, specialized
signal processing facilities and a symbolic manipulation capability.
• A wide range of user-contributed MATLAB programs is freely available on the
Internet.

Furthermore, MATLAB is a modern programming language and problem-solving en-


vironment: it has sophisticated data structures, contains built-in editing and debug-
ging tools, and supports object-oriented programming. These factors make MATLAB
an excellent language for teaching and a powerful tool for research and practical
problem-solving. Being interpreted, MATLAB inevitably suffers some loss of ef-
ficiency compared with compiled languages, but built-in performance acceleration
techniques (including some runtime compilation) reduce the inefficiencies and users
have the possibility of calling code and libraries written in other languages.
This book has two purposes. First, it aims to give a lively introduction to the most
popular features of MATLAB, covering all that most users will ever need to know.
We assume no prior knowledge of MATLAB, but the reader is expected to be familiar
with the basics of programming and with the use of the operating system under which
MATLAB is being run. We describe how and why to use MATLAB functions but
do not explain the mathematical theory and algorithms underlying them; instead,
references are given to the appropriate literature.
The second purpose of the book is to provide a compact reference to MATLAB.
The scope of MATLAB has grown dramatically as the package has been developed
1 MATLAB is a registered trademark of The MathWorks, Inc.

xxi
xxii Preface

(see Table 0.1), and even experienced MATLAB users may be unaware of some of the
functionality of the latest versions. Indeed, the PDF documentation for MATLAB
runs to well over ten thousand pages. Hence we believe that there is a need for a
manual that is wide-ranging yet concise. We hope that our approach of focusing on the
most important features of MATLAB, combined with the book’s logical organization
and detailed index, will make MATLAB Guide a useful reference.
The book is intended to be used by students, researchers, and practitioners alike.
Our philosophy is to teach by giving informative examples rather than to treat every
function comprehensively. Full documentation is available in the MATLAB help sys-
tem, which can be accessed from the Home tab of the MATLAB Toolstrip, by typing
doc in the Command Window, or on the website of The Mathworks. The contents of
the help system are also available as PDF files, accessible via “PDF Documentation”
links in the help system. When we refer to “the help system” we mean any one of
these sources.
Our treatment includes many “hidden” or easily overlooked features of MATLAB
and we provide a wealth of useful tips, covering such topics as customizing graphics,
coding style, code optimization, and debugging. However, we discuss only officially
documented MATLAB features (undocumented features can change without warning
and cannot be relied on).
The main subjects omitted are Graphical User Interface (GUI) tools, which can
be useful as front-ends to MATLAB computations, and MEX files.
We have not included exercises; MATLAB is often taught in conjunction with
particular subjects, and exercises are best tailored to the context.
We have been careful to show complete, undoctored MATLAB output and to test
every piece of MATLAB code listed. The only editing we have done has been to omit
some lines of output (to save space) and replace them by a line consisting of “...”.
MATLAB runs on several operating systems and we concentrate on features com-
mon to all. We do not describe how to install or run MATLAB, or how to customize
it—the documentation should be consulted for this system-specific information.
A web page for the book can be found at http://www.siam.org/books/ot150.
It includes links to all the codes used as examples in the book, errata, and links to
various MATLAB-related web resources. It also includes the bibliography of the book
as a BibTEX bib file and in PDF form with embedded links.

What This Book Describes

This book describes MATLAB 9.1 (Release 2016b). If you are not sure which version
of MATLAB you are using, type ver or version at the MATLAB prompt.

How This Book Is Organized

The book begins with a tutorial that provides a quick tour of MATLAB. The rest of
the book is independent of the tutorial, so the tutorial can be skipped—for example,
by readers already familiar with MATLAB.
The chapters are ordered so as to introduce topics in a logical fashion, with the
minimum of forward references. A principal aim was to cover MATLAB programs and
graphics as early as possible, subject to being able to provide meaningful examples.
Later chapters contain material that is more advanced or less likely to be needed by
the beginner.
Preface xxiii

Table 0.1. Selected highlights of MATLAB releases.

Year Version Notable features


1978 Classic Original Fortran version.
1984 1 Rewritten in C.
1985 2 30% more commands and functions, typeset docu-
mentation.
1987 3 Faster interpreter, color graphics, high-resolution
graphics printing.
1992 4 Sparse matrices, animation, visualization, user in-
terface controls, debugger, Handle Graphics® ,∗ Mi-
crosoft Windows support.
1997 5 Profiler, object-oriented programming, multidimen-
sional arrays, cell arrays, structures, more sparse
linear algebra, new ordinary differential equation
solvers, browser-based help.
2000 6, R12 MATLAB desktop including Help browser, ma-
trix computations based on LAPACK with opti-
mized BLAS, function handles, eigs interface to
ARPACK, boundary-value problem and partial dif-
ferential equation solvers, graphics object trans-
parency, Java support.
2002 6.5, R13 Performance acceleration, more control in warning
and error handling.
2004 7.0, R14 Mathematics on nondouble operands (single preci-
sion, integer), anonymous functions, nested func-
tions, publishing an M-file to HTML, LATEX, etc.,
enhanced plot annotation.
2008 7.6, R2008a Enhanced object-oriented programming capabilities.
2008 7.7, R2008b Upgraded random number generators.
2012 8.0, R2012b Redesigned desktop with Toolstrip, new help system.
2013 8.2, R2013b table data type and categorical arrays.
2014 8.4, R2014b Source control, updated graphics system, datetime
arrays, datastore.
2015 8.6, R2015b New execution engine, graph and digraph classes
2016 9.0, R2016a Live Editor, performance testing framework
2016 9.1, R2016b Local functions in scripts, string arrays, tall ar-
rays, implicit expansion of arrays with dimensions
of length 1.

Handle Graphics is a registered trademark of The MathWorks, Inc.
xxiv Preface

Using the Book


Readers new to MATLAB should begin by working through the tutorial in Chapter 1.
The tutorial gives a fast-paced overview of the capabilities of MATLAB, with all its
topics being covered in greater detail in subsequent chapters. Although it is designed
to be read sequentially, with most chapters building on material from earlier ones,
the book can be read in a nonsequential fashion by following cross-references and
making use of the index. It is difficult to do serious MATLAB computation without
a knowledge of arithmetic, matrices, colon notation, operators, flow control, and
program files, so Chapters 4–7 contain information essential for all users.
Appendix A lists our choice of the top 111 MATLAB functions—those that we
think every MATLAB user should know about. The beginner may like to tick off
these functions as they are learned, while intermediate users can pick out for study
those functions with which they are not already familiar.
From time to time we make reference to the extensive MATLAB documentation.
Reference information for a particular function, fun, can be obtained by typing help
fun or doc fun, but sometimes we need to refer to a page in HTML documentation
that is not directly accessible with a doc command. In this case we point to the
precise page in question by specifying a command such as

web([docroot '/matlab/numeric-types.html'])

Here, docroot refers to the location of the documentation on the system in question,
so this command should work on any MATLAB installation. Note that the quote
symbol, ', which displays in this way in MATLAB and is typeset this way in all the
MATLAB code in this book, is typed as the right or closing quote, ’, on the keyboard.

What’s New in the Third Edition


This third edition of the book is 25 percent longer than the second edition (2005) and
differs from it in several respects.

1. Many changes and new features introduced in MATLAB are incorporated.

2. All figures are now in color (they were monochrome in the second edition).

3. New “Asides”, highlighted in gray boxes, contain discussions on MATLAB-


related topics, such as anonymous functions, reproducibility, and color maps.

4. Our continuing experience in using MATLAB for teaching and research has led
to numerous improvements and additions—in particular, more examples.

5. The “Advanced Graphics” chapter (Chapter 17) (previously title “Handle Graph-
ics”) has been rewritten to reflect the major update to the graphics system
introduced in MATLAB 2014b.

6. A new chapter “Object-Oriented Programming” (Chapter 19) presents an in-


troduction to object-oriented programming in MATLAB through two examples
of classes.

7. The chapter “The Symbolic Math Toolbox” (Chapter 20) has been revised to
reflect the use of MuPAD as the underlying symbolic engine (previously the
engine was Maple), and the chapter has been extended.
Preface xxv

8. A new chapter “Graphs” (Chapter 21) describes the new MATLAB classes
graph and digraph, for representing and manipulating undirected graphs and
directed graphs.
9. A new chapter “Large Data Sets” (Chapter 22) describes MATLAB features for
handling data sets so large that they do not fit into the memory of the computer.
10. A new chapter “The Parallel Computing Toolbox” (Chapter 25) describes this
toolbox, which exploits multicore processors, clusters, and graphics processing
units (GPUs).

11. New sections have been added, including “Empty Matrices” (Section 5.4), “Ma-
trix Properties” (Section 9.1), “Argument Checking and Parsing” (Section 10.6),
“Fine Tuning the Display of Arrays” (Section 13.4), “Live Editor” (Section 16.7),
“Unit Tests” (Section 16.10), “String Arrays” (Section 18.2), “Categorical Ar-
rays” (Section 18.4), “Tables and Timetables” (Section 18.6), and “Timing
Code” (Section 23.1), and many existing sections contain new or reorganized
material.
12. Changes in MATLAB terminology have been incorporated. For example, the
terms “program files” and “local functions” replace what were previously called
“M-files” and “subfunctions”.

Future Versions of MATLAB


MATLAB will continue to evolve. New versions are released twice a year, denoted
“R20xya” and “R20xyb”. It is a good habit to inspect the release notes of each
new version in order to see what has changed. They can be found by typing doc
then selecting MATLAB or one of its installed toolboxes and following the link. The
release notes also give advanced notice of changes planned for the future, listed under
“Functionality being removed or changed”, enabling you to avoid using functions or
syntax that will become obsolete.

Acknowledgments
We are grateful to a number of people who offered helpful advice and comments during
the preparation of the book.
For the third edition: Penny Anderson, Bobby Cheng, Mike Croucher, Massim-
iliano Fasi, Heather Gorr, Stefan Güttel, Nick Hale, Richard Lang, Jasmina Lazic,
Steve Lord, Jos Martin, Umberto Noe, Sarah Palfreyman, Sam Relton, Ben Tordoff.
For the second edition: Penny Anderson, Paolo Bientinesi, David Carlisle, Jacek
Kierzenka, Cleve Moler, Jorge Moré, Jim Nagy, Larry Shampine.
For the first edition: Penny Anderson, Christian Beardah, Tom Bryan, Brian
Duffy, Cleve Moler, Damian Packer, Harikrishna Patel, Larry Shampine, Françoise
Tisseur, Nick Trefethen, Jack Williams.
It has been a pleasure working with Elizabeth Greenspan, Gina Rinelli Harris,
David Riegelhaupt, and Lois Sellers (SIAM), and Sam Clark (T&T Productions Ltd,
London), for the third edition; Beth Gallagher, Sara Murphy, Linda Thiel, and Kelly
Thomas for the second edition; and Beth Gallagher, Vickie Kearn, Michelle Mont-
gomery, Deborah Poulson, Lois Sellers, Kelly Thomas, and Marianne Will for the first
edition.
xxvi Preface

For those of you that have not experienced MATLAB,


we would like to try to show you what everybody is excited about....
The best way to appreciate PC-MATLAB is, of course, to try it yourself.
— JOHN LITTLE and CLEVE B. MOLER, A Preview of PC-MATLAB (1985)

In teaching, writing and research,


there is no greater clarifier than
a well-chosen example.
— CHARLES F. VAN LOAN, Using Examples to Build Computational Intuition (1995)

A new era in scientific computing


has been ushered in by the development of MATLAB.
— LLOYD N. TREFETHEN, Spectral Methods in MATLAB (2000)
Chapter 1
A Brief Tutorial

The best way to learn MATLAB is by trying it yourself, and hence we begin with a
whirlwind tour. Working through the examples below will give you a feel for the way
that MATLAB operates and an appreciation of its power and flexibility.
The tutorial is entirely independent of the rest of the book—all the MATLAB
features introduced are discussed in greater detail in the subsequent chapters. Indeed,
in order to keep this chapter brief, we have not explained all the functions used here.
You can use the index to find out more about particular topics that interest you.
The tutorial contains commands for you to type at the command line. In the
last part of the tutorial we give examples of script and function files—the MATLAB
versions of programs and functions, subroutines, or procedures in other languages.
These files are short, so you can type them in quickly. Alternatively, you can download
them from the website mentioned in the preface on p. xxii. You should experiment
as you proceed, keeping the following points in mind.
• Uppercase and lowercase characters are not equivalent (MATLAB is case sen-
sitive).
• Typing the name of a variable will cause MATLAB to display its current value.
• A semicolon at the end of a command suppresses the display of any output that
would otherwise be produced in the Command Window.
• MATLAB uses parentheses, (), square brackets, [], and curly braces, {}, and
these are not interchangeable.
• The up arrow and down arrow keys can be used to scroll through your previous
commands. Also, an old command can be recalled by typing the first few
characters followed by up arrow.
• You can type help topic to access online help on the command, function, or
symbol topic. Note that hyperlinks, indicated by underlines, are provided that
will take you to related help items and the more complete documentation in the
Help browser. Type doc topic to go directly to the Help browser.
• If you press the tab key after partially typing a function or variable name,
MATLAB will attempt to complete it, offering you a selection of choices if there
is more than one possible completion.
• You can quit MATLAB by typing exit or quit.
Having entered MATLAB, you should work through this tutorial by typing in the
text that appears after the MATLAB prompt, >>, in the Command Window. After
showing you what to type, we display the output that is produced. We begin with

1
2 A Brief Tutorial

Figure 1.1. MATLAB desktop at start of tutorial.

>> a = [1 2 3]

a =

1 2 3

This means that you are to type “a = [1 2 3]”, after which you will see the output
“a =” and “1 2 3” on separate lines separated by a blank line, as shown in Fig-
ure 1.1. (To save space we will subsequently omit blank lines in MATLAB output.
You can tell MATLAB to suppress blank lines by typing format compact.) This
example sets up a 1-by-3 array a (a row vector). In the next example, semicolons
separate the entries:

>> c = [4; 5; 6]
c =
4
5
6

A semicolon tells MATLAB to start a new row, so c is 3-by-1 (a column vector). Now
you can multiply the arrays a and c:

>> a*c
ans =
32

Here, you performed an inner product: a 1-by-3 array multiplied into a 3-by-1 array.
MATLAB automatically assigned the result to the variable ans, which is short for
answer. An alternative way to compute an inner product is with the dot function:

>> dot(a,c)
A Brief Tutorial 3

ans =
32
Inputs to MATLAB functions are specified after the function name and within paren-
theses. You may also form the outer product:
>> A = c*a
A =
4 8 12
5 10 15
6 12 18
Here, the answer is a 3-by-3 matrix that has been assigned to A.
The product a*a is not defined, since the dimensions are incompatible for matrix
multiplication:
>> a*a
Error using *
Inner matrix dimensions must agree.
Arithmetic operations on matrices and vectors come in two distinct forms. Matrix-
sense operations are based on the normal rules of linear algebra and are obtained
with the usual symbols +, -, *, /, and ^. Array-sense operations are defined to act
elementwise and are generally obtained by preceding the symbol with a dot. Thus if
you want to square each element of a you can write
>> b = a.^2
b =
1 4 9
Since the new vector b is 1-by-3, like a, you can form the array product of it with a:
>> a.*b
ans =
1 8 27
MATLAB has many mathematical functions that operate in the array sense when
given a vector or matrix argument. For example,
>> exp(a)
ans =
2.7183 7.3891 20.0855

>> log(ans)
ans =
1 2 3

>> sqrt(a)
ans =
1.0000 1.4142 1.7321
MATLAB displays floating-point numbers to 5 decimal digits, by default, but always
stores numbers and computes with them to the equivalent of 16 decimal digits. The
output format can be changed using the format command:
4 A Brief Tutorial

>> format long

>> sqrt(a)
ans =
1.000000000000000 1.414213562373095 1.732050807568877

>> format

The last command reinstates the default output format of 5 digits (and loose
line spacing, which we always suppress in this book, as noted above). Large or
small numbers are displayed in exponential notation, with a power of 10 scale factor
preceded by e:

>> 2^(-24)
ans =
5.9605e-08

Various data analysis functions are also available:

>> sum(b), mean(c)


ans =
14
ans =
5

As this example shows, you may include more than one command on the same line
by separating them with commas. If a command is followed by a semicolon then
MATLAB suppresses the output:

>> pi
ans =
3.1416

>> y = tan(pi/6);

The function pi, which is built into MATLAB, returns the value π. The variable ans
always contains the most recent unassigned expression, so after the assignment to y,
ans still holds the value π.
You may set up a two-dimensional array by using spaces to separate entries within
a row and semicolons to separate rows:

>> B = [-3 0 -1; 2 5 -7; -1 4 8]


B =
-3 0 -1
2 5 -7
-1 4 8

At the heart of MATLAB is a powerful range of linear algebra functions. For example,
recalling that c is a 3-by-1 vector, you may wish to solve the linear system B*x = c.
This can be done with the backslash operator:

>> x = B\c
x =
A Brief Tutorial 5

-1.2995
1.3779
-0.1014
You can check the result by computing the relative residual in the Euclidean norm:
>> norm(B*x-c)/(norm(B)*norm(x))
ans =
9.6513e-17
While nonzero because of rounding errors in the computations, this residual is about
as small as we can expect, given that MATLAB computes to the equivalent of about
16 decimal digits.
The eigenvalues of B can be found using eig:
>> e = eig(B)
e =
-3.1361
6.5680 + 5.1045i
6.5680 - 5.1045i

Here, i is the imaginary unit, −1. You may also specify two output arguments for
the function eig:
>> [V,D] = eig(B,'nobalance')
V =
0.9829 + 0.0000i -0.0385 - 0.0393i -0.0385 + 0.0393i
-0.1266 + 0.0000i -0.8005 + 0.0000i -0.8005 + 0.0000i
0.1337 + 0.0000i 0.1683 + 0.5725i 0.1683 - 0.5725i
D =
-3.1361 + 0.0000i 0.0000 + 0.0000i 0.0000 + 0.0000i
0.0000 + 0.0000i 6.5680 + 5.1045i 0.0000 + 0.0000i
0.0000 + 0.0000i 0.0000 + 0.0000i 6.5680 - 5.1045i
In this case the columns of V are eigenvectors of B and the diagonal elements of D
are the corresponding eigenvalues. Here, we gave eig the optional input argument
'nobalance', which disables the default balancing that attempts to improve the
scaling of the matrix. Single (closing) quotes act as string delimiters, so 'nobalance'
is a string. Many MATLAB functions take string arguments.
The colon notation is useful for constructing vectors of equally spaced values. For
example,
>> v = 1:6
v =
1 2 3 4 5 6
Generally, m:n generates the vector with entries m, m+1, . . . , n. Nonunit increments
can be specified with m:s:n, which generates entries that start at m and increase (or
decrease) in steps of s as far as n:
>> w = 2:3:10, y = 1:-0.25:0
w =
2 5 8
y =
1.0000 0.7500 0.5000 0.2500 0
6 A Brief Tutorial

You may construct big matrices out of smaller ones by following the conventions
that (a) square brackets enclose an array, (b) spaces or commas separate entries in a
row, and (c) semicolons separate rows:
>> C = [A,[8;9;10]], D = [B;a]
C =
4 8 12 8
5 10 15 9
6 12 18 10

D =
-3 0 -1
2 5 -7
-1 4 8
1 2 3
The element in row i and column j of the matrix C (where i and j always start at
1) can be accessed as C(i,j):
>> C(2,3)
ans =
15
More generally, C(i1:i2,j1:j2) picks out the submatrix formed by the intersection
of rows i1 to i2 and columns j1 to j2:
>> C(2:3,1:2)
ans =
5 10
6 12
You can build certain types of matrix automatically. For example, identities and
matrices of zeros and ones can be constructed with eye, zeros, and ones:
>> I3 = eye(3,3), Y = zeros(3,5), Z = ones(2)
I3 =
1 0 0
0 1 0
0 0 1
Y =
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
Z =
1 1
1 1
Note that for these functions the first argument specifies the number of rows and the
second the number of columns; if both numbers are the same then only one need
be given. The functions rand and randn work in a similar way, generating random
entries from the uniform distribution over [0, 1] and the normal (0, 1) distribution,
respectively. The numbers generated depend on the state of the random number
generator. By seeding the generator you can make your experiments repeatable.
Here, the seed is set to 20:
A Brief Tutorial 7

>> rng(20)
>> F = rand(3), g = randn(1,5)
F =
0.5881 0.8158 0.3787
0.8977 0.0359 0.5185
0.8915 0.6918 0.6580
g =
-1.3543 -0.9625 0.8736 0.8499 1.6579

Before the Days of rand


In 1955, the appropriately named RAND Corporation published the book
A Million Random Digits with 100, 000 Normal Deviates [144] as a resource
for researchers conducting large-scale randomized experiments. The book,
also available in punched card format, listed “random” numbers generated
via an electric roulette wheel. The book was reissued in 2001, attracting a
range of amusing online reviews.

By this point several variables have been created in the workspace. You can obtain
a list with the who command:
>> who

Your variables are:

A C F V Z ans c g w y
B D I3 Y a b e v x
You can obtain a more detailed list showing the size and class of each variable by
typing whos. Alternatively, look at the Workspace browser, which is displayed by
default in the MATLAB desktop (see Figure 1.1).
Like most programming languages, MATLAB has loop constructs. The following
example uses a for loop to evaluate the continued fraction

1
1+ ,
1
1+
1
1+
1
1+
1
1+
1
1+
1
1+
1
1+
1
1+
1
1+
1+1

which approximates the golden ratio, (1 + 5)/2. The evaluation is done from the
bottom up:
>> r = 2;
8 A Brief Tutorial

0.8

0.6

0.4

0.2

-0.2

-0.4

-0.6

-0.8
0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1

Figure 1.2. Basic 2D picture produced by plot.

>> for k = 1:10, r = 1 + 1/r; end


>> r
r =
1.6181
Loops involving while can be found later in this tutorial.
The plot function produces two-dimensional (2D) pictures:
>> t = 0:0.005:1; z = exp(10*t.*(t-1)).*sin(12*pi*t);
>> plot(t,z)
Here, plot(t,z) joins the points t(i),z(i) using the default solid linetype. MATLAB
opens a figure window in which the picture is displayed. Figure 1.2 shows the result.
You can close a figure window by typing close at the command line.
You can produce a histogram with the function histogram:
>> histogram(randn(1000,1))
Here, histogram is given 1000 points from the normal (0,1) random number generator.
The result is shown in Figure 1.3.
You are now ready for more challenging computations. A random Fibonacci se-
quence {xn } is generated by choosing x1 and x2 and setting

xn+1 = xn ± xn−1 , n ≥ 2.

Here, the ± indicates that + and − must have equal probability of being chosen.
Viswanath [175] analyzed this recurrence and showed that, with probability 1, for
large n the quantity |xn | increases like a multiple of cn , where c = 1.13198824 . . . (see
also [45]). You can test Viswanath’s result as follows:
>> clear
A Brief Tutorial 9

Figure 1.3. Histogram produced by histogram.

>> rng(100)
>> x = [1 2];
>> for n = 2:999, x(n+1) = x(n) + sign(rand-0.5)*x(n-1); end
>> semilogy(1:1000,abs(x))
>> c = 1.13198824;
>> hold on
>> semilogy(1:1000,c.^[1:1000])
>> hold off

Here, clear removes all variables from the workspace. The for loop stores a random
Fibonacci sequence in the array x; MATLAB automatically extends x each time a
new element x(n+1) is assigned. The semilogy function then plots n on the x-axis
against abs(x) on the y-axis, with logarithmic scaling for the y-axis. Typing hold on
tells MATLAB to superimpose the next picture on top of the current one. The second
semilogy plot produces a line of slope c. The overall picture, shown in Figure 1.4, is
consistent with Viswanath’s theory.
The MATLAB commands used to generate Figure 1.4 stretched over several lines.
This is inconvenient for a number of reasons, not least because if a change is made
to the experiment then it is necessary to reenter all the commands. To avoid this
difficulty you can employ a script. Create a file named rfib.m identical to Listing 1.1
in your current directory.2 You can call up the MATLAB Editor/Debugger from the
home tab of the Toolstrip or by typing edit in the Command Window; pwd displays
the current directory and ls or dir lists its contents. Now type

>> rfib

at the command line. This will reproduce the picture in Figure 1.4. Running rfib in
this way is essentially the same as typing the commands in the file at the command
2 “Directory” is a synonym for “folder”. We use the former term throughout this book.
10 A Brief Tutorial

1060

1050

1040

1030

1020

1010

100
0 100 200 300 400 500 600 700 800 900 1000

Figure 1.4. Growth of a random Fibonacci sequence.

line, in sequence. Note that in Listing 1.1 blank lines and indentation are used to
improve readability, and we have made the number of iterations a variable, m, so that
it can be more easily changed. The script also contains helpful comments—all text on
a line after the % character is ignored by MATLAB. Having set up these commands
in a script you are now free to experiment further. For example, changing rng(100)
to rng(101) generates a different random Fibonacci sequence, and adding the line
title('Random Fibonacci Sequence') at the end of the file will put a title on the
graph.
Our next example involves the Collatz iteration, which, given a positive integer
x1 , has the form xk+1 = f (xk ), where

3x + 1, if x is odd,
f (x) =
x/2, if x is even.
In words: if x is odd, replace it by 3x + 1, and if x is even, halve it. It has been
conjectured that this iteration will always lead to a value of 1 (and hence thereafter
cycle between 4, 2, and 1) whatever starting value x1 is chosen. There is ample
computational evidence to support this conjecture, which is variously known as the
Collatz problem, the 3x + 1 problem, the Syracuse problem, Kakutani’s problem,
Hasse’s algorithm, and Ulam’s problem. However, a rigorous proof has so far eluded
mathematicians. For further details, see [111] or type “Collatz problem” into your
favorite search engine. You can investigate the conjecture by creating the script
collatz.m shown in Listing 1.2. In this file a while loop and an if statement are
used to implement the iteration. The input command prompts you for a starting
value. The appropriate response is to type an integer and then hit return or enter:
>> collatz
Enter an integer bigger than 2: 27
Here, the starting value 27 has been entered. The iteration terminates and the re-
sulting picture is shown in Figure 1.5.
A Brief Tutorial 11

Listing 1.1. Script rfib.m.

%RFIB Random Fibonacci sequence.

rng(100) % Set random number state.


m = 1000; % Number of iterations.

x = [1 2]; % Initial conditions.


for n = 2:m-1 % Main loop.
x(n+1) = x(n) + sign(rand-0.5)*x(n-1);
end

semilogy(1:m,abs(x))
c = 1.13198824; % Viswanath's constant.
hold on
semilogy(1:m,c.^(1:m))
hold off

Listing 1.2. Script collatz.m.

%COLLATZ Collatz iteration.

n = input('Enter an integer bigger than 2: ');


narray = n;

count = 1;
while n ~= 1
if rem(n,2) == 1 % Remainder modulo 2.
n = 3*n+1;
else
n = n/2;
end
count = count + 1;
narray(count) = n; % Store the current iterate.
end

plot(narray,'*-') % Plot with * marker and solid line style.


title(['Collatz iteration starting at ' int2str(narray(1))])
12 A Brief Tutorial

To investigate the Collatz problem further, the script collbar in Listing 1.3 plots
a bar graph of the number of iterations required to reach the value 1, for starting
values 1, 2, . . . , 29. The result is shown in Figure 1.6. For this picture, the function
grid adds grid lines that extend from the axis tick marks, and xlabel and ylabel
add labels to the x- and y-axes.
The well-known and much-studied Mandelbrot set can be approximated graphi-
cally in just a few lines of MATLAB. It is defined as the set of points c in the complex
plane for which the sequence generated by the map z 7→ z 2 + c, starting with z = c,
remains bounded [140, Chap. 14]. The script mandel in Listing 1.4 produces the plot
of the Mandelbrot set shown in Figure 1.7. The script contains calls to linspace
of the form linspace(a,b,n), which generate an equally spaced vector of n values
between a and b. The meshgrid and complex functions are used to construct a ma-
trix C that represents the rectangular region of interest in the complex plane. The
waitbar function plots a bar showing the progress of the computation (the variable
h is a “handle” to the wait bar). The plot itself is produced by contourf, which
plots a filled contour. The expression abs(Z)<Z max in the call to contourf detects
points that have not exceeded the threshold Z max and that are therefore assumed
to lie in the Mandelbrot set; the double function is applied in order to convert the
resulting logical array to numeric form. You can experiment with mandel by changing
the region that is plotted, via the linspace calls, the number of iterations it max,
and the threshold Z max. Note that mandel changes the color map so that the image
is displayed in gray and white instead of the default blue and yellow; this makes it
much easier to see the boundary of the set. The default color map can be restored
with colormap(’default’).
Next we solve the ordinary differential equation (ODE) system
d
y1 (t) = 10(y2 (t) − y1 (t)),
dt
d
y2 (t) = 28y1 (t) − y2 (t) − y1 (t)y3 (t),
dt
d
y3 (t) = y1 (t)y2 (t) − 8y3 (t)/3.
dt
This is an example from the Lorenz equations family (see [161]). We take initial
conditions y(0) = [0, 1, 0]T and solve over 0 ≤ t ≤ 50. The program file lorenz_de in
Listing 1.5 is an example of a MATLAB function. Given t and y, this function returns
the right-hand side of the ODE as the vector yprime. This is the form required by
the MATLAB ODE solving functions. The script lorenz_run in Listing 1.6 uses
the MATLAB function ode45 to solve the ODE numerically and then produces the
(y1 , y3 ) phase plane plot shown in Figure 1.8. You can see an animated plot of the
solution by typing lorenz, which calls one of the MATLAB demonstrations (type
demos for the complete list).
Now we give an example of a recursive function, that is, a function that calls
itself. The Sierpinski gasket [139, Sec. 2.2] is based on the following process. Given
a triangle with vertices Pa , Pb , and Pc , we remove the triangle with vertices at the
midpoints of the edges, (Pa + Pb )/2, (Pb + Pc )/2, and (Pc + Pa )/2. This removes the
“middle quarter” of the triangle, as illustrated in Figure 1.9(a). Effectively, we have
replaced the original triangle with three “subtriangles”. We can now apply the middle
quarter removal process to each of these subtriangles to generate nine subsubtriangles,
and so on. The Sierpinski gasket is the set of all points that are never removed by
repeated application of this process. The function gasket in Listing 1.7 implements
A Brief Tutorial 13

Collatz iteration starting at 27


10000

9000

8000

7000

6000

5000

4000

3000

2000

1000

0
0 20 40 60 80 100 120

Figure 1.5. Plot produced by collatz.m.

Listing 1.3. Script collbar.m.

%COLLBAR Collatz iteration bar graph.

N = 29; % Use starting values 1,2,...,N.


niter = zeros(N,1); % Preallocate array.
for i = 1:N
count = 0;
n = i;
while n ~= 1
if rem(n,2) == 1
n = 3*n+1;
else
n = n/2;
end
count = count + 1;
end
niter(i) = count;
end
bar(niter) % Bar graph.
grid % Add horizontal and vertical grid lines.
title('Collatz iteration counts')
xlabel('Starting value','FontSize',12) % Label x-axis.
ylabel('Number of iterations','FontSize',12) % Label y-axis.
14 A Brief Tutorial

Collatz iteration counts


120

100
Number of iterations

80

60

40

20

0
0 5 10 15 20 25 30
Starting value

Figure 1.6. Plot produced by collbar.m.

Listing 1.4. Script mandel.m.

%MANDEL Mandelbrot set.

h = waitbar(0,'Computing...');
x = linspace(-2.1,0.6,2001);
y = linspace(-1.1,1.1,2001);
[X,Y] = meshgrid(x,y);
C = complex(X,Y);

Z_max = 1e6; it_max = 50;


Z = C;
for k = 1:it_max
Z = Z.^2 + C;
waitbar(k/it_max)
end
close(h)

contourf(x,y,double(abs(Z)<Z_max))
colormap([1 1 1; 1/2 1/2 1/2]) % Gray inside, white outside.
title('Mandelbrot Set','FontSize',16,'FontWeight','normal')
A Brief Tutorial 15

Figure 1.7. Mandelbrot set approximation produced by mandel.m.

Listing 1.5. Function lorenz de.m.

function yprime = lorenz_de(t,y)


%LORENZ_DE Lorenz equations.
% yprime = lorenz_de(t,y).

yprime = [10*(y(2)-y(1))
28*y(1)-y(2)-y(1)*y(3)
y(1)*y(2)-8*y(3)/3];

Listing 1.6. Script lorenz run.m.

%LORENZ_RUN ODE solving example: Lorenz.

tspan = [0 50]; % Solve for 0 <= t <= 50.


yzero = [0;1;0]; % Initial conditions.
[t,y] = ode45(@lorenz_de,tspan,yzero);
plot(y(:,1),y(:,3)) % (y_1,y_3) phase plane.
xlabel('y_1','FontSize',14)
ylabel('y_3 ','FontSize',14,'Rotation',0,'HorizontalAlignment','right')
title('Lorenz equations','FontSize',16,'FontWeight','normal')
16 A Brief Tutorial

Listing 1.7. Function gasket.m.

function gasket(Pa,Pb,Pc,level)
%GASKET Recursively generated Sierpinski gasket.
% GASKET(Pa, Pb, Pc, level) generates an approximation to
% the Sierpinski gasket, where the 2-vectors Pa, Pb, and Pc
% define the triangle vertices.
% level is the level of recursion.

if level == 0
% Fill the triangle with vertices Pa, Pb, Pc.
fill([Pa(1),Pb(1),Pc(1)],[Pa(2),Pb(2),Pc(2)],[0.5 0.5 0.5]);
hold on
else
% Recursive calls for the three subtriangles.
gasket(Pa,(Pa+Pb)/2,(Pa+Pc)/2,level-1)
gasket(Pb,(Pb+Pa)/2,(Pb+Pc)/2,level-1)
gasket(Pc,(Pc+Pa)/2,(Pc+Pb)/2,level-1)
end

the removal process. The input arguments Pa, Pb, and Pc define the vertices of the
triangle, and level specifies how many times the process is to be applied. If level
is nonzero then gasket calls itself three times with level reduced by 1, once for each
of the three subtriangles. When level finally reaches zero, the appropriate triangle
is drawn and filled with gray. The following code generates Figure 1.9(b).
level = 5;
Pa = [0;0];
Pb = [1;0];
Pc = [0.5;sqrt(3)/2];
gasket(Pa,Pb,Pc,level)
hold off
title_string = ['Gasket level = ' num2str(level)];
title(title_string,'FontSize',16,'FontWeight','normal')
axis('equal','off')
(Figure 1.9(a) was generated in the same way with level = 1.) In the last line, the
call to axis makes the units of the x- and y-axes equal and turns off the axes and
their labels. You should experiment with different initial vertices Pa, Pb, and Pc, and
different levels of recursion, but keep in mind that setting level bigger than 8 may
overstretch either your patience or your computer’s resources.
Other documents randomly have
different content
Missy was trembling dreadfully. “How was I to know?” she
answered nervously. “It might have been a bushranger, mightn't it?”
“Well, hardly,” replied John William, as seriously as though the
question had been put in the best of good faith. And it now became
obvious that he also had something on his mind and nerves, for he
shifted a little further away from Missy, and sat frowning at the dry
brown grass, and picking at it with his fingers.
“Anyhow, you startled me,” said Missy, as she arranged the carroty
fringe that had been shamefully dishevelled a moment before. “I am
very easily startled, you see.”
“I am very sorry. I do apologise, I'm sure! And I'll go away again
this minute, Missy, if you like.” He got to his knees with the words,
which were spoken in a more serious tone than ever.
“Oh, no, don't go away. I was only moping. I am glad you've
come.”
“Thank you, Missy.”
“But now you have come, you've got to talk and cheer me up.
See? There's too many things to think about on a Christmas Day—
when—when you're so far away from everybody.”
John William agreed and sympathised. “The fact is I had
something to show you,” he added; “that's why I came.”
“Then show away,” said Missy, forcing a smile. “Something in a
cardboard box, eh?”
“Yes. Will you open it and tell me how you like it?” He handed her
the box that he had taken out of his breast-pocket. Missy opened it
and produced a very yellow bauble of sufficiently ornate design.
“Well, I'm sure! A bangle!”
“Yes; but what do you think of it?” asked John William anxiously.
He had also blushed very brown.
“Oh, of course I think it's beautiful—beautiful!” exclaimed Missy,
with unmistakable sincerity. “But who's it for? That's what I want to
know,” she added, as she scanned him narrowly.
“Can't you guess?”
“Well, let's see. Yes—you're blushing! It's for your young woman,
that's evident.”
John William edged nearer.
“It's for the young lady—the young lady I should like to be mine—
only I'm so far below her,” he began in a murmur. Then he looked at
her hard. “Missy, for God's sake forgive me,” he cried out, “but it's
for you!”
“Nonsense!”
“But I mean it. I got it last night. Do, please, have it.”
“No,” said Missy firmly. “Thank you ever so very awfully much; but
you must take it back.” And she held it out to him with a still hand.
“I can't take it back—I won't!” cried young Teesdale excitedly.
“Consider it only as a Christmas box—surely your father's godson
may give you a little bit of a Christmas box? That's me, Missy, and
anything else I've gone and said you must forgive and forget too, for
it was all a slip. I didn't mean to say it, Missy, I didn't indeed. I hope
I know my position better than that. But this here little trumpery
what-you-call-it, you must accept it as a Christmas present from us
all. Yes, that's what you must do; for I'm bothered if I take it back.”
“You must,” repeated Missy very calmly. “I think you mean to
break my heart between you with your kindness. Here's the box and
here's the bangle.”
John William looked once and for all into the resolute light eyes.
Then first he took the box and put the lid on it, and stowed it away
in his breastpocket; and after that he took that gold bangle, very
gingerly, between finger and thumb, and spun it out into the centre
of the brown river, where it made bigger, widening bangles, that
took the best part of a minute to fail and die away. Then everything
was stiller than before; and stillest of all were the man and the
woman who stood facing each other on the bank, speckled with the
steep sunlight that came down on them like rain through the leaves
of the river-timber overhead.
“That was bad,” said Missy at last. “Something else was worse. It's
not much good your trying to hedge matters with me; and for my
part I'm going to speak straight and plain for once. If I thought that
you'd gone and fallen in love with me—as sure as we're standing
here, Jack, I'd put myself where you've put that bangle.”
Her hand pointed to the place. There was neither tremor in the
one nor ripple upon the other.
“But why?” Teesdale could only gasp.
“Because I'm so far below you.”
“Missy! Missy!” he was beginning passionately, but she checked
him at once.
“Let well alone, Jack. I've spoken God's truth. I'm not going to say
any more; only when you know all about me—as you may any day
now—perhaps even to-day—don't say that I told nothing but lies.
That's all. Now must I go back to the house, or will you?”
He glanced towards the river with unconscious significance. She
shook her head and smiled. He hung his, and went away.
Once more Missy was alone among the river-timber; once more
she flung herself down upon the short, dry grass, but this time upon
her back, while her eyes and her ears were wide open.
A cherry-picker was frivolling in the branches immediately above
her. From the moment it caught her eye, Missy seemed to take great
interest in that cherry-picker's proceedings. She had wasted
innumerable cartridges on these small birds, but that was in her
blood-thirsty days, now of ancient history, and there had never been
any ill-feeling between Missy and the cherry-pickers even then. One
solitary native cat was all the fair game that she had slaughtered in
her time. She now took to wondering why it was that these animals
were never to be seen upon a tree in day-time; and as she
wondered, her eyes hunted all visible forks and boughs; and as she
hunted, a flock of small parrots came whirring like a flight of arrows,
and called upon Missy's cherry-picker, and drove him from the
branches overhead. But the parrots were a new interest, and well
worth watching. They had red beaks and redder heads and tartan
wings and emerald breasts. Missy had had shots at these also
formerly; even now she shut her left eye and pretended that her
right fore-finger was a gun, and felt certain of three fine fellows with
one barrel had it really been a gun. Then at last she turned on her
elbow towards the river, and opened her mouth to talk to herself.
And after a long half-hour with nature this was all she had to say:
“If I did put myself in there, what use would it be? That beast
would get a hold of Arabella then. But it'd be nice never to know
what they said when they found out everything. What's more, I'd
rather be in there, after this, than in any town. After this!”
She gave that mob of chattering parrots a very affectionate
glance; also the dark green leaves with the dark blue sky behind
them; also the brown, still river, hidden away from the sun. She had
come to love them all, and the river would be a very good place for
her indeed.
She muttered on: “Then to think of John William! Well, I never! It
would be best for him too if I snuffed out, one way or another; and
as for 'Bella, if that brute doesn't turn up soon, he may not turn up
at all. But he said he'd keep me waiting. He's low enough down to
do it, too.”
She looked behind her shuddering, as she had looked behind her
many and many a time during the last few days. Instantly her eyes
fell upon that at which one has a right to shudder. Within six feet of
Missy a brown snake had stiffened itself from the ground with
darting tongue and eyes like holes in a head full of fire. And Missy
began to smile and hold out her hands to it.
“Come on,” she said. “Come on and do your worst! I wish you
would. That'd be a way out without no blame to anybody—and just
now they might be sorry. Come on, or I'll come to you. Ah, you
wretch, you blooming coward, you!”
She had got to her knees, and was actually making for the snake
on all fours; but it darted back into its hole like a streak of live
seaweed; and Missy then rose wearily to her feet, and stood looking
around her once more, as though for the last time.
“What am I to do?” she asked of river, trees, and sky. “What am I
to do? I haven't the pluck to finish myself, nor yet to make a clean
breast. I haven't any pluck at all. I might go back and do something
that'd make the whole kit of 'em glad to get rid o' me. That's what I
call a gaudy idea, but it would mean clearing out in a hurry. And I
don't want to clear out—not yet. Not just yet! So I'll slope back and
see what's happening and how things are panning out; and I'll go on
sitting tight as long as I'm let.”
CHAPTER XII.—“THE SONG OF
MIRIAM.”

A
ccordingly Missy reappeared in the verandah about tea-time,
and in the verandah she was once more paralysed with the
special terror that was hanging over her from hour to hour in
these days. An unfamiliar black coat had its back to the parlour
window; it was only when Missy discerned an equally unfamiliar red
face at the other side of the table that she remembered that
Christmas visitors had been expected in the afternoon, and reflected
that these must be they. The invited guests were a brace of
ministers connected with the chapel attended by the Teesdales, and
the red face, which was also very fat, and roofed over with a thatch
of very white hair, rose out of as black a coat as that other of which
Missy had seen the back. So these were clearly the ministers. And
they were already at tea.
As soon as Missy entered the parlour she recognised the person
sitting with his back to the window. He had lantern jaws hung with
black whiskers, and a very long but not so very cleanshaven upper
lip. His name was Appleton, he was the local minister, and Missy had
not only been taken to hear him preach, but she had met him
personally, and made an impression, judging by the length of time
the ministers hand had rested upon her shoulder on that occasion.
He greeted her now in a very complimentary manner, and with many
seasonable wishes, which received the echo of an echo from the
elder reverend visitor, whom Mrs. Teesdale made known to Missy as
their old friend Mr. Crowdy.
“Mr. Crowdy,” added Mrs. T., reproachfully, “came all the way from
Williamtown to preach our Christmas morning sermon. It was a
beautiful sermon, if ever I heard one.”
“It was that,” put in David, wagging his kind old head. “But you
should have told Mr. Crowdy, my dear, how Miriam feels our heat. I
wouldn't let her go this morning, Mr. Crowdy, on that account. So
you see it's me that's to blame.”
Mr. Crowdy looked very sorry for Miriam, but very well pleased
with himself and the world. Missy was shooting glances of gratitude
at her indefatigable old champion. Mr. Crowdy began to eye her
kindly out of his fat red face.
“So your name's Miriam? A good old-fashioned Biblical name, is
Miriam,” he said, in a wheezy, plethoric voice. “Singular thing, too,
my name's Aaron; but I'd make an oldish brother for you, young
lady, hey?”
Miriam laughed without understanding, and showed this. So Mr.
Teesdale explained.
“Miriam, my dear, was the sister of Moses and Aaron, you
remember.”
Missy did remember.
“Moses and Aaron? Why, of course!” cried she. “'Says Moses to
Aaron! '”
The quotation was not meant to go any further; but the white-
haired minister asked blandly, “Well, what did he say?” So bland,
indeed, was the question that Missy hummed forth after a very
trifling hesitation—

“Says Moses to Aaron,


While talking of these times'—
Says Aaron to Moses,
'I vote we make some rhymes!

The ways of this wicked world,


'Tis not a bed of roses—
No better than it ought to be—'
'Right you are!' says Moses.”

There was a short but perfect silence, during which Mrs. Teesdale
glared at Missy and her husband looked pained. Then the old
minister simply remarked that he saw no fun in profanity, and John
William (who was visibly out of his element) felt frightfully inclined to
punch Mr. Crowdy's white head for him. But the Reverend Mr.
Appleton took a lighter view of the matter.
“With all due deference to our dear old friend,” said this
gentleman, with characteristic unction, “I must say that I am of
opinion 'e is labouring under a slight misconception. Miss Miriam, I
feel sure, was not alluding to any Biblical characters at all, but to
two typical types of the latter-day Levite. Miss Miriam nods! I knew
that I was right!”
“Then I was wrong,” said Mr. Crowdy, cheerfully, as he nodded to
Missy, who had not seriously aggrieved him; “and all's well that ends
well.”
“Hear, hear!” chimed in David, thankfully. “Mrs. T., Mr. Appleton's
cup's off. And Mr. Crowdy hasn't got any jam. Or will you try our
Christmas cake now, Mr. Crowdy? My dears, my dears, you're
treating our guests very shabbily!”
“Some of them puts people about so—some that ought to know
better,” muttered Mrs. Tees-dale under her breath; but after that the
tea closed over Missy's latest misdemeanour—if indeed it was one
for Missy—and a slightly sticky meal went as smoothly as could be
expected to its end.
Then Mr. Appleton said grace, and Mr. Crowdy, pushing back his
plate and his chair, exclaimed in an oracular wheeze, “The Hundred!”
“The Old 'Undredth,” explained the other, getting on his feet and
producing a tuning-fork. He was the musical minister, Mr. Appleton.
Nevertheless, he led them off too high or too low, and started them
afresh three times, before they were all standing round that tea-
table and singing in unison at the rate of about two lines per minute

“All—peo—ple—that—on—earth-do—dwell—
Sing—to—the—Lord—with—cheer-fill-voice-
Him—serve—with—fear—His—praise-forth-tell-
Come—ye—be—fore—Him—and—-re-joice.”

And so through the five verses, which between them occupied the
better part of ten minutes; whereafter Mr. Crowdy knelt them all
down with their elbows among the tea-things, and offered up a
prayer.
Now it is noteworthy that the black sheep of this mob, that had no
business to be in this mob at all, displayed no sort of inclination to
smile at these grave proceedings. They took Missy completely by
surprise; but they failed to tickle her sense of humour, because there
was too much upon the conscience which had recently been born
again to Missy's soul. On the contrary, the hymn touched her heart
and the prayer made it bleed; for that heart was become like a foul
thing cleaned in the pure atmosphere of this peaceful homestead.
The prayer was very long and did not justify its length. It comprised
no point, no sentence, which in itself could have stung a sinner to
the quick. But through her fingers Missy could see the bald pate, the
drooping eyelids, and the reverent, submissive expression of old Mr.
Teesdale. And they drew the blood. The girl rose from her knees
with one thing tight in her mind. This was the fixed determination to
undeceive that trustful nature without further delay than was
necessary, and in the first fashion which offered.
A sort of chance came almost immediately; it was not the best
sort, but Missy had grown so desperate that now she was all for
running up her true piratical colours and then sheering off before a
gun could be brought to bear upon her. So she seized the
opportunity which occurred in the best parlour, to which the party
adjourned after tea. The best parlour was very seldom used. It had
the fusty smell of all best parlours, which never are for common use,
and was otherwise too much of a museum of albums,
antimacassars, ornaments and footstools, to be a very human
habitation at its best. Though all that met the eye looked clean,
there was a strong pervading sense of the dust of decades; but
some of this was about to be raised.
In the passage Mr. Appleton had taken Missy most affectionately
by the arm, and had whispered of Mr. Crowdy, who was ahead, “A
grand old man, and ripe for 'eaven!” But as they entered the best
parlour he was complimenting Missy upon her voice, which had quite
altered the sound of the late hymn from the moment when John
William fetched and handed to her an open hymn-book. And here
Mr. Crowdy, seating himself in the least uncomfortable of the
antimacassared chairs, had his say also.
“I like your voice too,” the florid old minister observed, cocking a
fat eye at Miriam. “But it is only natural that any young lady of your
name should be musical. Surely you remember? 'And Miriam the
prophetess, the sister of Aaron, took a timbrel in her hand; and all
the women went out after her with timbrels and with dances—' and
so forth. Exodus fifteenth. I suppose you can't play upon the timbrel,
hey, Miss Miriam?”
“No,” said Missy; “but I can dance.”
“Hum! And sing? What I mean is, young lady, do you only sing
hymns?”
Missy kept her countenance.
“I have sung songs as well,” she ventured to assert.
“Then give us one now, Missy,” cried old Tees-dale. “That's what
Mr. Crowdy wants, and so do we all.”
“Something lively?” suggested Missy, looking doubtfully at the red-
faced minister.
“Lively? To be sure,” replied Mr. Crowdy. “Christmas Day, young
lady, is not like a Sunday unless it happens to fall on one, which I'm
glad it hasn't this year. Make it as lively as convenient. I like to be
livened up!” And the old man rubbed his podgy hands and leant
forward in the least uncomfortable chair.
“And shall I give you a dance too?”
“A dance, by all means, if you dance alone. I understand that such
dancing has become quite the rage in the drawing-rooms at home.
And a very good thing too, if it puts a stop to that dancing two
together, which is an abomination in the sight of the Lord. But a
dance by yourself—by all manner of means!” cried Mr. Crowdy,
snatching off his spectacles and breathing upon the lenses.
“But I should require an accompaniment.”
“Nothing easier. My friend Appleton can accompany anything that
is hummed over to him twice. Can't you, Appleton?”
“Mr. Crowdy,” replied the younger man, in an injured voice, as he
looked askance at a little old piano with its back to the wall, and still
more hopelessly at a music-stool from which it would be perfectly
impossible to see the performance; “Mr. Crowdy, I do call this unfair!
I—I——”
“You—you—I know you, sir!” cried the aged divine, with
unmerciful good-humour. “Haven't I heard you do as much at your
own teas? Get up at once, sir, and don't shame our cloth by
disobliging a young lady who is offering to sing to us in the latest
style from England!”
“I'm not offering, mind!” said Missy a little sharply. “Still, I'm on to
do my best. Come over here, Mr. Appleton, and I'll hum it quite
quietly in your ear. It goes something like this.”
That conquered Appleton; but the Teesdales, while leaving the
whole matter in the hands of Missy and of the venerable Mr. Crowdy,
who wanted to hear her sing, had thrown in words here and there in
favour of the performance and of Mr. Appleton's part in it; all except
Mrs. T., who was determined to have no voice in a matter of which
she hoped to disapprove, and who showed her determination by an
even more unsympathetic cast of countenance than was usual with
her wherever Missy was concerned. Mrs. T. was seated upon a hard
sofa by her husband's side, Arabella on a low footstool, John William
by the window, and the two ministers we know where. The one at
the piano seemed to have got his teeth into a banjo accompaniment
which would have sounded very wonderfully like a banjo on that
little old tin-pot piano if he had thumped not quite so hard; but now
Missy was posing in front of the mantelpiece, and all eyes but the
unlucky accompanist's were covering her eagerly.
“Now you're all right, Mr. Appleton. You keep on like that, and I'll
nip in when I'm ready. If I stop and do a spout between the verses
you can stop too, only don't forget to weigh in with the chorus. But
when I dance, you keep on. See? That'll be all right, then. Ahem!”
Missy had spoken behind her hand in a stage whisper; now she
turned to her audience and struck an attitude that made them stare.
The smile upon her face opened their eyes still wider—it was so
brazen, so insinuating, and yet so terribly artificial. And with that
smile she began to dance, very slowly and rhythmically, plucking at
her dress and showing her ankles, while Appleton thumped carefully
on, little knowing what he was missing. And when it seemed as
though no song was coming the song began.
But the dance went on through all, being highly appropriate, at all
events to verse one, which ran:—

“Yuss! A fling and a slide with a pal, inside,


It isn't 'alf bad—but mind you!
The spot for a 'op is in front o' the shop
With a fried-fish-breeze be'ind you...

Well! Every lass was bold as brass,


But divvle a one a Venus;
An' Rorty 'Arry as I'm to marry
The only man between us!”

Here Missy and the music stopped together, Mr. Appleton holding
his fingers in readiness over the next notes, while Missy interrupted
her dance, too, to step forward and open fire upon her audience in
the following prose:—
“Now that's just 'ow the 'ole thing 'appened. They wouldn't give
my pore 'Arry no peace—catch them! Well, 'Arry'e done 's level—I
will say that for 'im. 'E took on three at once; but 'is legs wouldn't go
round fast enough, an' 'is arms wouldn't go round at all—catch
them! Now would you believe it? When 'e's 'ad enough o' the others
—a nasty common low lot they was, too—'e 'as the cheek to come to
yours truly. But—catch me! 'No, 'Arry,' I sez, 'ere's 2d. to go and 'ave
a pint o' four-'.lf,' I sez, 'w'ich you must need it,' I sez—just like that.
So 'e goes an' 'as 'alf a dozen. That's my 'Arry all over, that is! An'
w'en 'e come back 'e 'as the impidence to ax me again. But I give
'im a look like this,” cried Missy, leering horribly at the venerable
Crowdy. “Such a look! Just like that”—with a repetition of the leer for
Mrs. Teesdale's special benefit—“'.ause I seen what was wrong with
'im in the twinkling of a dress-improver. An' after that—chorus-up,
Mr. Appleton!—why, after that—

“'Arry 'e 'ad the 'ump,


An' I lets 'im know it—plump
'E swore 'e'd not,
So 'e got it 'ot,
I caught 'im a good ole crump.
You should 'a' seen 'im jump!
I didn't give a dump!
For I yells to 'is pals
'Now look at 'im, gals—
Arry, 'e 'as the 'ump!'.rdquo;

The dancing had been taken up again with the chorus. There was
some dancing plain at the end of it. Then came verse two:—
“'E swore and cussed till you thought 'e'd bust,
W'ich' is 'abit is when drinky;
'E cussed and swore till 'is mouth was sore
An' the street was painted pinky.
So I sez, sez I, to a stander-by
As was standin' by to listen,
'We've 'ad quite enough o' the reg'lar rough,
An' a bit too much o' this 'un!'.rdquo;

“'Yuss,'.rdquo; continued Missy without a break, “'an' if you're a


man,' I sez, 'come an' 'elp shift this 'ere bloomin' imitition,' I sez.
'Right you are,' 'e sez, 'since you put it so flatterin' like. An' wot do
they call you, my dear,' sez 'e. 'That's my bloomin' business,' sez I,
'wot's yours on the charge-sheet?' 'Ted,' sez 'e. 'Right,' sez I. 'You git
a holt of 'is 'eels, Ted, an' I'll 'ang on to 'is 'air!'.rdquo;
Up to this point matters had proceeded without audible let or
hindrance. But it appeared that at the psychological moment now
reached by the narrator the prostrate hero had regained the
command of his tongue, and the use he made of it was represented
by Missy in so voluble and violent a harangue, couched in such
exceedingly strong language, and all hurled so pointedly at the
heads of Mr. and Mrs. Teesdale on the sofa opposite the fire-place,
that an inevitable interruption now occurred.
“It's quite disgusting! I won't allow such language in my house.
Stop at once!” cried Mrs. T. half rising; but Missy's voice was louder;
while old David stretched an arm in front of his wife and fenced her
to the sofa.
“Sit still, my dear, and don't be foolish,” said he, quite firmly.
“Can't you see that it's part of the song, and only in fun?”
“Only in fun!” echoed Missy, whose speaking voice had risen to a
hoarse scream. “Ho, yuss, an' I s'pose it was fun between 'Arry an'
me an' Ted? You bet your bags it wasn't! Why, time we'd done with
'im, Ted's rigging was gone to glory—all but 'is chest-protector. And
as for me, you couldn't ha' made a decent pen-wiper out o' my 'ole
attire. An' why? Why 'cause—now then, you at the pianner!—'cause

“'Arry' e' ad the 'ump—


The liquorin' lushin' lump—
So I sez to Ted,
“Ere, sit on 'is 'ead,
Or shove 'im under the pump!'
Ted 'e turns out a trump.
We done it with bump an' thump.
For that 'orrible 'Arry
Was 'eavy to carry—
An' 'Arry 'e 'ad 'ump!”

Now not one of them guessed that this was the end of the song.
They had made up their minds to more and worse, and they got it in
Missy's final dance. She was wearing a dark blue skirt of some thin
material. Already there had been glimpses of a white underskirt and
a pair of crimson ankles, but now there were further and fuller
views. John William and Arabella had been curiously and painfully
fascinated from the beginning. Their father was still barring their
mother to the sofa with an outstretched arm. The poor old minister
sat forward in his chair with his eyes protruding from his head. His
junior, who was still thumping the old piano as though his life
depended upon it, was the one person present who saw nothing of
what was going on; and he suspected nothing amiss; he had been
too busy with his notes to attend even to the words. Every other eye
was fixed upon the dancing girl; every other forehead was wet with
a cold perspiration. But Mr. Appleton was so far unconsciously
infected with the spirit of the proceedings that he was now playing
that banjo accompaniment at about double his rate of starting. And
the ornaments were rattling on mantelpiece and table and bracket,
and a small vase fell with a crash into the fender—Missy had brought
it down with the toe of one high-heeled shoe. Then with a whoop
she was at the door. The door was flung open. There was a flutter of
white and a flare of crimson, neither quite in the room nor precisely
in the passage. The door was slammed, and the girl gone.
Mr. Teesdale was the first to rise. His face was very pale and
agitated. He crossed the room and laid a hand upon the shoulder of
Mr. Appleton, who was still pounding with all his heart at the old
piano. Appleton stopped and revolved on the music-stool with a face
of very comical ignorance and amazement. Mr. Teesdale went on to
the door and turned the handle. It did not open. The key had been
turned upon the outer side.
CHAPTER XIII.—ON THE
VERANDAH.

N
ight had fallen, and Mr. Teesdale had the homestead all to
himself. Arabella and her mother had accompanied the
ministers to evening worship in the township chapel. John
William was busy with the milking. As for Missy, she had
disappeared, as well she might, after her outrageous performance in
the best parlour. And Mr. Teesdale was beginning to wonder whether
they were ever to see her again; and if never, then what sort of
report could he send his old friend now?
He did not know. Her last prank was also incomparably her worst,
it had stunned poor David, and it left him unable to think coherently
of Missy any longer. Yet her own father had warned him that Miriam
was a very modern type of young woman; had hinted at the
possibility of her startling simple folks. Then again, David, who took
his newspaper very seriously indeed, had his own opinion of modern
society in England and elsewhere. And if, as he believed, Missy was
a specimen of that society, then it was not right to be hard upon the
specimen. Had not he gathered long ago from the newspapers that
the music-hall song and dance had found their way into smart
London drawing-rooms? Now that he had heard that song, and seen
that dance, were they much worse than he had been led to
suppose? If so, then society was even blacker than it was painted,
that was all. The individual in any case was not to blame, but least
of all in this case, where the individual had shown nothing but
kindness to an uninteresting old man, quite aside and apart from her
position in the old man's house as the child of his earliest friend.
And yet—and yet—he would do something to blot this last lurid
scene out of his mind. There was nothing he would not do, if only he
could do that. Yet this only showed him the narrowness of his own
mind. That, after all, was half the trouble. Here at the antipodes, in
an overlooked corner that had missed development with the colony,
just as Mr. Teesdale himself had missed it: here all minds must be
narrow. But theirs at the farm were perhaps narrower than most;
otherwise they would never have been so shocked at Missy; at all
events they would not have shown their feelings, as they evidently
must have shown them, to have driven poor Missy off the premises,
as they had apparently done.
Mr. Teesdale became greatly depressed as he made these
reflections, and gradually got as much of the blame on to his own
shoulders as one man could carry. It was very dark. He was sitting
out on the verandah and smoking; but it was too dark to enjoy a
pipe properly, even if David could have enjoyed anything just then.
He was sitting in one of those wooden chairs in which he had so
often sat of late while Missy read to him, and one hand rested
mournfully upon the seat of the empty chair at his side. Not that he
as yet really dreaded never seeing Missy again. He was keeping a
look-out for her all the time. Sooner or later she was bound to come
back.
She had come back already, but it was so dark that David never
saw her until he was putting a light to his second pipe. Then the
face of Missy, with her red hair tousled, came out of the night
beyond the verandah with startling vividness, and it was the most
defiant face that ever David Tees-dale had beheld.
“Missy,” cried he, “is that you?”
He dropped the match and Missy's face was gone.
“Yes, it's me,” said her voice, in such a tone as might have been
expected from her face.
“Then come in, child, come in,” said David joyfully, pushing back
his chair as he rose. “I'm that glad you've come back, you can't
think!”
“But I haven't come back—that's just it,” answered the defiant
voice out of the night.
“Then I'm going to fetch you back, Missy. I'm going——”
“You stop in that verandah. If you come out I'll take to my heels
and you'll never see me again—never! Now look here, Mr. Teesdale,
haven't I sickened you this time?”
“Done what, Missy?” asked David, uneasily, from the verandah. He
could see her outline now.
“Sickened you. I should have thought I'd sickened you just about
enough this trip, if you'd asked me. I should have said I'd choked
you off for good and all.”
“You know you've done no such thing, Missy. What nonsense the
child will talk!”
“What! I didn't sicken you this afternoon?”
“No.”
“Didn't disgust you, if you like that better?”
“No.”
“Didn't make you perspire, the whole lot of you?”
“Of course you didn't, Missy. How you talk! You amused us a good
deal, and you surprised us, too, a bit; but that was all.”
“Oh! So that was all, was it? So I only surprised you a bit? I
suppose you don't happen to know whether it was a big bit, eh?”
But David now decided that the time was come for firmness.
“Listen to me, Missy; I'm not going to have any more to say to
you unless you come inside at once!”
“But what if I'm not never coming inside—never no more?”
There was that within the words which made David pause to
consider. At length he said: “Very well, then, come into the verandah
and we'll have a sensible talk here, and I won't force you into the
house; though where else you're to go I don't quite see. However,
come here, and I won't insist on your coming a step further.”
“Honour bright?”
“Of course.”
“Hope to die?”
“I don't understand you, Missy; but I meant what I said.”
“Then I'm coming. One moment, though! Is anybody about? Is
Mrs. Teesdale in the house?”
“No, she's gone to chapel. So has Arabella, and John William's
milking. They'll none of 'em be back just yet. Ah, that's better, my
dear girl, that's better!”
Missy was back in her old wooden chair. Mr. Teesdale sat down
again in its fellow and put his hand affectionately upon the girl's
shoulder.
“So you mean to tell me your hairs didn't stand on end!” said
Missy, in a little whisper that was as unnecessary as it was
fascinating just then.
“I haven't got much to boast of,” answered the old man cheerily;
“but what hair I have didn't do any such thing, Missy.”
“Now just you think what you're saying,” pursued the girl, with an
air as of counsel cautioning a witness. “You tell me I neither
sickened you, nor disgusted you, nor choked you off for good and all
with that song and dance I gave you this afternoon. Your hairs didn't
stand on end, and I didn't even make you perspire—so you say! But
do you really mean me to believe you?”
“Why, bless the child! To be sure—to be sure!”
“Then, Mr. Teesdale, I must ask you whether you're in the habit of
telling lies.”
David opened his mouth to answer very promptly indeed, but kept
it open without answering at all at the moment. He had remembered
something that sent his left thumb and forefinger of their own
accord into an empty waistcoat pocket. “No,” said he presently with
a sigh, “I'm not exactly in the habit of saying what isn't true.”
“But you do it sometimes?”
“I have done it, God forgive me! But who has not?”
“Not me,” cried Missy candidly. “There's not a bigger liar in this
world than me! I'm going to tell you about that directly. I'm so glad
you've told a lie or two yourself—it gives me such a leg-up—though I
never should have thought it of you, Mr. Teesdale. I've told hundreds
since I've known you. Have you told any since you've known me?”
The question was asked with all the inquisitive sympathy of one
discovering a comrade in sin. “I mean not counting the ones you've
just been telling me,” added Missy when she got no answer, “about
your not being shocked, and all the rest of it.”
“That was no falsehood, Missy; that was the truth.”
“All right, then, we'll pass that. Have you told any other lies since
I've been here? Just whisper, and I promise I won't let on. I do so
want to know.”
“But why, my dear—but why?”
“Because it'll be ever so much easier for me to make my
confession when you've made yours.”
“Your confession! What can you have to confess, Missy?” The old
man chuckled as he patted her hand.
“More than you're prepared for. But you must fire first. Have you
or have you not told a wicked story since I've been staying here?”
Mr. Teesdale cleared his throat and sat upright in his chair.
“Missy,” said he solemnly, “the only untruth I can remember telling
in all my life, I have told since you have been with us; and I've told
it over and over again. Heaven knows why I admit this much to you!
I suppose there's something in you, my dear, that makes me say'
more than ever I mean to say. But I'm not going to say another
word about this—that's flat.”
“Good Lord!” murmured Missy. “And you've told it over and over
and over again! Oh, do tell me,” she whispered coaxingly; “you
might.”
“My dear, I've told you too much already.” And old Teesdale would
have risen and paced the verandah, but a pair of strong arms
restrained him. They were Missy's arms thrown round his neck, and
the old man was content to sit still.
“Tell me one thing,” she wheedled softly: “had it anything to do
with me—that wicked story you've told so often?”
Mr. Teesdale was silent.
“Then it had something to do with me. Let me think. Had it
anything—to do with—your watch?... Then it had! And anything to
do with that twenty pounds you sent me to the post office?... Yes, it
had! You pawned that watch to get me that money. You said you
had left it mending. I've heard you say so a dozen times. So this is
the lie you meant you'd told over and over again. And all for me! O
Mr. Teesdale, I am so sorry—I am—so—sorry.”
She had broken down and was sobbing bitterly on his shoulder.
The old man stroked her head.
“You needn't take it so to heart, Missy dear. Nay, come! Shall I tell
you why? Because it wasn't all for you, Missy. I hardly knew you
then. Nay, honey, it was all for your dear father—no one else.”
The effect of this distinction, made with a very touching sort of
pride, was to withdraw Missy's arms very suddenly from the old
man's neck, and to leave her sitting and trembling as far away from
him as possible, though still in her chair. Her moment was come; but
her nerve and her courage, her coolness and steadiness of purpose,
where were they now?
She braced herself together with a powerful effort. Hours ago she
had resolved, under influences that may be remembered, to
undeceive the too trustful old man now at her side. To that resolve
she still adhered; but as it had since become evident that nothing
she could possibly do would lead him to suspect the truth, there was
now no way for her but the hardest way of all—that of a full and
clean confession. Her teeth were chattering when she began, but Mr.
Teesdale understood her to say:
“Before you told your lie I had told you a dozen—I spoke hardly a
word of truth all the way into Melbourne that day. But there was one
great, big, tremendous lie at the bottom of all the rest. And can't
you guess what that was? You must guess—I can never tell you—I
couldn't get it out.”
Mr. Teesdale was very silent. “Yes, I think I can guess,” he said at
last, and sadly enough.
“Then what was it?” exclaimed Missy in an eager whisper. She was
shivering with excitement.
“Well, my dear, I suppose it was to do with them friends you had
to meet at the theatre. You might have trusted me a bit more,
Missy! I shouldn't have thought so much of it, after all.”
“Of what?”
“Why, of your going to the theatre alone. Wasn't that it, Missy?”
The girl moaned. “Oh, no—no! It was something ever so much
worse than that.”
“Then you weren't stopping with friends at all. Was that it? Yes,
you were staying all by yourself at one of the hotels.”
“No—no—no. It was ever so much worse than that too. That was
one of the lies I told you, but it was nothing like the one I mean.”
“Missy,” old David said gravely, “I don't want to know what you
mean. I don't indeed! I'd far rather know nothing at all about it.”
“But you must know!” cried Missy in desperation.
“Why must I?”
“Because this has gone on far too long. And I never meant it to go
on at all. No, I give you my oath I only meant to have a lark in the
beginning—to have a lark and be done with it! Anyhow I can't keep
it up any longer; that's all about it, and—but surely you can guess
now, Mr. Teesdale, can't you?”
Again the old man was long in answering. “Yes,” he exclaimed at
length, and with such conviction in his voice that Missy grasped her
chair-arms tight and sat holding her breath. “Yes, I do see now. You
borrowed that money not because you really needed it, but because
——”
The girl's groans stopped him. “To think that you can't guess,” she
wailed, “though I've as good as told you in so many words!”
“No, I can't guess,” answered David decisively. “What's more, I
don't want to. So I give it up. Hush, Missy, not another word! I won't
have it! I'll put my fingers in my ears if you will persist. I don't care

You might also like