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

MATLAB Basics

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 (383.66 KB, 23 trang )

Chapter 2
MATLAB Basics
In this chapter, you will start learning how to use MATLAB to do mathematics.
You should read this chapter at your computer, with MATLAB running. Try
the commands in a MATLAB Command Window as you go along. Feel free to
experiment with variants of the examples we present; the best 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.The
Glossary contains a synopsis of many MATLABoperators, constants,
functions, commands, and programming instructions.
Input and Output
You input commands to MATLAB in the MATLAB Command Window. MAT-
LAB returns output in two ways: Typically, text or numerical output is re-
turned in the same Command Window, but graphical output appears in a
separate graphics window. A sample screen, with both a MATLAB Desktop
and a graphics window, labeled Figure No. 1, is shown in Figure 2–1.
To generate this screen on your computer, first type 1/2 + 1/3. Then type
ezplot(’xˆ3 - x’).

While MATLAB is working, it may display a “wait” symbol — for example,
an hourglass appears on many operating systems. Or it may give no visual
evidence until it is finished with its calculation.
Arithmetic
As we have just seen, you can use MATLAB to do arithmetic as you would a
calculator. You can use “+” to add, “-” to subtract, “*” to multiply, “/” to divide,
8
Arithmetic
9
Figure 2-1: MATLAB Output.
and “ˆ” to exponentiate. 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 square and 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 witheachcalculation.
To do more complex calculations, you can assign computed values to variables
of your choosing. For example,
>> u = cos(10)
u=
-0.8391
10
Chapter 2: MATLAB Basics
>> v = sin(10)
v=
-0.5440
>> uˆ2 + vˆ2
ans =
1
MATLAB uses double-precision floating point arithmetic, which is accurate
to approximately 15 digits; however, MATLAB displays only 5 digits by default.
To 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 on the next page.
Algebra
Using MATLAB’s Symbolic MathToolbox, you can carry out algebraic
or symbolic calculations suchas factoring polynomials or solving algebraic
equations. Type help symbolic to make sure that the Symbolic Math Tool-
box is installed on your system.
To perform symbolic computations, you must use syms to declare the vari-
ables you plan to use to be symbolic variables. Consider the following series
of commands:
>> syms x y
>> (x - y)*(x - y)ˆ2
ans =
(x-y)^3
>> expand(ans)
Algebra
11
ans =
x^3-3*x^2*y+3*x*y^2-y^3
>> factor(ans)
ans =
(x-y)^3

Notice that symbolic output is left-justified, while numeric output is
indented. This feature is often useful in distinguishing symbolic output
from numerical output.
Although MATLAB makes minor simplifications to the expressions you
type, it does not make major changes unless you tell it to. The command ex-
pand told MATLAB to multiply out the expression, and factor forced MAT-

LAB 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 bothcommands 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 answer.
Symbolic Expressions, Variable Precision, and Exact Arithmetic
As we have noted, MATLAB uses floating point arithmetic for its calculations.
Using the Symbolic Math Toolbox, you can also do exact arithmetic with sym-
bolic expressions. 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
12
Chapter 2: MATLAB Basics
to about 15 digits, not its exact value. To compute an exact answer, instead
of an approximate answer, we must 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
characters 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 equiv-
alent to x = sym(’x’). The command syms has a lasting effect on its argu-
ment (it declares it to be symbolic from now on), while sym has only a tempo-
rary effect unless you assign the output to a variable, as in x = sym(’x’).
Here is how to add 1/2 and 1/3 symbolically:
>> sym(’1/2’) + sym(’1/3’)
ans =
5/6
Finally, you can also do variable-precision arithmetic with vpa. For example,
to print 50 digits of

2, type
>> vpa(’sqrt(2)’, 50)
ans =
1.4142135623730950488016887242096980785696718753769

You should be wary of using sym or vpa on an expression that
MATLAB must evaluate before applying variable-precision
arithmetic. To illustrate, enter 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 only carries 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 MATLABconverts between symbolic and floating point numbers.
Managing Variables
13
Managing Variables
We have now encountered three different classes of MATLAB data: floating
point numbers, strings, and symbolic expressions. In a long MATLAB session
it may be hard to remember the names and classes of all the variables you
have defined. You can type whos to see a summary of the names and types of
your currently defined variables. Here’s the output of whos for the MATLAB
session displayed in this chapter:
>> whos
Name Size Bytes Class
ans 1 x 1 226 sym object
u 1 x 1 8 double array
v 1 x 1 8 double array
x 1 x 1 126 sym object
y 1 x 1 126 sym object
Grand total is 58 elements using 494 bytes
We see that there are currently five assigned variables in our MATLAB
session. Three are of class “sym object”; that is, they are symbolic objects. The
variables x and y are symbolic because we declared them to be so using syms,
and ans is symbolic because it is the output of the last command we executed,
which involved a symbolic expression. The other two variables, u and v, are
of class “double array”. That means that they are arrays of double-precision
numbers; in this case the arrays are of size 1 × 1 (that is, scalars). The “Bytes”
column shows how much computer memory is allocated to each variable.
Try assigning u = pi, v = ’pi’, and w = sym(’pi’), and then type
whos to see how the different data types are described.

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 the name of the variable and press
ENTER
or
RETURN
.
MATLAB commands expect particular classes of data as input, and it is
important to know what class of data is expected by a given command; the help
text for a command usually indicates the class or classes of input it expects. The
wrong class 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 a function 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.
Otherwise values from a previous calculation can creep into the new
14
Chapter 2: MATLAB Basics
Figure 2-2: Desktop with the Workspace Browser.
calculation by accident. Finally, we observe that the Workspace browser pre-
sents a graphical alternative to whos. You can activate it by clicking on the
Workspace tab, by typing workspace at the command prompt, or through
the View item on the menu bar. Figure 2-2 depicts a Desktop in which the
Command Window and the Workspace browser contain the same information
as displayed above.
Errors in Input
If you make an error in an input line, MATLAB will beep and print an error
message. For example, here’s what happens when you try to evaluate 3uˆ2:
>> 3uˆ2

??? 3u^2
|
Error: Missing operator, comma, or semicolon.
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
place where it thinks the error might be; however, the actual error may have
occurred earlier or later in the expression.
Online Help
15

Missing multiplication operators and parentheses are among the
most common errors.
You can edit an input line by using the
UP-ARROW
key to redisplay the pre-
vious command, editing the command using the
LEFT-
and
RIGHT-ARROW
keys,
and then pressing
RETURN
or
ENTER
.The
UP-
and
DOWN-ARROW
keys allow you
to scroll back and forththroughall the commands you’ve typed in a MATLAB

session, and are very useful when you want to correct, modify, or reenter a
previous command.
Online Help
There are several ways to get online help in MATLAB. To get help on a particu-
lar command, enter help followed by the name of the command. For example,
help solve will display documentation for solve. Unless you have a large
monitor, the output of help solve will not fit in your MATLAB command
window, and the beginning of the documentation will scroll quickly past the
top of the screen. You can force MATLAB to display information one screen-
ful at a time by typing more on. You press the space bar to display the next
screenful, or
ENTER
to display the next line; type help more for details. Typing
more on affects all subsequent commands, until you type more off.
The command lookfor searches the first line of every MATLAB help file
for a specified string (use lookfor -all to searchall 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.
The most robust online help in MATLAB 6 is provided through the vastly
improved Help Browser. The Help Browser can be invoked in several ways: by
typing helpdesk at the command prompt, under the View item in the menu
bar, or through the question mark button on the tool bar. Upon its launch you
will see a window with two panes: the first, called the Help Navigator, used
to find documentation; and the second, called the display pane, for viewing
documentation. The display pane works much like a normal web browser. It
has an address window, buttons for moving forward and backward (among the
windows you have visited), live links for moving around in the documentation,
the capability of storing favorite sites, and other such tools.

You use the Help Navigator to locate the documentation that you will ex-
plore in the display pane. The Help Navigator has four tabs that allow you to
16
Chapter 2: MATLAB Basics
arrange your search for documentation in different ways. The first is the Con-
tents tab that displays a tree view of all the documentation topics available.
The extent of that tree will be determined by how much you (or your system
administrator) included in the original MATLAB installation (how many tool-
boxes, etc.). The second tab is an Index that displays all the documentation
available 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 pro-
vides the Search mechanism. You type in what you seek, either a function
or some other descriptive term, and the search engine locates corresponding
documentation that pertains to your entry. Finally, the fourth tab is a roster
of your Favorites. 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; if the display pane is not displaying the “Begin
Here” page, then click on it in the Contents tab; scroll down to the “Using
the Help Browser” link and click on it. The Help Browser is a powerful and
easy-to-use aid in finding the information you need on various components of
MATLAB. Like any such tool, the more you use it, the more adept you become
at its use.

If you type helpwin to launch the Help Browser, the display pane will
contain the same roster that you see as the result of typing help at the
command prompt, but the entries will be links.
Variables and Assignments
In MATLAB, you use the equal sign to assign values to a variable. For instance,
>>x=7

x=
7
will give the variable x the value 7 from now on. Henceforth, whenever MAT-
LAB sees the letter x, it will substitute the value 7. For example, if y has been
defined as a symbolic variable, then
>> xˆ2 - 2*x*y + y
ans =
49-13*y

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

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