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

Beyond the 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 (217.54 KB, 17 trang )

Chapter 4
Beyond the Basics
In this chapter, we describe some of the finer points of MATLAB and review in
more detail some of the concepts introduced in Chapter 2. We explore enough of
MATLAB’s internal structure to improve your ability to work withcomplicated
functions, expressions, and commands. At the end of this chapter, we introduce
some of the MATLAB commands for doing calculus.
Suppressing Output
Some MATLAB commands produce output that is superfluous. For example,
when you assign a value to a variable, MATLAB echoes the value. You can
suppress the output of a command by putting a semicolon after the command.
Here is an example:
>> syms x
>>y=x+7
y=
x+7
>>z=x+7;
>> z
z=
x+7
The semicolon does not affect the way MATLAB processes the command
internally, as you can see from its response to the command z.
50
Data Classes
51
You can also use semicolons to separate a string of commands when you are
interested only in the output of the final command (several examples appear
later in the chapter). Commas can also be used to separate commands without
suppressing output. If you use a semicolon after a graphics command, it will
not suppress the graphic.


The most common use of the semicolon is to suppress the printing of
a long vector, as indicated in Chapter 2.
Another object that you may want to suppress is MATLAB’s label for the
output of a command. The command disp is designed to achieve that; typing
disp(x) will print the value of the variable x without printing the label and
the equal sign. So,
>>x=7;
>> disp(x)
7
or
>> disp(solve(’x + tan(y) = 5’, ’y’))
-atan(x-5)
Data Classes
Every variable you define in MATLAB, as well as every input to, and output
from, a command, is an array of data belonging to a particular class.Inthis
book we use primarily four types of data: floating point numbers, symbolic
expressions, character strings, and inline functions. We introduced each of
these types in Chapter 2. In Table 4–1, we list for each type of data its class
(as given by whos ) and how you can create it.
Type of data Class Created by
Floating point double typing a number
Symbolic sym using sym or syms
Character string char typing a string inside single quotes
Inline function inline using inline
Table 4-1
You can think of an array as a two-dimensional grid of data. A single number
(or symbolic expression, or inline function) is regarded by MATLAB as a 1 × 1
52
Chapter 4: Beyond the Basics
array, sometimes called a scalar.A1× n array is called a row vector, and

an m × 1 array is called a column vector. (A string is actually a row vector of
characters.) An m × narray of numbers is called a matrix; see More on Matrices
below. You can see the class and array size of every variable you have defined
by looking in the Workspace browser or typing whos (see Managing Variables
in Chapter 2). The set of variable definitions shown by whos is called your
Workspace.
To use MATLAB commands effectively, you must pay close attention to the
class of data eachcommand accepts as input and returns as output. The input
to a command consists of one or more arguments separated by commas; some
arguments are optional. Some commands, suchas whos, do not require any
input. When you type a pair of words, such as hold on, MATLAB interprets
the second word as a string argument to the command given by the first word;
thus, hold on is equivalent to hold(’on’). The help text (see Online Help in
Chapter 2) for each command usually tells what classes of inputs the command
expects as well as what class of output it returns.
Many commands allow more than one class of input, though sometimes
only one data class is mentioned in the online help. This flexibility can be a
convenience in some cases and a pitfall in others. For example, the integration
command, int, accepts strings as well as symbolic input, though its help
text mentions only symbolic input. However, suppose that you have already
defined a=10, b=5, and now you attempt to factor the expression a
2
− b
2
,
forgetting your previous definitions and that you have to declare the variables
symbolic:
>> factor(aˆ2 - bˆ2)
ans =
355

The reason you don’t get an error message is that factor is the name of
a command that factors integers into prime numbers as well as factoring
expressions. Since a
2
− b
2
= 75 = 3 · 5
2
, the numerical version of factor is
applied. This output is clearly not what you intended, but in the course of a
complicated series of commands, you must be careful not to be fooled by such
unintended output.

Note that typing help factor only shows you the help text for the
numerical version of the command, but it does give a cross-reference to the
symbolic version at the bottom. If you want to see the help text for the
symbolic version instead, type help sym/factor. Functions suchas
factor withmore than one version are called overloaded.
Data Classes
53
Sometimes you need to convert one data class into another to prepare the
output of one command to serve as the input for another. For example, to use
plot on a symbolic expression obtained from solve, it is convenient to use
first vectorize and then inline, because inline does not allow symbolic
input and vectorize converts symbolic expressions to strings. You can make
the same conversion without vectorizing the expression using char. Other
useful conversion commands we have encountered are double (symbolic to
numerical), sym (numerical or string to symbolic), and inline itself (string to
inline function). Also, the commands num2str and str2num convert between
numbers and strings.

String Manipulation
Often it is useful to concatenate two or more strings together. The simplest way
to do this is to use MATLAB’s vector notation, keeping in mind that a string is
a “row vector” of characters. For example, typing [string1, string2] com-
bines string1 and string2 into one string.
Here is a useful application of string concatenation. You may need to define
a string variable containing an expression that takes more than one line to
type. (In most circumstances you can continue your MATLAB input onto the
next line by typing ... followed by
ENTER
or
RETURN
, but this is not allowed
in the middle of a string.) The solution is to break the expression into smaller
parts and concatenate them, as in:
>> eqn = [’left hand side of equation = ’, ...
’right hand side of equation’]
eqn =
left hand side of equation = right hand side of equation
Symbolicand Floating Point Numbers
We mentioned above that you can convert between symbolic numbers and
floating point numbers with double and sym. Numbers that you type are,
by default, floating point. However, if you mix symbolic and floating point
numbers in an arithmetic expression, the floating point numbers are auto-
matically converted to symbolic. This explains why you can type syms x and
then xˆ2 without having to convert 2 to a symbolic number. Here is another
example:
>>a=1
54
Chapter 4: Beyond the Basics

a=
1
>> b = a/sym(2)
b=
1/2
MATLAB was designed so that some floating point numbers are restored
to their exact values when converted to symbolic. Integers, rational numbers
withsmall numerators and denominators, square roots of small integers, the
number π, and certain combinations of these numbers are so restored. For
example,
>> c = sqrt(3)
c=
1.7321
>> sym(c)
ans =
sqrt(3)
Since it is difficult to predict when MATLAB will preserve exact values, it is
best to suppress the floating point evaluation of a numeric argument to sym by
enclosing it in single quotes to make it a string, e.g., sym(’1 + sqrt(3)’).
We will see below another way in which single quotes suppress evaluation.
Functions and Expressions
We have used the terms expression and function without carefully making a
distinction between the two. Strictly speaking, if we define f (x) = x
3
− 1, then
f (written without any particular input) is a function while f (x) and x
3
− 1
are expressions involving the variable x. In mathematical discourse we often
blur this distinction by calling f (x)orx

3
− 1 a function, but in MATLAB the
difference between functions and expressions is important.
In MATLAB, an expression can belong to either the string or symbolic class
of data. Consider the following example:
>> f = ’xˆ3 - 1’;
>> f(7)
ans =
1
Functions and Expressions
55
This result may be puzzling if you are expecting f to act like a function. Since
f is a string, f(7) denotes the seventh character in f, which is 1 (the spaces
count). Notice that like symbolic output, string output is not indented from
the left margin. This is a clue that the answer above is a string (consisting
of one character) and not a floating point number. Typing f(5) would yield a
minus sign and f(-1) would produce an error message.
You have learned two ways to define your own functions, using inline (see
Chapter 2) and using an M-file (see Chapter 3). Inline functions are most useful
for defining simple functions that can be expressed in one line and for turning
the output of a symbolic command into a function. Function M-files are useful
for defining functions that require several intermediate commands to compute
the output. Most MATLAB commands are actually M-files, and you can peruse
them for ideas to use in your own M-files — to see the M-file for, say, the
command mean you can enter type mean. See also More about M-files below.
Some commands, suchas ode45 (a numerical ordinary differential equa-
tions solver), require their first argument to be a function — to be precise,
either an inline function (as in ode45(f, [0 2], 1))orafunction handle,
that is, the name of a built-in function or a function M-file preceded by the
special symbol @ (as in ode45(@func, [0 2], 1)). The @ syntax is new in

MATLAB 6; in earlier versions of MATLAB, the substitute was to enclose the
name of the function in single quotes to make it a string. But with or without
quotes, typing a symbolic expression instead gives an error message. However,
most symbolic commands require their first argument to be either a string or
a symbolic expression, and not a function.
An important difference between strings and symbolic expressions is that
MATLAB automatically substitutes user-defined functions and variables into
symbolic expressions, but not into strings. (This is another sense in which the
single quotes you type around a string suppress evaluation.) For example, if
you type
>> h = inline(’t.ˆ3’, ’t’);
>> int(’h(t)’, ’t’)
ans =
int(h(t),t)
then the integral cannot be evaluated because within a string h is regarded
as an unknown function. But if you type
>> syms t
>> int(h(t), t)
ans =
1/4*t^4

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

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