Graphics Programs Reference
In-Depth Information
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
Chapter2)andusinganM-file(seeChapter3).Inlinefunctionsaremostuseful
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
fordefiningfunctionsthatrequireseveralintermediatecommandstocompute
theoutput.MostMATLABcommandsareactuallyM-files,andyoucanperuse
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)
)ora
function 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,typingasymbolicexpressioninsteadgivesanerrormessage.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
Search WWH ::
Custom Search