Variables and Assignments 18Graphing with ezplot 22 Plotting Multiple Curves 25 The Current Directory and Search Path 28 The Command History Window 30 Wrapping Long Input and Output Line
Trang 3A Guide to M ATLAB ®
for Beginners and Experienced Users
Second Edition
Brian R HuntRonald L LipsmanJonathan M Rosenberg
with Kevin R Coombes John E Osborn Garrett J Stuck
Trang 5All of the University of Maryland, College Park
withKevin R CoombesJohn E OsbornGarrett J Stuck
Trang 6Cambridge University Press
The Edinburgh Building, Cambridgecb2 2ru, UK
First published in print format
Information on this title: www.cambridge.org/9780521850681
This publication is in copyright Subject to statutory exception and to the provision ofrelevant collective licensing agreements, no reproduction of any part may take placewithout the written permission of Cambridge University Press
Published in the United States of America by Cambridge University Press, New Yorkwww.cambridge.org
hardbackpaperbackpaperback
eBook (EBL)eBook (EBL)hardback
Trang 7The symbol✰ denotes a more advanced chapter or section
Who Should Read This Book xii
How This Book Is Organized xii
Conventions Used in This Book xiv
Algebraic or Symbolic Computation 10
Substituting in Symbolic Expressions 10
Symbolic Expressions, Variable Precision, and Exact
Trang 8Variables and Assignments 18
Graphing with ezplot 22
Plotting Multiple Curves 25
The Current Directory and Search Path 28
The Command History Window 30
Wrapping Long Input and Output Lines 38
Printing and Saving Graphics 38
Fine-Tuning Your M-Files 41
Symbolic and Floating-Point Numbers 48
Functions and Expressions 48
Variables in Script M-Files 50
Variables in Function M-Files 50
Structure of Function M-Files 51
Solving Linear Systems 53
Calculating Eigenvalues and Eigenvectors 53
Doing Calculus with MATLAB 54
Trang 9Curves in Three-Dimensional Space 62
Surfaces in Three-Dimensional Space 64
Multiple Figure Windows 66
Combining Plots in One Window 67
Branching with switch 91
Breaking from a Loop 93
Other Programming Commands 94
Cell and Structure Arrays 94
Commands for Parsing Input and Output 95
Evaluation and Function Handles 97
User Input and Screen Output 98
Trang 10✰ Interacting with the Operating System 100
Calling External Programs 101
File Input and Output 102
Fine Points of Publishing 103
Saving and Running a GUI 126
GUI Callback Functions 127
✰ Numerical Solution of the Heat Equation 175
✰ A Model of Traffic Flow 185
Error or Warning Messages When Plotting 209
A Previously Saved M-File Evaluates Differently 210
Computer Won’t Respond 211
The Most Common Mistakes 211
Trang 11Contents ix
Solutions to Practice Set A: Algebra and Arithmetic 219
Solutions to Practice Set B: Calculus, Graphics, and Linear Algebra 231
Solutions to Practice Set C: Developing Your MATLAB Skills 255
Trang 13MATLAB is a high-level technical computing language and interactiveenvironment for algorithm development, data visualization, data analysis,and numerical computation Using MATLAB, you can solve technicalcomputing problems faster than with traditional programming languages,such as C, C++, and Fortran – The MathWorks, Inc
That statement encapsulates the view of The MathWorks, Inc., the developer of
MAT-LAB® MATLAB 7 is an ambitious program It contains hundreds of commands to
do mathematics You can use it to graph functions, solve equations, perform statisticaltests, and much more It is a high-level programming language that can communicatewith its cousins, e.g., Fortran and C You can produce sound and animate graphics.You can do simulations and modeling (especially if you have access not just to basicMATLAB but also to its accessory Simulink®) You can prepare materials for export
to the World Wide Web In addition, you can use MATLAB to combine ical computations with text and graphics in order to produce a polished, integrated,interactive document
mathemat-A program this sophisticated contains many features and options There are ally hundreds of useful commands at your disposal The MATLAB help documenta-tion contains thousands of entries The standard references, whether the MathWorksUser’s Guide for the product, or any of our competitors, contain a myriad of tablesdescribing an endless stream of commands, options, and features that the user might
liter-be expected to learn or access
MATLAB is more than a fancy calculator; it is an extremely useful and versatiletool Even if you know only a little about MATLAB, you can use it to accomplishwonderful things The hard part, however, is figuring out which of the hundreds ofcommands, scores of help pages, and thousands of items of documentation you need
to look at to start using it quickly and effectively
That’s where we come in
Why We Wrote This Book
The goal of this book is to get you started using MATLAB successfully and quickly
We point out the parts of MATLAB you need to know without overwhelming youwith details We help you avoid the rough spots We give you examples of real uses
of MATLAB that you can refer to when you’re doing your own work We provide
a handy reference to the most useful features of MATLAB When you’ve finished
xi
Trang 14reading this book, you will be able to use MATLAB effectively You’ll also be ready
to explore more of MATLAB on your own
You might not be a MATLAB expert when you finish this book, but you will beprepared to become one – if that’s what you want We figure you’re probably moreinterested in being an expert at your own specialty, whether that’s finance or physics,psychology or engineering You want to use MATLAB the way we do, as a tool.This book is designed to help you become a proficient MATLAB user as quickly aspossible, so you can get on with the business at hand
Who Should Read This Book
This book will be useful to complete novices, occasional users who want to sharpentheir skills, intermediate or experienced users who want to learn about the new fea-tures of MATLAB 7, or who want to learn how to use Simulink, and even experts whowant to find out whether we know anything they don’t
You can read through this guide to learn MATLAB on your own If your employer(or your professor) has plopped you in front of a computer with MATLAB and toldyou to learn how to use it, then you’ll find the book particularly useful If you areteaching or taking a course in which you want to use MATLAB as a tool to exploreanother subject – whether in mathematics, science, engineering, business, or statistics– this book will make a perfect supplement
As mentioned, we wrote this guide for use with MATLAB 7 If you plan tocontinue using MATLAB 5 or MATLAB 6, however, you can still profit from thisbook Virtually all of the material on MATLAB commands in this book applies to allthese versions The primary features of MATLAB 7 not found in earlier versions areanonymous functions, discussed in Chapter 2, and publishing, discussed in Chapters
3 and 7 Beyond that, only a small amount of material on the MATLAB interface,found mainly in Chapters 1, 3, and 9, does not apply to MATLAB 5
How This Book Is Organized
In writing, we used our experience to focus on providing important information asquickly as possible The book contains a short, focused introduction to MATLAB Itcontains practice problems (with complete solutions) so you can test your knowledge.There are several illuminating sample projects that show you how MATLAB can beused in real-world applications and an entire chapter on troubleshooting
The core of this book consists of about 70 pages: Chapters 1–4, and the beginning
of Chapter 5 Read that much and you’ll have a good grasp of the fundamentals ofMATLAB Read the rest – the remainder of the Graphics chapter as well as the chap-ters on Programming, Publishing, Simulink, GUIs, Applications, Troubleshooting,and the Glossary – and you’ll know enough to do a great deal with MATLAB.Here is a detailed summary of the contents of the book
Chapter 1, Getting Started, describes how to start MATLAB on various platforms.
It tells you how to enter commands, how to access online help, how to recognize the
Trang 15How This Book Is Organized xiii
various MATLAB windows you will encounter, and how to exit the application
Chapter 2, MATLAB Basics, shows you how to do elementary mathematics using
MATLAB This chapter contains the most essential MATLAB commands
Chapter 3, Interacting with MATLAB, contains an introduction to the MATLAB
Desktop interface This chapter will introduce you to the basic window features ofthe application, to the small program files (M-files) that you will use to make the mosteffective use of the software, and to a few methods for presenting the results of yourMATLAB sessions After completing this chapter, you’ll have a better appreciation
of the breadth described in the quote that opens this Preface
Practice Set A, Algebra and Arithmetic, contains some simple problems for
prac-ticing your newly acquired MATLAB skills Solutions are presented at the end of thebook
Chapter 4, Beyond the Basics, contains an explanation of some of the finer points
that are essential for using MATLAB effectively
Chapter 5, MATLAB Graphics, contains a more detailed look at many of the
MAT-LAB commands for producing graphics
Practice Set B, Calculus, Graphics, and Linear Algebra, gives you another chance
to practice what you’ve just learned As before, solutions are provided at the end ofthe book
Chapter 6, Programming, introduces you to the programming features of
MAT-LAB This chapter is designed to be useful both to the novice programmer and to theexperienced Fortran or C programmer
Chapter 7, Publishing and M-Books, contains an introduction to the
word-pro-cessing and desktop-publishing features available in MATLAB 7, either using M-files
and the publish command or else combining MATLAB with Microsoft Word.
Chapter 8, Simulink, describes the MATLAB companion software Simulink, a
graphically oriented package for modeling, simulating, and analyzing dynamical tems Many of the calculations that can be done with MATLAB can be done equallywell with Simulink If you don’t have access to Simulink, you may skip Chapter 8
sys-Chapter 9, GUIs, contains an introduction to the construction and deployment of Graphical User Interfaces, that is GUIs, using MATLAB This chapter is a little more
advanced than most of the others
Chapter 10, Applications, contains examples, from many different fields, of
solu-tions of real-world problems using MATLAB and/or Simulink
Practice Set C, Developing Your MATLAB Skills, contains practice problems whose
solutions use the methods and techniques you learned in Chapters 6–10
Chapter 11, Troubleshooting, is the place to turn when anything goes wrong.
Many common problems can be resolved by reading (and rereading) the advice inthis chapter
Next, we have Solutions to the Practice Sets, which contains solutions to all the problems from the three Practice Sets The Glossary contains short descriptions (with
examples) of many MATLAB commands and objects Though it is not a completereference, the Glossary is a handy guide to the most important features of MATLAB
Finally, there is a comprehensive Index.
Trang 16Conventions Used in This Book
We use distinct fonts to distinguish various entities When new terms are first
in-troduced, they are typeset in an italic font Output from MATLAB is typeset in a
monospaced typewriter font; commands that you type for interpretation by
MATLAB are indicated by a boldface version of that font These commands and
responses are often displayed on separate lines as they would be in a MATLAB sion, as in the following example:
ses->> x = sqrt(2*pi + 1)
x =
2.697
Selectable menu items (from the menu bars in the MATLAB Desktop, figure
win-dows, etc.) are typeset in a boldface font Submenu items are separated from menu items by a colon, as in File:Open Labels such as the names of windows and buttons
are quoted, in a “regular” font File and folder names, as well as web addresses, areprinted in a typewriter font Finally, names of keys on your computer keyboardare set in aSMALL CAPSfont
We use six special symbols throughout the book Here they are, together withtheir meanings
☞ Paragraphs like this one contain cross-references to other parts of the book,
or suggestions of where you can skip ahead to another chapter.
➯ Paragraphs like this one contain important notes Our favorite is “Save your work frequently.” Pay careful attention to these paragraphs.
✓ Paragraphs like this one contain useful tips or point out features of interest inthe surrounding landscape You might not need to think carefully about them
on a first reading, but they may draw your attention to some of the finer points
of MATLAB if you go back to them later
✰ Chapters, sections, or problems starting with this symbol are a little more advancedthan the rest of the book, and can be skipped on first reading if you wish
Symbolic Paragraphs like this discuss features of MATLAB’s Symbolic Math Toolbox,
used for symbolic (as opposed to numerical) calculations If you are not using the
Symbolic Math Toolbox, you can skip these sections
Paragraphs like this discuss features of Simulink If you are not using Simulink,you can skip these sections
Incidentally, if you are a student and you have purchased the MATLAB StudentVersion, then the Symbolic Math Toolbox and Simulink are automatically includedwith your software, along with basic MATLAB
Trang 17About the Authors xv
About the Authors
We are mathematics professors at the University of Maryland, College Park We haveused MATLAB in our research, in our mathematics courses, for presentations anddemonstrations, for production of graphics for books and for the Web, and even tohelp our kids do their homework We hope you’ll find MATLAB as useful as we do,and that this book will help you learn to use it quickly and effectively
Acknowledgment and Disclaimer. We are pleased to acknowledge support of ourresearch by the National Science Foundation, which contributed over many years tothe writing of this book Our work on the second edition was partially supported
by NSF Grants DMS-0103647, DMS-0104087, ATM-0434225, and DMS-0504212.Any opinions, findings, and conclusions or recommendations expressed in this mate-rial are those of the authors and do not necessarily reflect the views of the NationalScience Foundation
Trang 19Chapter 1
Getting Started
In this chapter, we will introduce you to the tools you need in order to begin usingMATLAB effectively These include the following: some relevant information oncomputer platforms and software; installation protocols; how to launch MATLAB,enter commands and use online help; a roster of MATLAB’s various windows; andfinally, how to exit the program We know you are anxious to get started using MAT-LAB, so we will keep this chapter brief After you complete it, you can go immedi-ately to Chapter 2 to find concrete and simple instructions for using MATLAB to domathematics We describe the MATLAB interface more elaborately in Chapter 3
Platforms and Versions
It is likely that you will use MATLAB on a computer running Microsoft Windows or
on some form of a UNIX operating system (such as Linux) Some previous versions
of MATLAB (Releases 11 and 12) did not support Macintosh, but the most currentversions (Releases 13 and 14) do If you are using a Macintosh, you should find thatour instructions for Windows will suffice for most of your needs Like MATLAB
6 (Releases 12 and 13), and unlike earlier versions, MATLAB 7 (Release 14) looksvirtually identical on these different platforms For definitiveness, we shall assumethat the reader is using a Windows computer In those very few instances where ourinstructions must be tailored differently for Linux, UNIX, or Macintosh users, weshall point it out clearly
✓ We use the word Windows to refer to all flavors of the Windows operating
system MATLAB 7 (R14) will run on Windows 2000, Windows NT (4.0 and higher), and on Windows XP MATLAB 7 will not run on Windows 95, Windows 98, or on Windows ME However, MATLAB 6.5 (R13) does run on
Windows 98 or Windows ME
This book is written to be compatible with the current version of MATLAB,namely MATLAB 7 (R14) The vast majority of the MATLAB commands we de-scribe, as well as many features of the MATLAB interface (e.g., the M-file Edi-tor/Debugger and M-books) are valid for version 6.5 (R13), and earlier versions insome cases When important differences between different versions arise, we willpoint them out We also note that the differences between the MATLAB ProfessionalVersion and the MATLAB Student Version are rather minor, and virtually unnotice-able to a beginner, or even a mid-level user Again, in the few instances where we
1
Trang 20describe a MATLAB feature that is available only in the Professional Version, wehighlight that fact clearly.
Installation
If you intend to run MATLAB, especially the Student Version, on your own computer,
it is quite possible that you will have to install it yourself You can easily accomplishthis using the product CDs Follow the installation instructions as you would withinstallation of any new software At some point in the installation you may be asked
which toolboxes you wish to install Unless you have severe space limitations, we
suggest that you install any that seem of interest to you or that you think you mightuse at some point in the future However, for the purposes of this book, you should be
sure to include the Symbolic Math Toolbox We also strongly encourage you to install
Simulink, which is described in Chapter 8
Starting MATLAB
You start MATLAB as you would any other software application In Windows, you
access it via the Start menu, under a name like MATLAB 7.0 or Student MATLAB.
Alternatively, you may have a desktop icon that enables you to start MATLAB with
a simple double-click In Linux or UNIX, generally you need only type matlab in
a terminal window, though you may first have to find the bin subdirectory of theMATLAB installation directory and add it to your path Or you may have an icon onyour desktop that achieves the task
However you start MATLAB, you will briefly see a window that displays the
MATLAB logo as well as some product information, and then a MATLAB Desktop window will launch That window will contain a title bar, a menu bar, a tool bar
and four embedded windows, one of which is hidden The largest and most important
window is the Command Window on the right We will go into more detail in ter 3 on the use and manipulation of the other three windows: the Command History
Chap-Window, the Current Directory Browser and the Workspace Browser For now we
concentrate on the Command Window in order to get you started issuing MATLABcommands as quickly as possible At the top of the Command Window, you maysee some general information about MATLAB, perhaps some special instructions for
getting started or accessing help, but most important of all, you will see a command
prompt (>> or EDU>>) If the Command Window is “active,” its title bar will be
dark, and the prompt will be followed by a cursor (a blinking vertical line) That
is the place where you will enter your MATLAB commands (see Chapter 2) If theCommand Window is not active, just click in it anywhere Figure 1.1 contains anexample of a newly launched MATLAB Desktop
Trang 21Typing in the Command Window 3
Figure 1.1 A MATLAB Desktop
✓ MATLAB 6 has a Desktop, but in older versions of MATLAB, for example5.3, there was no integrated Desktop Only the Command Window appearedwhen you launched the application (On UNIX systems, the terminal win-dow from which you invoked MATLAB 5 became the Command Window.)Commands that we instruct you to enter in the Command Window inside theDesktop for MATLAB can be entered directly into the Command Window inany older version
Typing in the Command Window
Click in the Command Window to make it active When a window becomes active,its title bar darkens and a blinking cursor appear after the prompt Now you can begin
entering commands Try typing 2+2, then press the ENTERor RETURNkey Next try
factor(123456789) , and finally sin(100) Your MATLAB Desktop should
look like Figure 1.2
Online Help
MATLAB has extensive online help In fact, using only this book and the online help,you should be able to become quite proficient with MATLAB
You can access the online help in one of several ways Typing help at the
com-mand prompt will reveal a long list of topics for which help is available Just to
illustrate, try typing help general Now you see a long list of “general purpose” MATLAB commands Next, try help factor to learn about the factor com-
mand In every instance above, more information than your screen can hold will
Trang 22Figure 1.2 The MATLAB Desktop with Several Commands Evaluated.
scroll by You can use the scroll bar on the right of the window to scroll back up.Alternatively, you can force MATLAB to display information one screenful at a time
by typing more on You press the space bar to display the next screenful; type help
more for details Typing more on affects all subsequent commands, until you type
more off
The lookfor command searches the first line of every MATLAB help file for a specified string (use lookfor -all to search all lines) For example, if you wanted
to see a list of all MATLAB commands that contain the word “factor” as part of the
command name or brief description, then you would type lookfor factor If the command you are looking for appears in the list, then you can use help on that
command to learn more about it
While help in the Command Window is useful for getting quick information on
a particular command, more extensive documentation is available via the MATLAB
Help Browser You can activate it in several ways, for example, by typing doc at
the command prompt Alternatively, it is available through the menu bar under Help.
Finally, the question-mark button on the tool bar will also invoke the Help Browser
Upon its launch you will see two windows or panes The first is called the Help
Navigator; it is used to find documentation The second, called the display pane, is
used for viewing documentation The display pane works much like a normal webbrowser It has an address window, buttons for moving forward and back (among thewindows you have visited), hyperlinks for moving around in the documentation, thecapability of storing favorite pages, and other useful tools
A particularly useful way to invoke the Help Browser is to type, for example,
doc sin This launches the Help Browser and displays the reference page for sin.
The reference page for a command is generally similar to the text available (through
help), but sometimes has more information
Trang 23Online Help 5
You can also use the Help Navigator to locate the documentation that you willexplore in the display pane The Help Navigator has four tabs that allow you to
arrange your search for documentation in different ways The first is the Contents tab
that displays a tree view of all the documentation topics available The extent of thattree will be determined by how much you (or your system administrator) included inthe original MATLAB installation (how many toolboxes, etc.) The second tab is an
Index that displays all available documentation in index format It responds to your
key entry of likely items you want to investigate in the usual alphabetic reaction mode
The third tab provides the Search mechanism You type in what you seek, either a
function or some other descriptive term, and the search engine locates documentation
pertaining to your entry Finally, the fourth tab is a small collection of Demos that
you can run to learn more about MATLAB Clicking on an item that appears in any
of these tabs brings up the corresponding documentation in the display pane
The Help Browser has an excellent tutorial describing its own operation To view
it, open the browser and select Help:Using the Help Browser from its menu bar The
Help Browser is a powerful and easy-to-use aid in finding the information you need
on various features of MATLAB Like any such tool, the more you use it, the more
adept you become at its use Figure 1.3 depicts the MATLAB Help Browser.
Figure 1.3 The MATLAB Help Browser
✓ If you are working with MATLAB version 5.3 or earlier, then typing help,
help general or help factor at the command prompt will work as
indicated above The Help Browser is not available, but the commands
helpwin and helpdesk call up more primitive, although still quite useful,
forms of help windows
If you are patient, and not overly anxious to get to Chapter 2, you can type demo
to try some of MATLAB’s online demonstrations
Trang 24MATLAB Windows
We have already described the MATLAB Command Window and the Help Browser,and have mentioned in passing the Command History Window, the Current DirectoryBrowser, and the Workspace Browser These, and several other windows you willencounter as you work with MATLAB, will allow you to do the following: controlfiles and folders that you and MATLAB will need to access; write and edit the smallMATLAB programs (M-files) that you will use to run MATLAB effectively; keeptrack of the variables and functions that you define as you use MATLAB; display andmanipulate graphics; and design models to solve problems and simulate processes.Some of these windows launch separately, and some are embedded in the Desktop
You can dock into the Desktop those that launch separately through their Desktop
menus, or by clicking on the downward curved arrow in their tool bars You canseparate windows inside your MATLAB Desktop out to your computer desktop byclicking on the upward curved arrow in the upper right-hand corner of the window’stool bar
These features are described more thoroughly in later chapters For now, we want
to call your attention to the other main type of window you will encounter, namelygraphics windows Many of the commands you issue will generate graphics or pic-
tures These will appear in a separate window, called a figure window In Chapter 5,
we will teach you how to generate and manipulate MATLAB figure windows mosteffectively
See Figure 2.1 in Chapter 2 for a simple example of a figure window
✓ In MATLAB 6 or earlier versions, you cannot dock figure windows Nor canyou in version 7 if you are using a Macintosh
Ending a Session
The simplest way to conclude a MATLAB session is to type quit at the prompt You
can also click on the button that generally closes your windows (usually an× in the
upper right-hand corner) Still another way to exit is to use the Exit MATLAB item
from the File menu of the Desktop Before you exit MATLAB, you should be sure
to save your work, print any graphics or other files you need, and in general clean upafter yourself Some strategies for doing so are discussed in Chapter 3
Trang 25Chapter 2
MATLAB Basics
In this chapter, you will start learning how to use MATLAB to do mathematics Werecommend that you read this chapter while running MATLAB Try the commands asyou go along Feel free to experiment with variants of the examples we present; thebest way to find out how MATLAB responds to a command is to try it
☞ For further practice, you can work the problems in Practice Set A You may also consult the Glossary for a synopsis of many MATLAB operators, con- stants, functions, commands, and programming instructions.
Input and Output
You input commands to MATLAB in the Command Window MATLAB returns put in two ways: typically, text or numerical output is returned in the same CommandWindow, but graphical output appears in a separate figure window A sample screen,with both a MATLAB Desktop and a figure window, labeled “Figure 1”, is shown in
out-Figure 2.1 To generate this screen on your computer, first type 1/2 + 1/3 Then type ezplot(’xˆ3 - x’).
Figure 2.1 MATLAB Windows
7
Trang 26✓ While MATLAB is working, it may display a “wait” symbol – for example,
an hourglass appears on many operating systems Or it may give no visualevidence until it is finished with its calculation
Arithmetic
As we have just seen, you can use MATLAB to do arithmetic as you would a
cal-culator You can add with +, subtract with -, multiply with *, divide with /, and exponentiate with ˆ For example:
>> 3ˆ2 - (5 + 4)/2 + 6*3
ans =
22.5000
MATLAB prints the answer and assigns the value to a variable called ans If you
want to perform further calculations with the answer, you can use the variable ans
rather than retype the answer For example, you can compute the sum of the squareand the square root of the previous answer as follows:
>> ansˆ2 + sqrt(ans)
ans =
510.9934
Observe that MATLAB assigns a new value to ans with each calculation To do more
complex calculations, you can assign computed values to variables of your choosing.For example:
display more digits, type format long Then all subsequent numerical output will have 15 digits displayed Type format short to return to 5-digit display.
MATLAB differs from a calculator in that it can do exact arithmetic For example,
it can add the fractions 1/2 and 1/3 symbolically to obtain the correct fraction 5/6.
We discuss how to do this in the section Symbolic Expressions, Variable Precision,
and Exact Arithmetic later in this chapter.
Trang 27Recovering from Problems 9
Recovering from Problems
Inevitably, when using any mathematical software system, you are bound to encounterminor glitches Even while entering simple arithmetic commands, you may acciden-tally mistype an entry or inadvertently violate a MATLAB rule In this brief section,
we mention three methods for coping with these kinds of problems
Errors in Input
If you make an error in an input line, MATLAB will normally print an error message
For example, here’s what happens when you try to evaluate 3uˆ2:
>> 3uˆ2
??? 3uˆ2
|
Error: Missing MATLAB operator.
The error is a missing multiplication operator * The correct input would be
3*uˆ2 Note that MATLAB places a marker (a vertical line segment) at the placewhere it thinks the error might be; however, the actual error may have occurred earlier
or later in the expression
✓ The error message generated in MATLAB 7.0.4 (the latest upgrade as this iswritten) is somewhat different You will find that error and warning messagesyou encounter may vary with versions of the program
➯ Missing multiplication operators and parentheses are among the most common input errors made by beginning users.
☞ Recall our discussion of online help in Chapter 1 If you can’t decipher an error message caused by a MATLAB command, refer to the online help for that command, or use the search feature of the Help Browser.
You can edit an input line by using theUP-ARROWkey to redisplay the previouscommand, editing the command using theLEFT- andRIGHT-ARROWkeys, and thenpressing RETURN or ENTER The UP- andDOWN-ARROW keys allow you to scrollback and forth through all the commands you’ve typed in a MATLAB session, andare very useful when you want to correct, modify, or reenter a previous command
Aborting Calculations
If MATLAB gets hung up in a calculation, or seems to be taking too long to perform
an operation, you can usually abort it by typing CTRL+C; that is, hold down the keylabeled CTRL, or CONTROL, and press C While not foolproof, this is the method ofchoice when MATLAB is not responding
Trang 28Algebraic or Symbolic Computation
symbolic calculations such as factoring polynomials or solving algebraic equations
Type help symbolic to make sure that the Symbolic Math Toolbox is installed on
your system
To perform symbolic computations, you must use syms to declare the variables
you plan to use to be symbolic variables Consider the following series of commands:
in-Although MATLAB makes minor simplifications to the expressions you type,
it does not make major changes unless you tell it to The command expand told MATLAB to multiply out the expression, and factor forced MATLAB to restore it
to factored form
MATLAB has a command called simplify, which you can sometimes use to
express a formula as simply as possible For example,
>> simplify((xˆ3 - yˆ3)/(x - y))
ans =
xˆ2+x*y+yˆ2
✓ MATLAB has a more robust command, called simple, that sometimes does
a better job than simplify Try both commands on the trigonometric expression sin(x)*cos(y) + cos(x)*sin(y) to compare – you’ll have to read the online help for simple to completely understand the an-
swer
Substituting in Symbolic Expressions
When you work with symbolic expressions you often need to substitute a numericalvalue, or even another symbolic expression, for one (or more) of the original variables
Trang 29Algebraic or Symbolic Computation 11
in the expression This is done by using the subs command For example, presuming that the symbol expression w is defined and it involves the symbolic variable u, then the command subs(w, u, 2) will substitute the value 2 for the variable u in the expression w More examples:
Symbolic Expressions, Variable Precision, and Exact Arithmetic
As we have noted, MATLAB uses floating-point arithmetic for its calculations Usingthe Symbolic Math Toolbox, you can also do exact arithmetic with symbolic expres-sions Consider the following example:
>> cos(pi/2)
ans =
6.1232e-17
The answer is written in floating-point format and means 6.1232 × 10 −17 However,
we know that cos(π/2) is really equal to 0 The inaccuracy is due to the fact that
typing pi in MATLAB gives an approximation to π accurate to about 15 digits, not
its exact value To compute an exact answer, instead of an approximate answer, we
Trang 30must create an exact symbolic representation of π/2 by typing sym(’pi/2’) Now
let’s take the cosine of the symbolic representation of π/2:
>> cos(sym(’pi/2’))
ans =
0
This is the expected answer
The quotes around pi/2 in sym(’pi/2’) create a string consisting of the
char-acters pi/2 and prevent MATLAB from evaluating pi/2 as a floating-point number The command sym converts the string to a symbolic expression.
The commands sym and syms are closely related In fact, syms x is equivalent
to x = sym(’x’) The command syms has a lasting effect on its argument In fact, even if x was previously defined, syms x clears that definition and renders x a
symbolic variable – which it remains until (if ever) it is redefined On the other hand,
sym has only a temporary effect unless you assign the output to a variable, as in x =
If you don’t specify the number of digits, the default setting is 32 You can change
the default with the command digits.
➯ You should be wary of using sym or vpa on an expression that MATLAB must evaluate before applying variable-precision arithmetic To illus- trate, evaluate the expressions 3ˆ45, vpa(3ˆ45), and vpa(’3ˆ45’) The first gives a floating-point approximation to the answer, the second – because MATLAB carries only 16-digit precision in its floating-point evaluation of the exponentiation – gives an answer that is correct only in its first 16 digits, and the third gives the exact answer.
☞ See the section Symbolic and Floating-Point Numbers in Chapter 4 for details about how MATLAB converts between symbolic and floating-point numbers.
Vectors and Matrices
MATLAB was written originally to allow mathematicians, scientists, and engineers
to handle the tools of linear algebra – that is, vectors and matrices – as effortlessly aspossible In this section we introduce these concepts
Trang 31Vectors and Matrices 13
Vectors
A vector is an ordered list of numbers You can enter a vector of any length in
MAT-LAB by typing a list of numbers, separated by commas and/or spaces, inside squarebrackets For example:
The notation 1:9 is used to represent a vector of numbers running from 1 to 9 in
increments of 1 The increment can be specified as the middle of three arguments:
You can perform mathematical operations on vectors For example, to square the
elements of the vector X, type
>> X.ˆ2
ans =
Trang 32The period in this expression is very important; it says that the numbers in X should
be squared individually, or element-by-element Typing Xˆ2 would tell MATLAB to
use matrix multiplication to multiply X by itself and would produce an error message
in this case (We discuss matrices below and in Chapter 4.) Similarly, you must type
.* or / if you want to multiply or divide vectors element-by-element For example,
to multiply the elements of the vector X by the corresponding elements of the vector
A matrix is a rectangular array of numbers Row and column vectors, which we
discussed above, are examples of matrices Consider the 3× 4 matrix
Note that the matrix elements in any row are separated by commas, and the rows are
separated by semicolons The elements in a row can also be separated by spaces
If two matrices A and B are the same size, their (element-by-element) sum is obtained by typing A + B You can also add a scalar (a single number) to a matrix;
A + c adds c to each element in A Likewise, A - B represents the difference of
A and B, and A - c subtracts the number c from each element of A If A and B are
multiplicatively compatible, i.e., if A is n × m and B is m × , then their product A*B
is n × Recall that the element of A*B in the ith row and jth column is the sum of
the products of the elements from the ith row of A times the elements from the jth
Trang 33Suppressing Output 15
The product of a number c and the matrix A is given by c*A, and A’ represents the conjugate transpose of A (For more information, see the online help for ctranspose and transpose.)
A simple illustration is given by the matrix product of the 3× 4 matrix A above
by the 4× 1 column vector Z’:
The result is a 3× 1 matrix, in other words, a column vector.
☞ MATLAB has many commands for manipulating matrices You can read about them in the section More about Matrices in Chapter 4 and in the online help; some of them are illustrated in the section Linear Economic Models in Chapter 10.
Suppressing Output
Typing a semicolon at the end of an input line suppresses printing of the output of theMATLAB command The semicolon should generally be used when defining large
vectors or matrices (such as X = -1:0.1:2;) It can also be used in any other
situation where the MATLAB output need not be displayed
Functions
In MATLAB you will use both built-in functions and functions that you create self
your-Built-in Functions
MATLAB has many built-in functions These include sqrt, cos, sin, tan, log,
exp , and atan (for arctan) as well as more specialized mathematical functions like
gamma , erf, and besselj MATLAB also has several built-in constants,
includ-ing pi (the number π), i (the complex number i = √
−1), and Inf (∞) Some
Trang 34To get an exact answer, you need to use a symbolic argument.
>> sin(sym(’2*pi/3’))
ans =
1/2*3ˆ(1/2)
User-Defined Functions
In this section we will examine two methods to define your own functions in
MAT-LAB The first uses the command inline, and the second uses the operator @ to
create what is called an “anonymous function.” The latter method is new in
MAT-LAB 7, and is now the preferred method We shall mention inline periodically for
the sake of users of earlier versions, but we strongly recommend that users of
MAT-LAB 7, and users of older versions when they upgrade, adopt @ as the usual method
for defining their functions Functions can also be defined in separate files calledM-files – see Chapter 3
Here’s how to define the function f (x) = x2using these commands
As we observed earlier, most MATLAB functions can operate on vectors as well
as scalars To insure that your user-defined function can act on vectors, insert dots
before the mathematical operators *, /, and ˆ Thus to obtain a vectorized version of
Trang 35Managing Variables 17
ans =
You can plot f and f1, using MATLAB graphics, in several ways that we will
explore in the section Graphics later in this chapter We conclude this section by
remarking that one can also define functions of two or more variables For example,either of the following
>> g = @(x, y) xˆ2 + yˆ2; g(1, 2)
>> g1 = inline(’xˆ2 + yˆ2’, ’x’, ’y’); g1(1, 2)
results in the answer 5 If instead you define
num-be hard to rememnum-ber the names and types of all the variables you have defined You
can type whos to see a summary of the names and types, or classes, of your currently
defined variables But before you do that, first assign a = pi, b = ’pi’, and c =
sym(’pi’) ; now type whos Here’s the output for the MATLAB session displayed
Trang 36x 1x1 126 sym object
Grand total is 183 elements using 2968 bytes
The variables A, X, Y, Z, a, and d were assigned numerical data and are reported
as “double array” That means that they are arrays of double-precision numbers; in
this case the arrays a and d are of size 1× 1, i.e., scalars The “Bytes” column shows
how much computer memory is allocated to each variable Also, ans is numerical
since the last unassigned output was a 1×2 vector The variable b is a string, reported
as “char array”, while the variables c, u, v, w, x and y are symbolic Finally we see
two function handles and two inline objects, corresponding to the pairs of anonymousfunctions and inline functions
The command whos shows information about all defined variables, but it does
not show the values of the variables To see the value of a variable, simply type thename of the variable and press ENTERor RETURN
MATLAB commands expect particular classes of data as input, and it is tant to know what class of data is expected by a given command; the help text for acommand usually indicates the class or classes of input it expects The wrong class
impor-of input usually produces an error message or unexpected output For example, type
sin(’pi’)to see how unexpected output can result from supplying a string to afunction that isn’t designed to accept strings
To clear all defined variables, type clear or clear all You can also type, for example, clear x y to clear only x and y.
You should generally clear variables before starting a new calculation Otherwisevalues from a previous calculation can creep into the new calculation by accident
Finally, we observe that the Workspace Browser presents a graphical alternative to
whos You can activate it by clicking on its tab under the Current Directory Browser,
or by typing workspace at the command prompt Figure 2.2 depicts a Desktop in
which the Command Window and the Workspace Browser contain the same tion as displayed above
informa-Variables and Assignments
In MATLAB, you use the equal sign to assign values to a variable For instance,
Trang 37Variables and Assignments 19
Figure 2.2 Desktop with the Workspace Browser
You can make very general assignments for symbolic variables and then late them:
un-ters For example, you might use cubicsol as the name of the solution of a cubic
Trang 38Solving Equations
You can solve equations involving variables with solve or fzero For example, to
find the solutions of the quadratic equation x2− 2x − 4 = 0, type
The answer consists of the exact (symbolic) solutions (3± √ 19i)/2 (complex
num-bers, where the letter i in the answer stands for the imaginary unit √
which variable(s) to solve for For example, type solve(’2*x - log(y) =
1’, ’y’) to solve 2x − log y = 1 for y in terms of x You can specify more
than one equation as well For example:
This system of equations has two solutions MATLAB reports the solution by giving
the two x-values and the two y-values for those solutions Thus the first solution consists of the first value of x together with the first value of y You can extract these
values by typing x(1) and y(1):
>> x(1)
ans =
1+2*2ˆ(1/2)
>> y(1)
Trang 39Solving Equations 21
ans =
7+4*2ˆ(1/2)
The second solution can be extracted with x(2) and y(2).
Note that, in the preceding solve command, we assigned the output to the vector
[x, y] If you use solve on a system of equations without assigning the output to
a vector, then MATLAB does not automatically display the values of the solution:
>> sol = solve(’xˆ2 - y = 2’, ’y - 2*x = 5’)
sol =
x: [2x1 sym]
y: [2x1 sym]
To see the vectors of x- and y-values of the solution, type sol.x and sol.y To see
the individual values, type sol.x(1), sol.y(1), etc.
☞ In this example, the output of solve is a structure array See the section Cell
and Structure Arrays in Chapter 6 for more about this data class.
Some equations cannot be solved symbolically, and in these cases solve tries to
find a numerical answer For example:
You can numerically find the (approximate) solutions shown on the graph with the
fzerocommand, which looks for a zero of a given function near a specified value
of x A solution of the equation e −x = sin(x) is a zero of the function e −x − sin(x),
so to find an approximate solution near x = 0.5, type
Trang 400 2 4 6 8 10
−1
−0.5 0 0.5 1
x exp(−x) and sin(x)
Figure 2.3 Two Intersecting Curves
Graphics
In this section, we introduce MATLAB’s two basic plotting commands and show how
to use them
Graphing with ezplot
The simplest way to graph a function of one variable is with ezplot, which expects
a string, a symbolic expression, or an anonymous function, representing the function
to be plotted For example, to graph x2+ x + 1 on the interval −2 to 2 (using the
string form of ezplot), type
>> ezplot(’xˆ2 + x + 1’, [-2 2])
The plot will appear on the screen in a new window labeled “Figure 1”
Using a symbolic expression, you can produce the plot in Figure 2.4 with the ing input:
follow->> syms x, ezplot(xˆ2 + x + 1, [-2 2])
Finally, you can use an anonymous function as the argument to ezplot, as in:
>> ezplot(@(x) x.ˆ2 + x + 1, [-2 2])
✓ Graphs can be misleading if you do not pay attention to the axes For
exam-ple, the input ezplot(xˆ2 + x + 3, [-2 2]) produces a graph that
looks identical to the previous one, except that the vertical axis has differenttick marks (and MATLAB assigns the graph a different title)