Tải bản đầy đủ (.pdf) (24 trang)

matlab programming for engineers

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (1.6 MB, 24 trang )

MATLAB
®
Programming
for Engineers
Fourth Edition
Stephen J. Chapman
BAE SYSTEMS Australia
Australia • Canada • Mexico • Singapore • Spain • United Kingdom • United States
00USE_FM.qxd 10/5/07 1:43 PM Page iii
Copyright 2008 Cengage Learning, Inc. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Licensed to:
iChapters User
Publisher:
Chris Carson
Developmental Editor:
Hilda Gowans
Permissions Coordinator:
Kristiina Bowering
Production Services:
RPK Editorial Services
Copy Editor:
Harlan James
Proofreader:
Erin Wagner
Indexer:
Shelly Gerger-Knechtl
Production Manager:
Renate McCloy
Creative Director:
Angela Cluer
Interior Design:


Carmela Pereira
Cover Design:
Andrew Adams
Compositor:
Integra
Printer:
Webcom Limited
COPYRIGHT © 2008 by Thomson
Learning, part of the Thomson
Corporation
Printed in Canada
123407
For more information contact
Thomson Learning,
1120 Birchmount Road,
Toronto, Ontario, Canada,
MIK 5G4. Or you can visit our
Internet site at

Library Congress Control Number:
2007932905
ISBN-10: 0-495-24449-X
ISBN-13: 978-0-495-24449-3
ALL RIGHTS RESERVED. No part of
this work covered by the copyright
herein may be reproduced, tran-
scribed, or used in any form or by
any means – graphic, electronic, or
mechanical, including photocopying,
recording, taping, Web distribution,

or information storage and retrieval
systems – without the written
permission of the publisher.
For permission to use material from
this text or product, submit a request
online at www.thomsonrights.com
Every effort has been made to trace
ownership of all copyright material
and to secure permission from copy-
right holders. In the event of any
question arising as to the use of any
material, we will be pleased to make
the necessary corrections in future
printings.
MATLAB
®
and SIMULINK
®
are regis-
tered trademarks of The MathWorks,
3 Apple Hill Drive, Natick, MA 01760.
North America
Thomson Learning
1120 Birchmount Road
Toronto, Ontario MIK 5G4
Canada
Asia
Thomson Learning
5 Shenton Way #01-01
UIC Building

Singapore 068808
Australia/New Zealand
Thomson Learning
102 Dodds Street
Southbank, Victoria
Australia 3006
Europe/Middle East/Africa
Thomson Learning
High Holborn House
50/51 Bedford Row
London WCIR 4LR
United Kingdom
Latin America
Thomson Learning
Seneca, 53
Colonia Polanco
11560 Mexico D.F.
Mexico
Spain
Paraninfo
Calle/Magallanes, 25
28015 Madrid, Spain
MATLAB
®
Programming for Engineers, Fourth Edition
by Stephen J. Chapman
00USE_FM.qxd 10/5/07 1:43 PM Page iv
Copyright 2008 Cengage Learning, Inc. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Licensed to:
iChapters User

CHAPTER
1
Introduction
to MATLAB
MATLAB (short for MATrix LABoratory) is a special-purpose computer program
optimized to perform engineering and scientific calculations. It started life as a
program designed to perform matrix mathematics, but over the years it has
grown into a flexible computing system capable of solving essentially any techni-
cal problem.
The MATLAB program implements the MATLAB programming language and
provides a very extensive library of predefined functions to make technical pro-
gramming tasks easier and more efficient. This book introduces the MATLAB
language as it is implemented in MATLAB Version 7.4 (Release 2007a) and shows
how to use it to solve typical technical problems.
MATLAB is a huge program with an incredibly rich variety of functions. Even
the basic version of MATLAB without any toolkits is much richer than other tech-
nical programming languages. There are more than 1000 functions in the basic
MATLAB product alone, and the toolkits extend this capability with many more
functions in various specialties.This book makes no attempt to introduce the user
to all of MATLAB’s functions. Instead, it teaches a user the basics of how to write,
debug, and optimize good MATLAB programs and presents a subset of the most
important functions. Just as importantly, it teaches the programmer how to use
MATLAB’s own tools to locate the right function for a specific purpose from the
enormous number of choices available.
1
01Ch01.qxd 10/5/07 3:41 PM Page 1
Copyright 2008 Cengage Learning, Inc. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Licensed to:
iChapters User
1.1

The Advantages of MATLAB
MATLAB has many advantages compared with conventional computer languages
for technical problem solving. These include
1. Ease of Use
MATLAB is an interpreted language, like many versions of Basic. Like
Basic, it is very easy to use. The program can be used as a scratch pad to
evaluate expressions typed at the command line, or it can be used to exe-
cute large prewritten programs. Programs may be easily written and
modified with the built-in integrated development environment, and
debugged with the MATLAB debugger. Because the language is so easy
to use, it is ideal for the rapid prototyping of new programs.
Many program development tools are provided to make the program
easy to use. They include an integrated editor/debugger, on-line docu-
mentation and manuals, a workspace browser, and extensive demos.
2. Platform Independence
MATLAB is supported on many different computer systems, providing a
large measure of platform independence. At the time of this writing, the lan-
guage is supported on Windows 2000/XP/Vista, Linux, several versions of
Unix, and the Macintosh. Programs written on any platform will run on all
of the other platforms, and data files written on any platform may be read
transparently on any other platform. As a result, programs written in MAT-
LAB can migrate to new platforms when the needs of the user change.
3. Predefined Functions
MATLAB comes complete with an extensive library of predefined func-
tions that provide tested and prepackaged solutions to many basic techni-
cal tasks. For example, suppose that you are writing a program that must
calculate the statistics associated with an input data set. In most lan-
guages, you would need to write your own subroutines or functions to
implement calculations such as the arithmetic mean, standard deviation,
median, and so on. These and hundreds of other functions are built right

into the MATLAB language, making your job much easier.
In addition to the large library of functions built into the basic
MATLAB language, there are many special-purpose toolboxes available to
help solve complex problems in specific areas. For example, a user can buy
standard toolboxes to solve problems in signal processing, control systems,
communications, image processing, and neural networks, among many
others. There is also an extensive collection of free user-contributed MAT-
LAB programs that are shared through the MATLAB Web site.
4. Device-Independent Plotting
Unlike most other computer languages, MATLAB has many integral plot-
ting and imaging commands. The plots and images can be displayed on any
2 |
Chapter 1 Introduction to MATLAB
01Ch01.qxd 10/5/07 3:41 PM Page 2
Copyright 2008 Cengage Learning, Inc. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Licensed to:
iChapters User
1.3 The MATLAB Environment | 3
graphical output device supported by the computer on which MATLAB is
running. This capability makes MATLAB an outstanding tool for visual-
izing technical data.
5. Graphical User Interface
MATLAB includes tools that allow a programmer to interactively con-
struct a Graphical User Interface (GUI) for his or her program. With this
capability, the programmer can design sophisticated data-analysis pro-
grams that can be operated by relatively inexperienced users.
6. MATLAB Compiler
MATLAB’s flexibility and platform independence is achieved by compil-
ing MATLAB programs into a device-independent p-code and then inter-
preting the p-code instructions at runtime. This approach is similar to that

used by Microsoft’s Visual Basic language. Unfortunately, the resulting
programs can sometimes execute slowly because the MATLAB code is
interpreted rather than compiled. We will point out features that tend to
slow program execution when we encounter them.
A separate MATLAB compiler is available. This compiler can com-
pile a MATLAB program into a true executable that runs faster than the
interpreted code. It is a great way to convert a prototype MATLAB pro-
gram into an executable suitable for sale and distribution to users.
1.2 Disadvantages of MATLAB
MATLAB has two principal disadvantages. The first is that it is an interpreted
language and therefore may execute more slowly than compiled languages. This
problem can be mitigated by properly structuring the MATLAB program.
The second disadvantage is cost: a full copy of MATLAB is five to ten times
more expensive than a conventional C or Fortran compiler. This relatively high
cost is more than offset by the reduced time required for an engineer or scientist
to create a working program, so MATLAB is cost-effective for businesses.
However, it is too expensive for most individuals to consider purchasing.
Fortunately, there is also an inexpensive Student Edition of MATLAB, which is a
great tool for students wishing to learn the language. The Student Edition of
MATLAB is essentially identical to the full edition.
1.3 The MATLAB Environment
The fundamental unit of data in any MATLAB program is the array. An
array is a collection of data values organized into rows and columns and known
by a single name. Individual data values within an array may be accessed
by including the name of the array, followed by subscripts in parentheses
that identify the row and column of the particular value. Even scalars are
01Ch01.qxd 10/5/07 3:41 PM Page 3
Copyright 2008 Cengage Learning, Inc. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Licensed to:
iChapters User

4 | Chapter 1 Introduction to MATLAB
treated as arrays by MATLAB—they are simply arrays with only one row and
one column. We will learn how to create and manipulate MATLAB arrays in
Section 1.4.
When MATLAB executes, it can display several types of windows that
accept commands or display information. The three most important types of
windows are Command Windows, where commands may be entered; Figure Win-
dows, which display plots and graphs; and Edit Windows, which permit a user to
create and modify MATLAB programs. We will see examples of all three types
of windows in this section.
In addition, MATLAB can display other windows that provide help and that
allow the user to examine the values of variables defined in memory. We will
examine some of these additional windows here, examine the others when we
discuss how to debug MATLAB programs.
1.3.1 The MATLAB Desktop
When you start MATLAB Version 7.4, a special window called the MATLAB
desktop appears. The desktop is a window that contains other windows showing
MATLAB data, plus toolbars and a “Start” button similar to that used by
Windows XP. By default, most MATLAB tools are “docked” to the desktop so
that they appear inside the desktop window. However, the user can choose to
“undock” any or all tools, making them appear in windows separate from the
desktop.
The default configuration of the MATLAB desktop is shown in Figure 1.1.
It integrates many tools for managing files, variables, and applications within the
MATLAB environment.
The major tools within or accessible from the MATLAB desktop are
᭿
The Command Window
᭿
The Command History Window

᭿
The Start Button
᭿
The Documents Window, including the Editor/Debugger and the Array Editor
᭿
Figure Windows
᭿
Workspace Browser
᭿
Help Browser
᭿
Path Browser
We will discuss the functions of these tools in later sections of this chapter.
1.3.2 The Command Window
The right-hand side of the default MATLAB desktop contains the Command
Window. A user can enter interactive commands at the command prompt (») in
the Command Window, and they will be executed on the spot.
01Ch01.qxd 10/5/07 3:41 PM Page 4
Copyright 2008 Cengage Learning, Inc. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Licensed to:
iChapters User
As an example of a simple interactive calculation, suppose that you want to
calculate the area of a circle with a radius of 2.5 m. This can be done in the
MATLAB Command Window by typing
» area = pi * 2.5^2
area =
19.6350
MATLAB calculates the answer as soon as the Enter key is pressed and stores the
answer in a variable (really a array) called area. The contents of the vari-
able are displayed in the Command Window as shown in Figure 1.2, and the var-

iable can be used in further calculations. (Note that is predefined in MATLAB,
so we can just use pi without first declaring it to be 3.141592 . . . ).
If a statement is too long to type on a single line, it may be continued on
successive lines by typing an ellipsis ( . . . ) at the end of the first line and then
continuing on the next line. For example, the following two statements are
identical.
p
1 3 1
1.3 The MATLAB Environment | 5
Figure 1.1 The default MATLAB desktop. The exact appearance of the desktop may differ slightly
on different types of computers.
Current Directory
Browser shows a list of the
files in the current directory
This control allow a
user to view or change
the current directory
Launch
the Help
Browser
MATLAB
Command
Window
Start Button
launches toolboxes,
MATLAB tools, etc.
Command History
window displays
previous commands
Workspace Browser

shows variables
defined in workspace
01Ch01.qxd 10/5/07 3:41 PM Page 5
Copyright 2008 Cengage Learning, Inc. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Licensed to:
iChapters User
6 | Chapter 1 Introduction to MATLAB
x1 = 1 + 1/2 + 1/3 + 1/4 + 1/5 + 1/6
and
x1 = 1 + 1/2 + 1/3 + 1/4
+ 1/5 + 1/6
Instead of typing commands directly in the Command Window, a user can
place a series of commands into a file, and the entire file can be executed by
typing its name in the Command Window. Such files are called script files. Script
files (and functions, which we will see later) are also known as M-files, because
they have a file extension of “.m”.
1.3.3 The Command History Window
The Command History Window displays a list of the commands that a user has
entered in the Command Window. The list of previous commands can extend back
to previous executions of the program. Commands remain in the list until they are
deleted. To reexecute any command, simply double-click it with the left mouse
Figure 1.2 The Command Window appears on the right side of the desktop. Users enter commands
and see responses here.
User input
Result of
calculation
01Ch01.qxd 10/5/07 3:41 PM Page 6
Copyright 2008 Cengage Learning, Inc. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Licensed to:
iChapters User

button. To delete one or more commands from the Command History window,
select the commands and right-click them with the mouse. A popup menu will be
displayed that allows the user to delete the items (see Figure 1.3).
1.3.4 The Start Button
The Start Button (see Figure 1.4) allows a user to access MATLAB tools, desk-
top tools, help files, and so on. It works just like the Start button on a Windows
desktop. To start a particular tool, just click on the Start Button and select the tool
from the appropriate submenu.
1.3.5 The Edit/Debug Window
An Edit Window is used to create new M-files, or to modify existing ones. An
Edit Window is created automatically when you create a new M-file or open an
existing one. You can create a new M-file by selecting “File/New/M-file” from
the desktop menu or by clicking the toolbar icon. You can open an existing
M-file file by selecting “File/Open” from the desktop menu or by clicking the
toolbar icon.
1.3 The MATLAB Environment | 7
Figure 1.3 The Command History Window, showing two commands being deleted.
01Ch01.qxd 10/5/07 3:41 PM Page 7
Copyright 2008 Cengage Learning, Inc. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Licensed to:
iChapters User
An Edit Window displaying a simple M-file called calc_area.m is shown
in Figure 1.5. This file calculates the area of a circle, given its radius, and displays
the result. By default, the Edit Window is an independent window not docked to
the desktop, as shown in Figure 1.5(a). The Edit Window can also be docked to the
MATLAB desktop. In that case, it appears within a container called the
Documents Window, as shown in Figure 1.5(b). We will learn how to dock and
undock a window later in this chapter.
The Edit Window is essentially a programming text editor, with the
MATLAB languages features highlighted in different colors. Comments in an

M-file file appear in green, variables and numbers appear in black, complete
character strings appear in magenta, incomplete character strings appear in red,
and language keywords appear in blue.
After an M-file is saved, it may be executed by typing its name in the
Command Window. For the M-file in Figure 1.5, the results are
» calc_area
The area of the circle is 19.635
The Edit Window also doubles as a debugger, as we shall see in Chapter 2.
1.3.6 Figure Windows
A Figure Window is used to display MATLAB graphics. A figure can be a two-
or three-dimensional plot of data, an image, or a graphical user interface (GUI).
8 |
Chapter 1 Introduction to MATLAB
Figure 1.4 The Start Button, which allows a user to select from a wide variety of MATLAB
and desktop tools.
01Ch01.qxd 10/5/07 3:41 PM Page 8
Copyright 2008 Cengage Learning, Inc. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Licensed to:
iChapters User
Figure 1.5 (a) The MATLAB Editor, displayed as an independent window. (b) The MATLAB
Editor, docked to the MATLAB desktop.
(a)
(b)
01Ch01.qxd 10/5/07 3:41 PM Page 9
Copyright 2008 Cengage Learning, Inc. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Licensed to:
iChapters User
10 | Chapter 1 Introduction to MATLAB
A simple script file that calculates and plots the function sin x is shown as
follows:

% sin_x.m: This M-file calculates and plots the
% function sin(x) for 0 <= x <= 6.
x = 0:0.1:6
y = sin(x)
plot(x,y)
If this file is saved under the name sin_x.m, then a user can execute the file by
typing “sin_x” in the Command Window. When this script file is executed,
MATLAB opens a Figure Window and plots the function sin x in it. The resulting
plot is shown in Figure 1.6.
1.3.7 Docking and Undocking Windows
MATLAB windows such as the Command Window, the Edit Window, and Figure
Windows can either be docked to the desktop, or they can be undocked. When a
window is docked, it appears as a pane within the MATLAB desktop. When it is
undocked, it appears as an independent window on the computer screen separate
from the desktop. When a window is docked to the desktop, the upper right-hand
corner contains a small button with an arrow pointing up and to the right ( ).
If this button is clicked, the window will become an independent window. When
Figure 1.6 MATLAB plot of sin x versus x.
01Ch01.qxd 10/5/07 3:41 PM Page 10
Copyright 2008 Cengage Learning, Inc. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Licensed to:
iChapters User
the window is an independent window, the upper right-hand corner contains a
small button with an arrow pointing down and to the right ( ). If this button is
clicked, the window will be re-docked with the desktop. Figure 1.5 shows the Edit
Window in both its docked and undocked state. Note the undock and dock arrows
in the upper right-hand corner.
1.3.8 The MATLAB Workspace
A statement such as
z=10

creates a variable named z, stores the value 10 in it, and saves it in a part of com-
puter memory known as the workspace. A workspace is the collection of all the
variables and arrays that can be used by MATLAB when a particular command,
M-file, or function is executing. All commands executed in the Command
Window (as well as all script files executed from the Command Window) share a
common workspace, so they can all share variables. As we will see later, MAT-
LAB functions differ from script files in that each function has its own separate
workspace.
A list of the variables and arrays in the current workspace can be generated
with the whos command. For example, after M-files calc_area and sin_x
are executed, the whos command will display the following list of variables:
» whos
Name Size Bytes Class Attributes
area 1x1 8 double
radius 1x1 8 double
string 1x32 64 char
x 1x61 488 double
y 1x61 488 double
Script file calc_area created variables area, radius, and string, and
script file sin_x created variables x and y. Note that all of the variables are in
the same workspace, so if two script files are executed in succession, the second
script file can use variables created by the first script file.
The contents of any variable or array may be determined by typing the appro-
priate name in the Command Window. For example, the contents of string can
be found as follows:
» string
string =
The area of the circle is 19.635
A variable can be deleted from the workspace with the clear command.
The clear command takes the form

clear var1 var2
1.3 The MATLAB Environment | 11
01Ch01.qxd 10/5/07 3:41 PM Page 11
Copyright 2008 Cengage Learning, Inc. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Licensed to:
iChapters User
12 | Chapter 1 Introduction to MATLAB
where var1 and var2 are the names of the variables to be deleted. The
command clear variables or simply clear deletes all variables from the
current workspace.
1.3.9 The Workspace Browser
The contents of the current workspace can also be examined with a GUI-based
Workspace Browser. The Workspace Browser appears by default in the upper left-
hand corner of the desktop. It provides a graphic display of the same information
as the whos command, and it also shows the actual contents of each array if the
information is short enough to fit within the display area. The Workspace
Browser is dynamically updated whenever the contents of the workspace change.
A typical Workspace Browser window is shown in Figure 1.7. As you can
see, it displays the same information as the whos command. Double-clicking on
Figure 1.7 The Workspace Browser and the Array Editor. The Array Editor is invoked by double-
clicking a variable in the Workspace Browser. It allows a user to change the values
contained in a variable or array.
Workspace Browser shows a list the
variables defined in the workspace
Array Editor allows the user to
edit any variable or array selected
in the Workspace Browser.
01Ch01.qxd 10/5/07 3:41 PM Page 12
Copyright 2008 Cengage Learning, Inc. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Licensed to:

iChapters User
1.3 The MATLAB Environment | 13
Figure 1.8 The Help Browser.
any variable in the window will bring up the Array Editor, which allows the user
to modify the information stored in the variable.
One or more variables may be deleted from the workspace by selecting them
in the Workspace Browser with the mouse and pressing the delete key, or by right-
clicking with the mouse and selecting the delete option.
1.3.10 Getting Help
There are three ways to get help in MATLAB. The preferred method is to use the Help
Browser. The Help Browser can be started by selecting the icon from the desktop
toolbar or by typing helpdesk or helpwin in the Command Window. A user can
get help by browsing the MATLAB documentation, or he or she can search for the
details of a particular command. The Help Browser is shown in Figure 1.8.
01Ch01.qxd 10/5/07 3:41 PM Page 13
Copyright 2008 Cengage Learning, Inc. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Licensed to:
iChapters User
14 | Chapter 1 Introduction to MATLAB
There are also two command-line–oriented ways to get help. The first way is
to type help or help followed by a function name in the Command Window. If
you just type help, MATLAB will display a list of possible help topics in the
Command Window. If a specific function or a toolbox name is included, help will
be provided for that particular function or toolbox.
The second way to get help is the lookfor command. The lookfor
command differs from the help command in that the help command searches
for an exact function name match, while the lookfor command searches the
quick summary information in each function for a match. This makes look-
for slower than help, but it improves the chances of getting back useful
information. For example, suppose that you were looking for a function to take

the inverse of a matrix. Since MATLAB does not have a function named
inverse, the command “help inverse” will produce nothing. On the
other hand, the command “lookfor inverse” will produce the following
results:
» lookfor inverse
INVHILB Inverse Hilbert matrix.
ACOS Inverse cosine.
ACOSH Inverse hyperbolic cosine.
ACOT Inverse cotangent.
ACOTH Inverse hyperbolic cotangent.
ACSC Inverse cosecant.
ACSCH Inverse hyperbolic cosecant.
ASEC Inverse secant.
ASECH Inverse hyperbolic secant.
ASIN Inverse sine.
ASINH Inverse hyperbolic sine.
ATAN Inverse tangent.
ATAN2 Four quadrant inverse tangent.
ATANH Inverse hyperbolic tangent.
ERFINV Inverse error function.
INV Matrix inverse.
PINV Pseudoinverse.
IFFT Inverse discrete Fourier transform.
IFFT2 Two-dimensional inverse discrete Fourier transform.
IFFTN N-dimensional inverse discrete Fourier transform.
IPERMUTE Inverse permute array dimensions.
From this list, we can see that the function being sought is named inv.
1.3.11 A Few Important Commands
If you are new to MATLAB, a few demonstrations may help to give you a feel for
its capabilities. To run MATLAB’s built-in demonstrations, type demo in the

Command Window, or select “demos” from the Start Button.
01Ch01.qxd 10/5/07 3:41 PM Page 14
Copyright 2008 Cengage Learning, Inc. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Licensed to:
iChapters User
The contents of the Command Window can be cleared at any time using the
clc command, and the contents of the current Figure Window can be cleared at
any time using the clf command. The variables in the workspace can be cleared
with the clear command. As we have seen, the contents of the workspace persist
between the executions of separate commands and M-files, so it is possible for
the results of one problem to have an effect on the next one that you may attempt
to solve. To avoid this possibility, it is a good idea to issue the clear command
at the start of each new independent calculation.
Another important command is the abort command. If an M-file appears to
be running for too long, it may contain an infinite loop and it will never termi-
nate. In this case, the user can regain control by typing control-c (abbreviated ^c)
in the Command Window. This command is entered by holding down the control
key while typing a “c”. When MATLAB detects a ^c, it interrupts the running
program and returns a command prompt.
The exclamation point (!)is another important special character. Its special
purpose is to send a command to the computer’s operating system. Any characters
after the exclamation point will be sent to the operating system and executed as
though they had been typed at the operating system’s command prompt. This fea-
ture lets you embed operating system commands directly into MATLAB programs.
Finally, it is possible to keep track of everything done during a MATLAB
session with the diary command. The form of this command is
diary filename
After this command is typed, a copy of all input and most output typed in the
Command Window will be echoed in the diary file. This is a great tool for
recreating events when something goes wrong during a MATLAB session. The

command “diary off” suspends input into the diary file, and the command
“diary on” resumes input again.
1.3.12 The MATLAB Search Path
MATLAB has a search path that it uses to find M-files. MATLAB’s M-files are
organized in directories on your file system. Many of these directories of M-files
are provided along with MATLAB, and users may add others. If a user enters a
name at the MATLAB prompt, the MATLAB interpreter attempts to find the
name as follows:
1. It looks for the name as a variable. If it is a variable, MATLAB displays
the current contents of the variable.
2. It checks to see if the name is an M-file in the current directory. If it is,
MATLAB executes that function or command.
3. It checks to see if the name is an M-file in any directory in the search
path. If it is, MATLAB executes that function or command.
Note that MATLAB checks for variable names first, so if you define a vari-
able with the same name as a MATLAB function or command, that function or
command becomes inaccessible. This is a common mistake made by novice users.
1.3 The MATLAB Environment | 15
01Ch01.qxd 10/5/07 3:41 PM Page 15
Copyright 2008 Cengage Learning, Inc. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Licensed to:
iChapters User

Programming Pitfalls
Never use a variable with the same name as a MATLAB function or command.
If you do so, that function or command will become inaccessible.
Also, if there is more than one function or command with the same name, the
first one found on the search path will be executed and all of the others will be
inaccessible. This is a common problem for novice users, since they sometimes
create M-files with the same names as standard MATLAB functions, making

them inaccessible.

Programming Pitfalls
Never create an M-file with the same name as a MATLAB function or command.
MATLAB includes a special command (which) to help you find out just
which version of a file is being executed and where it is located. This can be
16 |
Chapter 1 Introduction to MATLAB
Figure 1.9 The Path Tool.
01Ch01.qxd 10/5/07 3:41 PM Page 16
Copyright 2008 Cengage Learning, Inc. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Licensed to:
iChapters User
useful in finding filename conflicts. The format of this command is which
functionname, where functionname is the name of the function that you
are trying to locate. For example, the cross-product function cross.m can be
located as follows:
» which cross
C:\Program Files\MATLAB\R2007a\toolbox\matlab\specfun\cross.m
The MATLAB search path can be examined and modified at any time by
selecting “Desktop Tools/Path” from the Start Button, or by typing editpath
in the Command Window. The Path Tool is shown in Figure 1.9. It allows a user
to add, delete, or change the order of directories in the path.
Other path-related functions include
᭿
addpath—Add directory to MATLAB search path.
᭿
path—Display MATLAB search path.
᭿
path2rc—Add current directory to MATLAB search path.

᭿
rmpath—Remove directory from MATLAB search path.
1.4 Using MATLAB as a Scratch Pad
In its simplest form, MATLAB can be used as a scratch pad to perform mathemati-
cal calculations. The calculations to be performed are typed directly into the
Command Window, using the symbols +, –, *, /, and ^ for addition, subtraction, mul-
tiplication, division, and exponentiation, respectively. After an expression is typed,
the results of the expression will be automatically calculated and displayed. For
example, suppose we would like to calculate the volume of a cylinder of radius r and
length l. The area of the circle at the base of the cylinder is given by the equation
(1-1)
and the total volume of the cylinder will be
(1-2)
If the radius of the cylinder is 0.1 m and the length is 0.5 m, the volume of the
cylinder can be found using the MATLAB statements (user inputs are shown in
boldface):
» A = pi * 0.1^2
A=
0.0314
» V = A * 0.5
V=
0.0157
Note that pi is predefined to be the value 3.141592 . . . . Also, note that the value
stored in A was saved by MATLAB and reused when we calculated V.
V 5 Al
A 5 pr
2
1.4 Using MATLAB as a Scratch Pad | 17
01Ch01.qxd 10/5/07 3:41 PM Page 17
Copyright 2008 Cengage Learning, Inc. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.

Licensed to:
iChapters User
Quiz 1.1
This quiz provides a quick check to see if you have understood the con-
cepts introduced in Chapter 1. If you have trouble with the quiz, reread
the sections, ask your instructor, or discuss the material with a fellow
student. The answers to this quiz are found in the back of the book.
1. What is the purpose of the MATLAB Command Window? The Edit
Window? The Figure Window?
2. List the different ways that you get help in MATLAB.
3. What is a workspace? How can you determine what is stored in a
MATLAB workspace?
4. How can you clear the contents of a workspace?
5. The distance traveled by a ball falling in the air is given by the equation
Use MATLAB to calculate the position of the ball at time s if
m, m/s, and m/sec
2
.
6. Suppose that and . Use MATLAB to evaluate the fol-
lowing expression:
The following questions are intended to help you become familiar
with MATLAB tools.
7. Execute the M-files calc_area.m and sin_x.m in the Command
Window (these M-files are available from the book’s Web site). Then
use the Workspace Browser to determine which variables are defined
in the current workspace.
8. Use the Array Editor to examine and modify the contents of vari-
able x in the workspace. Then type the command plot(x,y) in
the Command Window. What happens to the data displayed in the
Figure Window?

1.5 Summary
In this chapter, we have learned about the basic types of MATLAB windows, the
workspace, and how to get on-line help. The MATLAB desktop appears when the
program is started. It integrates many of the MATLAB tools in a single location.
These tools include the Command Window, the Command History Window, the
x
2
y
3
sx 2 yd
2
y 5 4x 5 3
a 529.81v
0
5 15x
0
5 10
t 5 5
x 5 x
0
1 v
0
t 1
1
2
at
2
18 | Chapter 1 Introduction to MATLAB
01Ch01.qxd 10/5/07 3:41 PM Page 18
Copyright 2008 Cengage Learning, Inc. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.

Licensed to:
iChapters User
Start Button, the Workspace Browser, the Array Editor, and the Current Directory
Viewer. The Command Window is the most important of the windows. It is the
one in which all commands are typed and results are displayed.
The Edit/Debug window is used to create or modify M-files. It displays the
contents of the M-file with the contents of the file color-coded according to
function: comments, keywords, strings, and so forth. This window can be docked
to the desktop, but by default it is independent.
The Figure Window is used to display graphics.
A MATLAB user can get help by either using the Help Browser or the
command-line help functions help and lookfor. The Help Browser allows full
access to the entire MATLAB documentation set. The command-line function
help displays help about a specific function in the Command Window.
Unfortunately, you must know the name of the function in order to get help about
it. The function lookfor searches for a given string in the first comment line of
every MATLAB function and displays any matches.
When a user types a command in the Command Window, MATLAB searches
for that command in the directories specified in the MATLAB path. It will exe-
cute the first M-file in the path that matches the command; any further M-files
with the same name will never be found. The Path Tool can be used to add, delete,
or modify directories in the MATLAB path.
1.5.1 MATLAB Summary
The following summary lists all of the MATLAB special symbols described in
this chapter, along with a brief description of each one.
1.6 Exercises
1.1 The following MATLAB statements plot the function for
the range .
x = 0:0.1:10;
y=2*exp(−0.2 * x);

plot(x,y);
0 # x # 10
ysxd 5 2e
20.2x
1.6 Exercises | 19
Special Symbols
+ Addition
- Subtraction
* Multiplication
/ Division
^ Exponentiation
01Ch01.qxd 10/5/07 3:41 PM Page 19
Copyright 2008 Cengage Learning, Inc. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Licensed to:
iChapters User
Use the MATLAB Edit Window to create a new empty M-file, type these
statements into the file, and save the file with the name test1.m. Then,
execute the program by typing the name test1 in the Command Window.
What result do you get?
1.2 Get help on the MATLAB function exp using: (a) The “help exp” com-
mand typed in the Command Window and (b) the Help Browser.
1.3 Use the lookfor command to determine how to take the base-10 loga-
rithm of a number in MATLAB.
1.4 Suppose that and . Evaluate the following expressions using
MATLAB:
(a)
(b)
(c)
(d)
1.5 Use the MATLAB Help Browser to find the command required to show

MATLAB’s current directory. What is the current directory when MATLAB
starts up?
1.6 Use the MATLAB Help Browser to find out how to create a new directory
from within MATLAB. Then, create a new directory called mynewdir
under the current directory. Add the new directory to the top of MATLAB’s
path.
1.7 Change the current directory to mynewdir. Then open an Edit Window
and add the following lines:
% Create an input array from –2*pi to 2*pi
t = -2*pi:pi/10:2*pi;
% Calculate |sin(t)|
x = abs(sin(t));
% Plot result
plot(t,x);
Save the file with the name test2.m and execute it by typing test2 in
the Command Window. What happens?
1.8 Close the Figure Window and change back to the original directory that
MATLAB started up in. Next type “test2” in the Command Window.
What happens, and why?
4
3
p v
2
v
3
v
3
2 u
3
2v

22
su 1 vd
2
4u
3v
v 5 3u 5 1
20 |
Chapter 1 Introduction to MATLAB
01Ch01.qxd 10/5/07 3:41 PM Page 20
Copyright 2008 Cengage Learning, Inc. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Licensed to:
iChapters User
APPENDIXB
Answers
to
Quizzes
This appendix contains the answers to all of the quizzes in the book.
Quiz 1.1, page 18
1. The MATLAB Command Window is the window where a user enters
commands. A user can enter interactive commands at the command
prompt (») in the Command Window, and they will be executed on
the spot. The Command Window is also used to start M-files execut-
ing. The Edit/Debug Window is an editor used to create, modify, and
debug M-files. The Figure Window is used to display MATLAB
graphical output.
2. You can get help in MATLAB by:
᭿
Typing help <command_name> in the Command Window. This
command will display information about a command or function
in the Command Window.

᭿
Typing lookfor <keyword> in the Command Window. This
command will display in the Command Window a list of all com-
mands or functions containing the keyword in their first comment
line.
᭿
Starting the Help Browser by typing helpwin or helpdesk in
the Command Window, by selecting “Help” from the Start menu,
or by clicking on the question mark icon ( ) on the desktop. The
Help Browser contains an extensive hypertext-based description
of all of the features in MATLAB, plus a complete copy of all
537
13App B.qxd 10/5/07 3:48 PM Page 537
Copyright 2008 Cengage Learning, Inc. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Licensed to:
iChapters User
manuals on-line in HTML and Adobe PDF formats. It is the most
comprehensive source of help in MATLAB.
3. A workspace is the collection of all the variables and arrays that can
be used by MATLAB when a particular command, M-file, or func-
tion is executing. All commands executed in the Command Window
(and all script files executed from the Command Window) share a
common workspace, so they can all share variables. The contents of
the workspace can be examined with the whos command, or graphi-
cally with the Workspace Browser.
4. To clear the contents of a workspace, type clear or clear vari-
ables in the Command Window.
5. The commands to perform this calculation are
» t = 5;
» x0 = 10;

» v0 = 15;
» a = -9.81;
» x = x0 + v0 * t + 1/2 * a * t^2
x =
-37.6250
6. The commands to perform this calculation are
» x = 3;
» y = 4;
» res = x^2 * y^3 / (x - y)^2
res =
576
Questions 7 and 8 are intended to get you to explore the features of
MATLAB. There is no single “right” answer for them.
538 |
Appendix B Answers to Quizzes
13App B.qxd 10/5/07 3:48 PM Page 538
Copyright 2008 Cengage Learning, Inc. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
This page contains answers for this chapter only.

Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Tải bản đầy đủ ngay
×