Title: Functions and Files
1Chapter 3 Functions and Files
23-2
Getting Help for Functions You can use the
lookfor command to find functions that are
relevant to your application. For example, type
lookfor imaginary to get a list of the functions
that deal with imaginary numbers. You will see
listed imag Complex imaginary part i
Imaginary unit j Imaginary unit There is also
conj(x), real(x), angle(x), abs(x)
More? See page 142.
33-3
Some common mathematical functions Table 3.11
Exponential e x Square root ?x (
automatically produces imaginary sqrt(-4) 2I
) Natural logarithm ln x Common (base 10)
logarithm log x log10 x (continued)
Exponential exp(x) sqrt(x) Logarithmic log(x) l
og10(x)
In class T3.1-1 p145
4Some common mathematical functions (continued)
- Numeric
- ceil(x)
- fix(x)
- floor(x)
- round(x)
- sign(x)
- Round to nearest integer toward 8.
- Round to nearest integer toward zero.
- Round to nearest integer toward -8.
- Round toward nearest integer.
- Signum function
- 1 if x gt 0 0 if x 0 -1 if x lt 0.
gtgt ceil(1.1) ans 2 gtgt fix(1.1) ans
1 gtgt floor(1.1) ans 1 gtgt floor(-1.1) ans
-2 gtgt fix(-1.1) ans -1 gtgt round(1.1) ans
1 gtgt round(-1.1) ans -1
All of these functions work on vectors element by
element, like any other Matlab function
3-5
More? See pages 142-148.
53-6
The rectangular and polar representations of the
complex number a ib. Figure 3.11
6Complex Functions
- x a ib
- abs(x) sqrt(a2b2) - Absolute value.
- angle(x) atan2(b,a) - Angle of a complex
number. - (note the imaginary part comes
1st) - conj(x) a ib - Complex conjugate.
- real(x) a - Real part of a complex number.
- imag(x) b - Imaginary part of a complex
number. - If x is a complex vector, abs(x) will give you
vector of absolute values, not length of a vector - Need norm(x) sqrt(xx)
-
3-4
73-7
Operations with Complex Numbers gtgtx -3
4i gtgty 6 - 8i gtgtmag_x abs(x) mag_x
5.0000 gtgtmag_y abs(y) mag_y 10.0000 gtgtmag_pro
duct abs(xy) 50.0000
(continued )
83-8
Operations with Complex Numbers
(continued) gtgtangle_x angle(x) angle_x
2.2143 radians gtgtangle_y angle(y) angle_y
-0.9273 gtgtsum_angles angle_x
angle_y sum_angles 1.2870 gtgtangle_product
angle(xy) angle_product 1.2870 - same as
sum of angles In class T3.1-2 p145, T3.1-3 p147
More? See pages 143-145.
93-9
Operations on Arrays MATLAB will treat a
variable as an array automatically. For example,
to compute the square roots of 5, 7, and 15,
type gtgt x 4 49 25 x 4 49 25 gtgt
y sqrt(x) y 2 7 5
103-10
Expressing Function Arguments We can write sin 2
in text, but MATLAB requires parentheses
surrounding the 2 (which is called the function
argument or parameter). Thus to evaluate sin 2
in MATLAB, we type sin(2). The MATLAB function
name must be followed by a pair of parentheses
that surround the argument. To express in text
the sine of the second element of the array x, we
would type sinx(2). However, in MATLAB you
cannot use square brackets or braces in this way,
and you must type sin(x(2)).
(continued )
113-11
Expressing Function Arguments (continued) To
evaluate cos(x 3 -1), you type cos(x.3 - 1). To
evaluate tan(?x-2), you type tan(sqrt(x)-2).
Using a function as an argument of another
function is called function composition. Be sure
to check the order of precedence and the number
and placement of parentheses when typing such
expressions. Every left-facing parenthesis
requires a right-facing mate. However, this
condition does not guarantee that the expression
is correct!
123-12
Expressing Function Arguments (continued) Another
common mistake involves expressions like cos3 x,
which means (cos x)3. In MATLAB we write this
expression as (cos(x)).3, NOT as cos3(x),
cos3x, cos(x3), or cos(x)3!
133-13
Expressing Function Arguments (continued) The
MATLAB trigonometric functions operate in radian
mode. Thus sin(5) computes the sine of 5 rad,
not the sine of 5. To convert between degrees
and radians, use the relation qradians (pi
/180)qdegrees. Similarly, inverse trig functions
return an answer in radians asin(0.5) gives
0.5236 radians
More? See pages 145-146.
143-14
Trigonometric functions Table 3.12
Cosine cos x. Cotangent cot x. Cosecant csc
x. Secant sec x. Sine sin x. Tangent tan
x.
cos(x) cot(x) csc(x) sec(x) sin(x) tan(x)
15Inverse Trigonometric functions Table 3.12
- Inverse cosine arccos x.
- Inverse cotangent arccot x.
- Inverse cosecant arccsc x.
- Inverse secant arcsec x.
- Inverse sine arcsin x .
- Inverse tangent arctan x .
- Four-quadrant inverse tangent.
- acos(x)
- acot(x)
- acsc(x)
- asec(x)
- asin(x)
- atan(x)
- atan2(y,x)
3-15
16Difference between atan and atan2
Matlab has two inverse tangent function (see
above). atan(x) returns angle between pi/2 and
pi/2. However, another correct answer is the
angle that lies on opposite quadrant. atan(1)
gives 0.7854 rad ? 45 degrees But tan(45deg
180deg ) tan(225deg) 1 as well Matlab uses
atan2(y,x) to determine the arctangent
unambiguously. It gives the ange between positive
real axis x and line from origin to (x,y)
gtgt atan(1/1) ans 0.7854 gtgt atan(-1/-1) ans
0.7854 gtgt atan(1/-1) ans -0.7854 gtgt
atan(-1/1) ans -0.7854
gtgt atan2(1,1) ans 0.7854 gtgt
atan2(-1,-1) ans -2.3562 gtgt atan2(-1,1) ans
-0.7854 gtgt atan2(1,-1) ans 2.3562
The order of arguments is important for
atan2 NOTE that y comes 1st !!!
173-16
Hyperbolic functions Table 3.13
Hyperbolic cosine Hyperbolic cotangent. Hyperbol
ic cosecant Hyperbolic secant Hyperbolic
sine Hyperbolic tangent
cosh(x) coth(x) csch(x) sech(x) sinh(x) tanh(
x)
18Inverse Hyperbolic functions Table 3.13
- Inverse hyperbolic cosine
- Inverse hyperbolic cotangent
- Inverse hyperbolic cosecant
- Inverse hyperbolic secant
- Inverse hyperbolic sine
- Inverse hyperbolic tangent
- acosh(x)
- acoth(x)
- acsch(x)
- asech(x)
- asinh(x)
- atanh(x)
3-17
193-18
User-Defined Functions -- must be in a function
file. Unlike script file, all the variables in
function file are local (available only within a
function). Functions operate on local
variables in their own workspace, separate from
Matlab command space. Functions encapsulate
repeated operations. The first line in a
function file must begin with a function
definition line that has a list of inputs and
outputs. This line distinguishes a function
M-file from a script M-file. function output
variables name(input variables) Note that the
output variables are enclosed in square brackets
(only need it for more than one output variable),
while the input variables must be enclosed with
parentheses. The function name (here, name)
should be the same as the file name in which it
is saved (with the .m extension).
More? See pages 148-149.
203-19
User-Defined Functions Example function z
fun(x,y) just one output variable, so do not
need u 3x z u 6y.2 Note
u,z local variables Note the use of a
semicolon at the end of the lines. This
prevents the values of u and z from being
displayed. Note also the use of the array
exponentiation operator (.). This enables the
function to accept y as an array.
(continued )
213-20
User-Defined Functions Example (continued) Call
this function with its output argument gtgtz
fun(3,7) z 303 The function uses x 3 and
y 7 to compute z.
(continued )
223-21
User-Defined Functions Example (continued) Call
this function without its output argument and try
to access its value. You will see an error
message. gtgtfun(3,7) ans 303 gtgtz ???
Undefined function or variable z.
(continued )
233-22
User-Defined Functions Example
(continued) Assign the output argument to
another variable gtgtq fun(3,7) q 303 You
can suppress the output by putting a semicolon
after the function call. For example, if you
type q fun(3,7) the value of q will be
computed but not displayed (because of the
semicolon).
243-23
The variables x and y are local to the function
fun, so unless you pass their values by naming
them x and y, their values will not be available
in the workspace outside the function. The
variable u is also local to the function. For
example, gtgtx 3y 7 gtgtq fun(x,y) gtgtx x
3 gtgty y 7 gtgtu ??? Undefined function or
variable u.
253-24
Only the order of the arguments is important, not
the names of the arguments gtgtx 7y 3 gtgtz
fun(y,x) z 303 The second line is
equivalent to z fun(3,7).
263-25
You can use arrays as input arguments gtgtr
fun(24,79) r 300 393 498 the
result is also an array
273-26
A function may have more than one output. These
are enclosed in square brackets. For example,
the function circle computes the area A and
circumference C of a circle, given its radius as
an input argument. function A, C circle(r) A
pir.2 area C 2pir
circumference
28The function is called as follows, if the radius
is 4. gtgtA, C circle(4) A 50.2655 C
25.1327
3-27
29A function may have no input arguments and no
output list. For example, the function show_date
computes and stores the date in the variable
today, and displays the value of today. function
show_date today date date is Matlab
internal command giving you the date as a string
3-28
303-29
Examples of Function Definition Lines
- One input, one output
- function area_square square(side)
- 2. Brackets are optional for one input, one
output - function area_square square(side)
- 3. Two inputs, one output
- function volume_box box(height,width,length)
- 4. One input, two outputs
- function area_circle,circumf circle(radius)
- 5. No named output function sqplot(side)
- Note that comments can be placed anywhere in the
function file, but the lines immediately
following function definition are displayed by
the help and lookfor commands
31Function Example function dist,vel
drop(g,v0,t) Computes the distance traveled
and the velocity of a dropped object, as
functions of g, the initial velocity v0, and
the time t. vel gt v0 dist 0.5gt.2
v0t
Used array operation because we expect time t to
be a vector
(continued )
3-30
32Function Example (continued) 1. The variable
names used in the function definition may, but
need not, be used when the function is
called gtgta 32.2 here use different
names gtgtinitial_speed 10 gtgttime
5 gtgtfeet_dropped,speed . . .
drop(a,initial_speed,time)
a, initial_speed, and time are different local
parameters inside the function drop anyway
(continued )
3-31
33Function Example (continued) 2. The input
variables need not be assigned values outside the
function prior to the function call, can just use
literal numbers feet_dropped,speed
drop(32.2,10,5) 3. The inputs and outputs may be
arrays feet_dropped,speeddrop(32.2,10,015
) This function call produces the arrays
feet_dropped and speed, each with six values
corresponding to the six values of time in the
array time. In class Ch3 9, 12
3-32
More? See pages 148-153.
34 Local Variables The names of the input
variables given in the function definition line
are local to that function. This means that
other variable names can be used when you call
the function. All variables inside a function
are erased after the function finishes executing,
except when the same variable names appear in the
output variable list used in the function
call. For example, when using drop function, we
can assign vel and dist before function call, and
their values will be unchanged after the call
because vel and dist do NOT appear in the output
list (feet_dropped and speed) were used. All
variables are gone once a function finishes gt
harder to find errors. Use Debugger Utility
3-33
35Global Variables The global command declares
certain variables global, and therefore their
values are available to the basic workspace and
to other functions that declare these variables
global. The syntax to declare the variables a,
x, and q is global a x q Any assignment to
those variables, in any function or in the base
workspace, is available to all the other
functions declaring them global. Note that it
is very easy to change a global variable by
mistake and very hard to find this error use it
only for global constants.
3-34
More? See pages 153-156.
36- Global Variables (continue)
- The proper use of global is for parameters which
are common to several functions - global g
- g 9.81
- ..
- .
- vel velfunct(t,v0)
- function v velfunc(t,v0)
- global g
- v v0 gt
- Book uses ideal gas and van-der-Waals gas example
37Finding Zeros of a Function We have used before
roots to find roots of polynomials, but it only
works for polynomials. For arbitrary function,
use the fzero function to find the zero of a
function of a single variable, which is denoted
by x. As always PLOT FIRST One form of its
syntax is fzero(function, x0) where function
is a string containing the name of the function,
and x0 is a user-supplied guess for the zero.
The fzero function returns a value of x that is
near x0, or NaN if it fails. It cannot find
complex roots ( fzero('x21',0) gives NaN). It
identifies only points where the function crosses
the x-axis, not points where the function just
touches the axis. (Although in the latest
version used on fzero('x2',0) gives 0 as it
should) For example, fzero(cos(x)sin(x),2)
returns the value 2.3562.
3-35
38- If x0 is vector or length two, fzero assumes
that x0 where the sign of function changes. - An error is given if it is NOT true.
- In this case, we are guaranteed to get a value
where function changes sign. - gtgt x,fval fzero('cos(x)sin(x)',2)
- x 2.3562
- fval 1.1102e-016 get the value of
function at solution x - gtgt x,fval,exitflag fzero('cos(x)sin(x)',2)
- x 2.3562
- fval 1.1102e-016
- exitflag 1 exitflag gt 0
found zero, exitflag lt 0 no interval was found
with sign change - Note fzero finds a point x where function
changes sign gt if it is continuous, f(x) 0 - It it is discontinous, it may return a
discontinous point - fzero('tan(x)',1) gives
1.5708 pi/2
39Using fzero with User-Defined Functions To use
the fzero function to find the zeros of more
complicated functions, it is more convenient to
define the function in a function file. For
example, if y x 2e-x -3, define the following
function file function y f1(x) y x
2exp(-x) - 3
(continued )
3-36
40Plot of the function y x 2e-x - 3. Figure
3.21
PLOT FIRST There is a zero near x -0.5 and one
near x 3.
3-37
(continued )
41Example (continued) To find a more precise value
of the zero near x -0.5, type gtgtx
fzero(f1,-0.5) OR gtgtx fzero(_at_f1,-0.5) The
answer is x -0.5881.
3-38
More? See pages 156-157.
42Finding the Minimum of a Function The fminbnd
function finds the minimum of a function of a
single variable, which is denoted by x. One form
of its syntax is fminbnd(function, x1, x2)
OR fminbnd(_at_function, x1, x2) where
function is a string containing the name of the
function. The fminbnd function returns a value
of x that minimizes the function in the closed
interval x1 x x2. As always, PLOT FIRST For
example, fminbnd(cos,0,4) returns the value
3.1416 approximately pi, where cos reaches min
of (-1).
3-39
43When using fminbnd it is more convenient to
define the function in a function file. For
example, if y 1 - xe -x , define the following
function file function y f2(x) y
1-x.exp(-x) To find the value of x that gives
a minimum of y for 0 x 5, type gtgtx
fminbnd(f2,0,5) The answer is x 1. To find
the minimum value of y, type y f2(x). The
result is y 0.6321. Or better use
x,fval,exitflag fminbnd(f2,0,5) To find
max of a function, find min of ( - f(x))
3-40
44A function can have one or more local minima and
a global minimum. If the specified range of the
independent variable does not enclose the global
minimum, fminbnd will not find the global
minimum. fminbnd may find a minimum that occurs
on a boundary.
3-41
45Plot of the function y 0.025x 5 - 0.0625x 4 -
0.333x 3 x 2. Figure 3.22
This function has one local and one global
minimum. On the interval 1, 4 the minimum is at
the boundary x 1, while there is local min
at x 3.
3-42
46To find the minimum of a function of more than
one variable, use the fminsearch function. One
form of its syntax is fminsearch(function,
x0) where function is a string containing the
name of the function. The vector x0 is a guess
that must be supplied by the user.
3-43
47To minimize the function f xe-x2 - y2 , we
first define it in an M-file, using the vector x
whose elements are x(1) x and x(2)
y. function f f4(x) f x(1).exp(-x(1).2-x(2)
.2) Suppose we guess that the minimum is near
x y 0. The session is gtgtfminsearch(f4,0,0
) ans -0.7071 0.000 Thus the minimum
occurs at x -0.7071, y 0. The alternative
syntax gtgtx,fval,exitflag fminsearch(f4,0,
0) fminsearch can often handle discontinuities
particularly near the solutions. It may give
local min only and minimizes only over real
numbers For complex x, split into real and
imaginary parts.
3-44
More? See pages 157-162.
48 Evaluating input functions Inside of functions
in order to evaluate functions which are passed
into given function as arguments, we must utilize
the feval. Example We would like to write a
function that computes the slope of the line
between the two points (a, f (a)) and (b, f (b)).
Recall that the slope between these two points
is give by m ( f (b) - f (a) )/ ( b - a ) .
We begin by writing a MATLAB function called
slope.m slope.m -compute the slope between
(a,f(a)) and (b,f(b)) function m
slope(func,a,b) fa feval(func,a) fb
feval(func,b) m (fb-fa)/(b-a) If we are
now in the correct directory, we type in MATLAB
gtgt slope(_at_functest,1,2) where functest is
defined in a separate file
493-45
Function Handles You can create a function
handle to any function by using the at sign, _at_,
before the function name. You can then name the
handle if you wish, and use the handle to
reference the function. For example, to create
a handle to the sine function, you
type gtgtsine_handle _at_sin where sine_handle is
a user-selected name for the handle.
(continued )
50Function Handles (continued) A common use of a
function handle is to pass the function as an
argument to another function. For example, we
can plot sin x over 0 x 6 as
follows gtgtplot(00.016,feval(sine_handle,00
.016)) Book has a typo no feval???
(continued )
3-46
51Function Handles (continued) This is a rather
cumbersome way to plot the sine function, but the
concept can be extended to create a general
purpose plotting function that accepts a function
as an input. For example, function x
gen_plot(fun_handle, interval) plot(interval,
feval(fun_handle, interval)) You may call this
function to plot the sin x over 0 x 6 as
follows gtgtgen_plot(sine_handle,00.016) or gtgtg
en_plot(_at_sin,00.016)
(continued )
3-47
52Function Handles (continued) There are a number
of advantages of using function handles
like speed of execution, providing access to
sub-functions, using function handles as data
types can create arrays of function
handles. For example, this function gen_plot may
be used as follows with a function handle array,
to create two subplots, one for the sine and one
for the cosine. fh(1) _at_sin fh(2) _at_cos for
k 12 subplot(2,1,k) gen_plot(fh(k),00.0
18) end
3-48
More? See pages 163-164.
53- Methods for Calling Functions
- There are four ways to invoke, or call, a
function into action. These are - As a character string identifying the appropriate
function M-file, - 2. As a function handle,
- 3. As an inline function object, or
- 4. As a string expression.
- Examples of these ways follow for the fzero
function used with the user-defined function
fun1, which computes y x2 - 4.
(continued )
3-49
54Methods for Calling Functions (continued) 1. As
a character string identifying the appropriate
function M-file, which is function y
fun1(x) y x.3 1 The function may be
called as follows, to compute the zero over the
range -2 x 1 gtgtx, value
fzero(fun1,-2, 1)
(continued )
3-50
55Methods for Calling Functions (continued) 2. As
a function handle to an existing function
M-file gtgtx, value fzero(_at_fun1,-2, 1) --
fastest method 3. As an inline function
object gtgtfun1 x.3 1 gtgtfun_inline
inline(fun1) gtgtx, value fzero(fun_inline,-2
, 1) Inline method is slower than others
(continued )
3-51
56Methods for Calling Functions (continued) 4. As
a string expression gtgtfun1 x.3
1 gtgtx, value fzero(fun1,-2, 1) or
as gtgtx, value fzero(x.3 1,-2, 3) --
determines that 1st argument to fzero is a string
and calls inline to convert the string into
inline function object.
(continued )
3-52
57Methods for Calling Functions (continued) The
function handle method (method 2) is the fastest
method, followed by method 1. In addition to
speed improvement, another advantage of using a
function handle is that it provides access to
subfunctions, which are normally not visible
outside of their defining M-file.
3-53
More? See pages 164-165.
58Types of User-Defined Functions The following
types of user-defined functions can be created in
MATLAB. The primary function is the first
function in an M-file and typically contains the
main program. Following the primary function in
the same file can be any number of subfunctions,
which can serve as subroutines to the primary
function.
(continued )
3-54
59Types of User-Defined Functions
(continued) Usually the primary function is the
only function in an M-file that you can call from
the MATLAB command line or from another M-file
function. You invoke this function using the
name of the M-file in which it is defined. We
normally use the same name for the function and
its file, but if the function name differs from
the file name, you must use the file name
to invoke the function.
(continued )
3-55
60Types of User-Defined Functions
(continued) Anonymous functions enable you to
create a simple function without needing to
create an M-file for it. You can construct an
anonymous function either at the MATLAB command
line or from within another function or script.
Thus, anonymous functions provide a quick way
of making a function from any MATLAB expression
without the need to create, name, and save a
file.
(continued )
3-56
61Types of User-Defined Functions
(continued) Subfunctions are placed in the
primary function and are called by the primary
function. You can use multiple functions
within a single primary function M-file.
(continued )
3-57
62Types of User-Defined Functions
(continued) Nested functions are functions
defined within another function. They can help
to improve the readability of your program and
also give you more flexible access to variables
in the M-file. The difference between nested
functions and subfunctions is that subfunctions
normally cannot be accessed outside of their
primary function file.
(continued )
3-58
63Types of User-Defined Functions
(continued) Overloaded functions are functions
that respond differently to different types of
input arguments. They are similar to overloaded
functions in any object-oriented language. For
example, an overloaded function can be created to
treat integer inputs differently than inputs of
class double.
(continued )
3-59
64Types of User-Defined Functions
(continued) Private functions enable you to
restrict access to a function. They can be
called only from an M-file function in the parent
directory.
3-60
More? See pages 165-172.
65The term function function is not a separate
function type but refers to any function that
accepts another function as an input argument,
such as the function fzero. You can pass a
function to another function using a function
handle.
3-61
66Anonymous Functions Anonymous functions enable
you to create a simple function without needing
to create an M-file for it. You can construct
an anonymous function either at the MATLAB
command line or from within another function or
script. The syntax for creating an anonymous
function from an expression is fhandle
_at_(arglist) expr where arglist is a
comma-separated list of input arguments to be
passed to the function, and expr is any single,
valid MATLAB expression. fhandle is a function
handle, can pass it to other functions.
3-62
(continued )
67Anonymous Functions (continued) To create a
simple function called sq to calculate the square
of a number, type gtgtsq _at_(x) x.2 To improve
readability, you may enclose the expression in
parentheses, as sq _at_(x) (x.2). To execute
the function, type the name of the function
handle, followed by any input arguments enclosed
in parentheses. For example, gtgtsq(5,7) ans
25 49
(continued )
3-63
68Anonymous Functions (continued) You might think
that this particular anonymous function will not
save you any work because typing sq(5,7)
requires nine keystrokes, one more than is
required to type 5,7.2. Here, however, the
anonymous function protects you from forgetting
to type the period (.) required for array
exponentiation. Anonymous functions are useful,
however, for more complicated functions involving
numerous keystrokes.
(continued )
3-64
69Anonymous Functions (continued) You can pass the
handle of an anonymous function to other
functions. For example, to find the minimum of
the polynomial 2x2 - 10x 1 over the interval
-4, 4, you type gtgtpoly1 _at_(x) 2x.2 - 10x
1 gtgtfminbnd(poly1, -4, 4) ans 2.5 If you are
not going to use that polynomial again, you can
omit the handle definition line and type
instead gtgtfminbnd(_at_(x) 2x.2 - 10x 1, -4, 4)
3-65
70Multiple Input Arguments You can create
anonymous functions having more than one input.
For example, to define the function Ö(x 4 y 6
-1), type gtgtf _at_(x,y) sqrt(x.4 y.6
-1) Then type gtgtf(3, 4) ans 64.6220
3-66
71As another example, consider the function
defining a plane, z Ax By. The scalar
variables A and B must be assigned values before
you create the function handle. For
example, gtgtA 2 B 3 gtgtplane _at_(x,y) Ax
By gtgtz plane(1,4) z 14
3-67
72- No input arguments
- d _at_() date
- To call it, just use
- gtgt d() must include parenthesis
- ans 24-Mar-2009
73Calling One Function within Another One
anonymous function can call another to implement
function composition. Consider the function 3
cos(x 4)-1. It is composed of the functions g(y)
3 cos(y) -1 and f (x) x 4. In the following
session the function whose handle is h calls the
functions whose handles are f and g. gtgtf _at_(x)
x.4 gtgtg _at_(x) 3cos(x)-1 gtgth _at_(x)
g(f(x)) gtgt h(3) ans 1.3301
3-68
74Variables and Anonymous Functions Variables can
appear in anonymous functions in two ways (1)
As variables specified in the argument list, as
for example f _at_(x) x.4 -1 (2) As variables
specified in the body of the expression, as for
example with the variables A and B in plane
_at_(x,y) Ax By. When the function is created
MATLAB captures the values of these variables and
retains those values for the lifetime of the
function handle. If the values of A or B are
changed after the handle is created, their values
associated with the handle do NOT change.
3-69
75Subfunctions A function M-file may contain more
than one user-defined function. The first
defined function in the file is called the
primary function, whose name is the same as the
M-file name. All other functions in the file
are called subfunctions. Subfunctions are
normally visible only to the primary function
and other subfunctions in the same file that is,
they normally cannot be called by programs or
functions outside the file. However, this
limitation can be removed with the use of
function handles.
(continued )
3-71
76Subfunctions (continued) Create the primary
function first with a function definition line
and its defining code, and name the file with
this function name as usual. Then create each
subfunction with its own function definition line
and defining code. The order of the
subfunctions does not matter, but function names
must be unique within the M-file.
3-72
More? See pages 168-170.
77Precedence When Calling Functions The order in
which MATLAB checks for functions is very
important. When a function is called from
within an M-file, MATLAB first checks to see if
the function is a built-in function such as
sin. If not, it checks to see if it is a
subfunction in the file, then checks to see if it
is a private function (which is a function M-file
residing in the private subdirectory of the
calling function). Then MATLAB checks for a
standard M-file on your search path.
(continued )
3-73
78Precedence When Calling Functions
(continued) Thus, because MATLAB checks for a
subfunction before checking for private and
standard M-file functions, you may use
subfunctions with the same name as another
existing M-file. This feature allows you to name
subfunctions without being concerned about
whether another function exists with the same
name, so you need not choose long function names
to avoid conflict. This feature also protects
you from using another function unintentionally.
3-74
79The following example shows how the MATLAB
M-function mean can be superceded by our own
definition of the mean, one which gives the
root-mean square value. The function mean is a
subfunction. The function subfun_demo is the
primary function. function y subfun_demo(a) y
a - mean(a) function w mean(x) w
sqrt(sum(x.2))/length(x)
(continued )
3-75
80Example (continued) A sample session
follows. gtgty subfn_demo(4, -4) y 1.1716
-6.8284 If we had used the MATLAB M-function
mean, we would have obtained a different answer
that is, gtgta4,-4 gtgtb a - mean(a) b 4
-4
3-76
81Thus the use of subfunctions enables you to
reduce the number of files that define your
functions. For example, if it were not for the
subfunction mean in the previous example, we
would have had to define a separate M-file for
our mean function and give it a different name so
as not to confuse it with the MATLAB function of
the same name. Subfunctions are normally visible
only to the primary function and other
subfunctions in the same file. However, we can
use a function handle to allow access to the
subfunction from outside the M-file.
3-77
More? See pages 169-170.
82- Example of using handles with subfunctions
- function yzero fn_demo1(range) -- primary
function - fun _at_testfun
-- NOTE the use of function handle - yzero, value fzero( fun, range)
- -------------------------------------------
- function y testfun(x) --
subfunction - y (x.2 - 1).cos(pix) ./(1x.2)
- gtgt fn_demo1(0 2)
- ans
- 1.5000 -- Works just fine
- Now do NOT use function handle
- function yzero fn_demo1(range) -- primary
function - yzero, value fzero( testfun, range)
-- did NOT use function handle - -------------------------------------------
- function y testfun(x) --
subfunction - y (x.2 - 1).cos(pix) ./(1x.2)
83Nested Functions With MATLAB 7 you can now place
the definitions of one or more functions within
another function - nested within the main
function. You can also nest functions within
other nested functions.
(continued )
3-78
84Nested Functions (continued) Like any M-file
function, a nested function contains the usual
components of an M-file function. You must,
however, always terminate a nested function with
an end statement. In fact, if an M-file contains
at least one nested function, you must terminate
all functions, including subfunctions, in the
file with an end statement, whether or not they
contain nested functions.
3-79
85Example The following example constructs a
function handle for a nested function and then
passes the handle to the MATLAB function fminbnd
to find the minimum point on a parabola. The
parabola function constructs and returns a
function handle f for the nested function p.
This handle gets passed to fminbnd. function f
parabola(a, b, c) f _at_p function y
p(x) y ax2 bx c end end
(continued )
3-80
86Example (continued) In the Command window
type gtgtf parabola(4, -50, 5) gtgtfminbnd(f,
-10, 10) ans 6.2500 Note than the function
p(x) can see the variables a, b, and c in the
calling functions workspace.
3-81
87- Nested functions might seem to be the same as
subfunctions, but they are not. - Nested functions have two unique properties
- A nested function can access the workspaces of
all functions inside of which it is nested. - So for example, a variable that has a value
assigned to it by the primary function can be
read or overwritten by a function nested at any
level within the main function. - A variable assigned in a nested function can be
read or overwritten by any of the functions
containing that function.
(continued )
3-82
882. If you construct a function handle for a
nested function, the handle not only stores the
information needed to access the nested function
it also stores the values of all variables shared
between the nested function and those functions
that contain it. This means that these variables
persist in memory between calls made by means of
the function handle.
3-83
More? See pages 170-172.
89Private Functions Private functions reside in
subdirectories with the special name private, and
they are visible only to functions in the parent
directory. Assume the directory rsmith is on the
MATLAB search path. A subdirectory of rsmith
called private may contain functions that only
the functions in rsmith can call. Because
private functions are invisible outside the
parent directory rsmith, they can use the same
names as functions in other directories.
(continued )
3-84
90Private Functions (continued) Primary functions
and subfunctions can be implemented as private
functions. Create a private directory by
creating a subdirectory called private using the
standard procedure for creating a directory or a
folder on your computer, but do not place the
private directory on your path.
3-85
91Importing Spreadsheet Files Some spreadsheet
programs store data in the .wk1 format. You can
use the command M wk1read(filename) to
import this data into MATLAB and store it in the
matrix M. The command A xlsread(filename)
imports the Microsoft Excel workbook file
filename.xls into the array A. The command A, B
xlsread(filename) imports all numeric data
into the array A and all text data into the cell
array B.
3-86
More? See pages 172-173.
92The Import Wizard To import ASCII data, you must
know how the data in the file is formatted. For
example, many ASCII data files use a fixed (or
uniform) format of rows and columns.
(continued )
3-87
93The Import Wizard (continued) For these files,
you should know the following. How many data
items are in each row? Are the data items
numeric, text strings, or a mixture of both
types? Does each row or column have a
descriptive text header? What character is
used as the delimiter, that is, the character
used to separate the data items in each row? The
delimiter is also called the column separator.
(continued )
3-88
94The Import Wizard (continued) You can use the
Import Wizard to import many types of ASCII data
formats, including data on the clipboard. Note
that when you use the Import Wizard to create a
variable in the MATLAB workspace, it overwrites
any existing variable in the workspace with the
same name without issuing a warning. The Import
Wizard presents a series of dialog boxes in which
you 1. Specify the name of the file you want
to import, 2. Specify the delimiter used in the
file, and 3. Select the variables that you want
to import.
3-89
95The first screen in the Import Wizard. Figure
3.41
3-90
More? See pages 173-177.
96The following slides contain figures from Chapter
3 and its homework problems.
3-91
97Cross section of an irrigation channel. Figure
3.23
3-92
98Figure P12
3-93
99Figure P13
3-94