Page 44 - A Guide to MATLAB for Beginners and Experienced Users
P. 44
Functions 25
To 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 show how to use inline to define your own functions.
2
Here’s how to define the polynomial function f (x) = x + x + 1:
>> f = inline(’xˆ2+x+1’, ’x’)
f=
Inline function:
f(x)=x^2+x+1
The first argument to inline is a string containing the expression defining
the function. The second argument is a string specifying the independent
variable.
The second argument to inline can be omitted, in which case MATLABwill
“guess” what it should be, using the rules about “Default Variables” to be
discussed later at the end of Chapter 4.
Once the function is defined, you can evaluate it:
>> f(4)
ans =
21
MATLAB functions can operate on vectors as well as scalars. To make an
inline function that can act on vectors, we use MATLAB’s vectorize function.
2
Here is the vectorized version of f (x) = x + x + 1:
>> f1 = inline(vectorize(’xˆ2+x+ 1’), ’x’)
f1 =
Inline function:
f1(x) = x.^2+x+1