Download Essential MATLAB® for Engineers and Scientists and more Thesis Matlab skills in PDF only on Docsity!
Essential MATLAB ® for Engineers and Scientists
Essential MATLAB®
for
Engineers and Scientists
Third edition
Brian D. Hahn
and
Daniel T. Valentine
AMSTERDAM • BOSTON • HEIDELBERG • LONDON • NEW YORK • OXFORD PARIS • SAN DIEGO • SAN FRANCISCO • SINGAPORE • SYDNEY • TOKYO Butterworth-Heinemann is an imprint of Elsevier
Butterworth-Heinemann is an imprint of Elsevier Linacre House, Jordan Hill, Oxford, OX2 8DP 30 Corporate Drive, Burlington, MA 01803
First published 2002 Reprinted 2002, 2003, 2004, 2005, 2006 Second edition 2006 Third edition 2007
Copyright © 2002, 2006, 2007 Brian D. Hahn and Daniel T. Valentine. Published by Elsevier Ltd. All rights reserved
The right of Brian D. Hahn and Daniel T. Valentine to be identified as the authors of this work has been asserted in accordance with the Copyright, Designs and Patents Act 1988
No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means electronic, mechanical, photocopying, recording or otherwise without the prior written permission of the publisher
Permission may be sought directly from Elsevier’s Science & Technology Rights Department in Oxford, UK: phone (+44) (0) 1865 843830; fax (+44) (0) 1865 853333; email: [email protected]. Alternatively you can submit your request online by visiting the Elsevier web site at http://elsevier.com/locate/permissions, and selecting Obtaining permission to use Elsevier material
Notice No responsibility is assumed by the publisher for any injury and/or damage to persons or property as a matter of products liability, negligence or otherwise, or from any use or operation of any methods, products, instructions or ideas contained in the material herein. Because of rapid advances in the medical sciences, in particular, independent verification of diagnoses and drug dosages should be made
British Library Cataloguing in Publication Data A catalogue record for this book is available from the British Library
Library of Congress Cataloging-in-Publication Data A catalog record for this book is available from the Library of Congress
ISBN 13: 9-78-0-75-068417- ISBN 10: 0-75-068417-
For information on all Butterworth-Heinemann publications visit our web site at books.elsevier.com
Typeset by Charon Tec Ltd (A Macmillan Company), Chennai, India, www.charontec.com Printed and bound in Italy
07 08 09 10 11 10 9 8 7 6 5 4 3 2 1
- PART I ESSENTIALS Preface to the third edition xvii
- 1 Introduction
- 1.1 Using MATLAB
- 1.2 The MATLAB desktop
- 1.3 Sample program
- 1.3.1 Cut and paste
- 1.3.2 Saving a program: script files
- 1.3.3 How a program works
- 2 MATLAB fundamentals
- 2.1 Variables and the workspace
- 2.1.1 Variables
- 2.1.2 Case sensitivity
- 2.1.3 The workspace
- 2.1.4 Adding commonly used constants to the workspace
- 2.2 Arrays: vectors and matrices
- 2.2.1 Initializing vectors: explicit lists
- 2.2.2 Initializing vectors: the colon operator
- 2.2.3 linspace
- 2.2.4 Transposing vectors
- 2.2.5 Subscripts
- 2.2.6 Matrices
- 2.2.7 Capturing output
- 2.3 Vertical motion under gravity
- 2.4 Operators, expressions and statements
- 2.4.1 Numbers
- 2.4.2 Data types
- 2.4.3 Arithmetic operators
- 2.4.4 Precedence of operators
- 2.4.5 The colon operator
- 2.4.6 The transpose operator
- 2.4.7 Arithmetic operations on arrays Contents
- 2.4.8 Expressions
- 2.4.9 Statements
- 2.4.10 Statements, commands and functions
- 2.4.11 Vectorization of formulae
- 2.5 Output
- 2.5.1 disp
- 2.5.2 format
- 2.5.3 Scale factors
- 2.6 Repeating with for
- 2.6.1 Square roots with Newton’s method
- 2.6.2 Factorials!
- 2.6.3 Limit of a sequence
- 2.6.4 The basic for construct
- 2.6.5 for in a single line
- 2.6.6 More general for
- 2.6.7 Avoid for loops by vectorizing!
- 2.6.8 A common mistake: for less loops!
- 2.7 Decisions
- 2.7.1 The one-line if statement
- 2.7.2 The if-else construct
- 2.7.3 The one-line if-else statement
- 2.7.4 elseif
- 2.7.5 Logical operators
- 2.7.6 Multiple ifs versus elseif
- 2.7.7 Nested ifs
- 2.7.8 Vectorizing ifs?
- 2.7.9 switch
- 2.8 Complex numbers
- 2.9 More on input and output
- 2.9.1 fprintf
- 2.9.2 Output to a disk file with fprintf
- 2.9.3 General file I/O
- 2.9.4 Saving and loading data
- 2.10 Odds ’n ends
- 2.10.1 Variables, functions and scripts with the same name
- 2.10.2 The input statement
- 2.10.3 Shelling out to the operating system
- 2.10.4 More Help functions
- 2.11 Programming style
- 3 Program design and algorithm development
- 3.1 Computer program design process
- 3.1.1 Projectile problem example
- 3.2 Other examples of structure plans Contents
- 3.3 Structured programming with functions
- 4 MATLAB functions & *data import-export utilities
- 4.1 Some common functions
- 4.2 *Importing and exporting data
- 4.2.1 The load and save commands
- 4.2.2 Exporting text (ASCII) data
- 4.2.3 Importing text (ASCII) data
- 4.2.4 Exporting binary data
- 4.2.5 The Import Wizard
- 4.2.6 Low-level file I/O functions
- 4.2.7 Other import/export functions
- 5 Logical vectors
- 5.1 Examples
- 5.1.1 Discontinuous graphs
- 5.1.2 Avoiding division by zero
- 5.1.3 Avoiding infinity
- 5.1.4 Counting random numbers
- 5.1.5 Rolling dice
- 5.2 Logical operators
- 5.2.1 Operator precedence
- 5.2.2 Danger
- 5.2.3 Logical operators and vectors
- 5.3 Subscripting with logical vectors
- 5.4 Logical functions
- 5.5 Logical vectors instead of elseif ladders
- 6 Matrices of numbers & arrays of strings
- 6.1 Matrices
- 6.1.1 A concrete example
- 6.1.2 Creating matrices
- 6.1.3 Subscripts
- 6.1.4 Transpose
- 6.1.5 The colon operator
- 6.1.6 Duplicating rows and columns: tiling
- 6.1.7 Deleting rows and columns
- 6.1.8 Elementary matrices
- 6.1.9 *Specialized matrices
- 6.1.10 Using MATLAB functions with matrices
- 6.1.11 Manipulating matrices
- 6.1.12 Array (element-by-element) operations on matrices Contents
- 6.1.13 Matrices and for
- 6.1.14 Visualization of matrices
- 6.1.15 Vectorizing nested fors: loan repayment tables
- 6.1.16 Multidimensional arrays
- 6.2 Matrix operations
- 6.2.1 Matrix multiplication
- 6.2.2 Matrix exponentiation
- 6.3 Other matrix functions
- 6.4 *Strings
- 6.4.1 Assignment
- 6.4.2 Input
- 6.4.3 Strings are arrays
- 6.4.4 Concatenation of strings
- 6.4.5 ASCII codes, double and char
- 6.4.6 fprintf of strings
- 6.4.7 Comparing strings
- 6.4.8 Other string functions
- 6.5 *Two-dimensional strings
- 6.6 *eval and text macros
- 6.6.1 Error trapping with eval and lasterr
- 6.6.2 eval with try...catch
- 7 Introduction to graphics
- 7.1 Basic 2-D graphs
- 7.1.1 Labels
- 7.1.2 Multiple plots on the same axes
- 7.1.3 Line styles, markers and color
- 7.1.4 Axis limits
- 7.1.5 Multiple plots in a figure: subplot
- 7.1.6 figure, clf and cla
- 7.1.7 Graphical input
- 7.1.8 Logarithmic plots
- 7.1.9 Polar plots
- 7.1.10 Plotting rapidly changing mathematical functions: fplot
- 7.1.11 The property editor
- 7.2 3-D plots
- 7.2.1 plot3
- 7.2.2 Animated 3-D plots with comet3
- 7.2.3 Mesh surfaces
- 7.2.4 Contour plots
- 7.2.5 Cropping a surface with NaNs
- 7.2.6 Visualizing vector fields
- 7.2.7 Visualization of matrices
- 7.2.8 Rotation of 3-D graphs Contents
- 7.2.9 Other cool graphics functions
- 8 Loops
- 8.1 Determinate repetition with for
- 8.1.1 Binomial coefficient
- 8.1.2 Update processes
- 8.1.3 Nested fors
- 8.2 Indeterminate repetition with while
- 8.2.1 A guessing game
- 8.2.2 The while statement
- 8.2.3 Doubling time of an investment
- 8.2.4 Prime numbers
- 8.2.5 Projectile trajectory
- 8.2.6 break and continue
- 8.2.7 Menus
- 9 Errors and pitfalls
- 9.1 Syntax errors
- 9.2 Pitfalls and surprises
- 9.2.1 Incompatible vector sizes
- 9.2.2 Name hiding
- 9.2.3 Other pitfalls for the unwary
- 9.3 Errors in logic
- 9.4 Rounding error
- 9.5 Trapping and generating errors
- 10 Function M-files - 10.1 Some examples - 10.1.1 Inline objects: harmonic oscillators - 10.1.2 Function M-files: Newton’s method again - 10.2 Basic rules - 10.2.1 Subfunctions - 10.2.2 Private functions - 10.2.3 P-code files - 10.2.4 Improving M-file performance with the profiler - 10.3 Function handles - 10.4 Command/function duality - 10.5 Function name resolution - 10.6 Debugging M-files - 10.6.1 Debugging a script - 10.6.2 Debugging a function - 10.7 Recursion
- 11 Vectors as arrays & *advanced data structures Contents
- 11.1 Update processes
- 11.1.1 Unit time steps
- 11.1.2 Non-unit time steps
- 11.1.3 Using a function
- 11.1.4 Exact solution
- 11.2 Frequencies, bar charts and histograms
- 11.2.1 A random walk
- 11.2.2 Histograms
- 11.3 *Sorting
- 11.3.1 Bubble Sort
- 11.3.2 MATLAB’s sort
- 11.4 *Structures
- 11.5 *Cell arrays
- 11.5.1 Assigning data to cell arrays
- 11.5.2 Accessing data in cell arrays
- 11.5.3 Using cell arrays
- 11.5.4 Displaying and visualizing cell arrays
- 11.6 *Classes and objects
- 12 *More graphics
- 12.1 Handle Graphics
- 12.1.1 Getting handles
- 12.1.2 Graphics object properties and how to change them
- 12.1.3 A vector of handles
- 12.1.4 Graphics object creation functions
- 12.1.5 Parenting
- 12.1.6 Positioning figures
- 12.2 Editing plots
- 12.2.1 Plot edit mode
- 12.2.2 Property Editor
- 12.3 Animation
- 12.3.1 Animation with Handle Graphics
- 12.4 Color etc.
- 12.4.1 Colormaps
- 12.4.2 Color of surface plots
- 12.4.3 Truecolor
- 12.5 Lighting and camera
- 12.6 Saving, printing and exporting graphs
- 12.6.1 Saving and opening figure files
- 12.6.2 Printing a graph
- 12.6.3 Exporting a graph
- 13 *Graphical User Interfaces (GUIs) Contents
- 13.1 Basic structure of a GUI
- 13.2 A first example: getting the time
- 13.3 Newton again
- 13.4 Axes on a GUI
- 13.5 Adding color to a button
- PART II APPLICATIONS
- 14 Dynamical systems
- 14.1 Cantilever beam
- 14.2 Electric current
- 14.3 Free fall
- 14.4 Projectile with friction
- 15 Simulation
- 15.1 Random number generation
- 15.2 Spinning coins
- 15.3 Rolling dice
- 15.4 Bacteria division
- 15.5 A random walk
- 15.6 Traffic flow
- 15.7 Normal (Gaussian) random numbers
- 16 *More matrices
- 16.1 Leslie matrices: population growth
- 16.2 Markov processes
- 16.3 Linear equations
- 16.3.1 MATLAB’s solution
- 16.3.2 The residual
- 16.3.3 Overdetermined systems
- 16.3.4 Underdetermined systems
- 16.3.5 Ill conditioning
- 16.3.6 Matrix division
- 16.4 Sparse matrices
- 17 *Introduction to numerical methods
- 17.1 Equations
- 17.1.1 Newton’s method
- 17.1.2 The Bisection method
- 17.1.3 fzero Contents
- 17.1.4 roots
- 17.2 Integration
- 17.2.1 The Trapezoidal rule
- 17.2.2 Simpson’s rule
- 17.2.3 quad
- 17.3 Numerical differentiation
- 17.4 First-order differential equations
- 17.4.1 Euler’s method
- 17.4.2 Example: bacteria growth
- 17.4.3 Alternative subscript notation
- 17.4.4 A predictor-corrector method
- 17.5 Linear ordinary differential equations (LODEs)
- 17.6 Runge-Kutta methods
- 17.6.1 A single differential equation
- 17.6.2 Systems of differential equations: chaos
- 17.6.3 Passing additional parameters to an ODE solver
- 17.7 A partial differential equation
- 17.8 Other numerical methods
- Appendix A: Syntax quick reference
- A.1 Expressions
- A.2 Function M-files
- A.3 Graphics
- A.4 if and switch
- A.5 for and while
- A.6 Input/output
- A.7 load/save
- A.8 Vectors and matrices
- Appendix B: Operators
- Appendix C: Command and functionquick reference
- C.1 General purpose commands
- C.1.1 Managing commands
- C.1.2 Managing variables and the workspace
- C.1.3 Files and the operating system
- C.1.4 Controlling the Command Window
- C.1.5 Starting and quitting MATLAB
- C.2 Logical functions
- C.3 Language constructs and debugging Contents
- C.3.1 MATLAB as a programming language
- C.3.2 Interactive input
- C.4 Matrices and matrix manipulation
- C.4.1 Elementary matrices
- C.4.2 Special variables and constants
- C.4.3 Time and date
- C.4.4 Matrix manipulation
- C.4.5 Specialized matrices
- C.5 Mathematical functions
- C.6 Matrix functions
- C.7 Data analysis
- C.8 Polynomial functions
- C.9 Function functions
- C.10 Sparse matrix functions
- C.11 Character string functions
- C.12 File I/O functions
- C.13 Graphics
- C.13.1 2-D
- C.13.2 3-D
- C.13.3 General
- Appendix D: ASCII character codes
- Appendix E: Solutions to selected exercises
- Index
In memory of Brian Hahn 1946–
Daniel T. Valentine and the staff at Butterworth-Heinemann, Elsevier would like to dedicate this book to the memory of Brian Hahn, who wrote the first edition in 1997 while he was an Associate Professor in the Department of Mathematics and Applied Mathematics, Univer- sity of Cape Town, South Africa. Brian’s academic career began after a PhD in Theoretical Physics obtained from Cambridge. His first post as Lecturer was at the University of the Witwaterstrand, Johannesburg. He was promoted to Senior Lecturer in 1979. He joined the University of Cape Town in the same year and was appointed Associate Professor in Applied Mathematics in 1991. Brian served as Head of Department for five years. He was a loved and respected teacher whose expertise in modeling and computing translated so well into the first year Applied Mathematics courses. He was the author of more than ten books on programming languages. We trust that the third edition of this book will continue to help students understand and exploit the full power of MATLAB both as a mathematical tool and as a programming language.
This page intentionally left blank
Preface
while on the other hand also stressing programming principles and algorithm development, with the help of structure plans.
Although most of MATLAB’s basic features are covered, the book is neither an exhaustive nor systematic reference manual, since this would not be in keeping with its informal style. Constructs, such as for and if, are not therefore always introduced in their most general form initially, as is common in many texts, but rather more gradually in the most natural places throughout the book. On the other hand, many texts present these constructs somewhat superficially; this book attempts to discuss them thoroughly. For the curious, there are helpful syntax and function quick references in the appendices.
MATLAB by its nature lends itself to a number of pitfalls for the unwary beginner. The text warns the user of these wherever possible.
The fundamentals of MATLAB are motivated throughout with many examples, from a number of different scientific and engineering areas, such as simulation, popu- lation modeling, and numerical methods, as well as from business and everyday life. Beginners, as well as experienced programmers wishing to learn MATLAB as an additional language, will therefore find plenty of interest in the book.
Emphasis is also placed on programming style throughout the book—writing clear and readable code.
Each chapter concludes with a summary of the MATLAB features introduced in the chapter.
There is a large collection of exercises at the end of each chapter, gleaned from the author’s many years’ experience of running hands-on programming courses for beginners and professionals alike, in BASIC, Pascal, C, C++ and MATLAB. Complete solutions to many of the exercises appear in an appendix.
There is a comprehensive and instructive index.
For the second edition, in working my way through Version 6, I found so many interesting new features (for example, GUIs) that I was unable to resist incorpo- rating most of them into the text. Consequently I decided to split the book into two parts. Part I contains what I consider to be the real essentials; Part II has everything else.
In this edition I have attempted to retain the style and approach of the first edition: informal, aimed at beginners, and with plenty of examples from science and engineering. Several of the chapters from the previous editions, which
xviii
Preface
feature the essential elements of MATLAB, have been brought together to form Part 1. In addition, I have added two new chapters. These are Chapters 3 and 14.
Chapter 3 describes a structured step-by-step method to achieve top-down design and algorithm development. The steps in the design process are applied in several examples. The intention is to get students thinking about how they need to formulate a problem to successfully utilize MATLAB. Chapter 14 on Dynamical Systems provides straightforward applications of the tools described and examined in the first 10 chapters. The problems solve are on relatively sim- ple dynamical systems of engineering and scientific interest. Since this book is an introductory course on MATLAB, a tool for technical computing, the exam- ples are mathematical formulations of problems from first courses in science and engineering. The purpose of the text is to provide instruction on how to solve the mathematical problems needed to gain insight into science and engi- neering. Thus, these eleven chapters (skipping over the sections marked with an asterisk) are sufficient for a first course in MATLAB. (For the computer and programming-calculator wise students, the chapters on more advanced topics should help them get into the application of MATLAB to solve the more complex problems confronted in upper division courses at university and, subsequently, on the job.)
This book can be used as a course textbook or for student self-study. For the latter, it is a useful supplemental text for any course in science and engineering. The instructor, of course, provides the necessary encouragement, enthusiasm and guidance to help the student begin to learn the power of MATLAB to solve numerous problems that engineers and scientists formulate in terms of math- ematics and, hence, help the student begin to master MATLAB. The book is written as a sequence of exercises, and the reader would benefit from doing the exercises within the text as well as doing some of the exercises at the end of the chapters.
To the student: I recommend that you read the text while you are at your com- puter so that you can do the exercises with MATLAB. It will be useful and fun for you to go through the exercises with the purpose of discovering how MATLAB does what it is commanded by you to do. You learn how to use a tool like MAT- LAB through hands-on experience. This, of course, is a good thing because it is quite pleasurable to learn by doing and, hence, discover how to use MATLAB to enhance your learning of engineering and science by tapping the wealth of capa- bility at your disposal in MATLAB. You will discover immediately that computer tools produce correct answers only when commands and input data are accu- rate and correct (no typographical errors are tolerated). ‘Debugging’—finding the errors in your typed command lines—is a big part of the game that is played
xix