Advanced Function Programming
Since the introduction of function handles in MATLAB 6.0, their use has become quite widespread in the MATLAB documentation and elsewhere, and so it.is a good idea to become familiar with the concept. In addition, anonymous functions, subfunctions, and nested functions are also now seen more often In documentation
and examples. This section covers the basic features of function handles and these new types of functions: The topics covered in this section are most useful for large programming projects. An understanding of these topics is not,necessary to master the remaining topics in this, text. Therefore, this section may be omitted, if desired.
Function Handles ;
You can create a function handle, to any function by using the at sign, @, before the function name. You can the 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.
»sine~handle = @sin;
where sine_handle is a user-selected name for the handle.
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:
»p.lot ( [0: 0.01: 6] , sine handle [0: 0.,01: 6] )
where we have used tile feval function to evaluate the function at the given argument [0: 0 . 01 : 6] . This is a rather cumbersome way to plot the sine function, but the concept can ‘be extended to create a general purpose platting function that accepts a function as an i,n.put For example,
function x = gen-plot (fun_handle, interval) plot (interval, fun_handle, ‘interval)
You may call this function-to plot the sin x over 0:::: x ::::6 as follow
»gen-plot (sine handle, f 0: 0.01: 6) ) ::
»gen-plot (@sin, [0: 0.01: 6])
There are several’ advantages to using function handles; these are described in “the MATLAB documentation. Two advantages that we will discuss later are speed of execution and providing access to sub functions, which are normally not visible’outside of their defining M-file. Another advantage is that function handles are a standard MATLAB data type, and’thus they can be used in the same manner’ as other data types. For example, you can create arrays, cell arrays, or structures of function handles. You can access individual function handles just as you access elements of a numeric array or structure.
For example, the 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(l) = @sin;
fh(2) =. @cos;
for. k = 1:2
gen-plot (fh(k),[0:O.01: 8] )
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,
- As a function handle,
- As an “inline” function object, or
Examples of these ways follow for the f zero function used with the user-defined
function fun1, which computes y =x2 – 4.
- As a character string identifying the appropriate function M-file, which is
function y = fun1~x)y = x.”2-4;
The function may be called as follows, to compute the zero over the range o ~x::::: 3: »[x, value] = fzero(‘fun1’, [0, 3])
- As a function handle to an existing function:M-file
»[x,value] = fzero(@funl, [q, 3])
- As an “inline” function object: ·»fun1 = ‘x.”2-4’; »fun_inline = . .inline(fun1) ; »[x, value] = fzero(fun_inline, [0, 3])
- As’ a string expression:
»funl = ‘x.”2-4’; »[x, value] = fzero(funl, [0, 3])
or as »[x,.value] = fzero(‘x.”2-4’,[O, 3]
The third method, which uses an inline object, is not discussed in the
and fourth methods are equivalent because they both utilize the inline function; the only difference is that with the fourth method MATLAB determines that the first argument of f zero is a string variable and calls inline to convert the string variable to an inline function object. 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 sub functions, which are normally not visible outside of their defining M-file. This is discussed later in this section.
Types of Functions
At this point it is helpful to review the types of functions provided for in MATLAB. MATLAB provides built-if functions, such as clear, sin, and plot, which are not M-files, and also some functions that are M-files, such as the function mean.In addition, 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 sub functions, which can serve as subroutines to the primary function. 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.
• 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.
• Sub-functions 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.·
• 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 sub functions is that sub functions normally cannot be accessed outside of their primary function file.
• 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.
• Private functions enable you to restrict access to a function. They can be called
The 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 f zero. You can pass a function to another function using a function handle.
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 = @ (arglist) expr
where arglist is a comma-separated list bf input arguments to be passed to the functions and expr is arty!single, valid MATLAB expression. This syntax creates the function handle f handle, which enables you to invoke the function. Note/that this. syntax is different from that used to create other function handles, f hand Le = function name .The handle is also useful for passing the anonymous function in call to some other function in the same way as any other
For example; to create a simple function called sq to calculate the square of a number, type
sq =: @(x) x.”2;-‘
To improve.readability, you may in close the expression in parentheses, as sq ‘= @(x) (x . “2) :. To execute the function, type the name of the function handle, followed by any input arguments enclosed in parentheses. For example,
»sq ( [5, 7] )
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. You can pass the handle of an anonymous function to other functions. For example, to find the minimum of the polynomial 4×2 – 50x +5 over the interval
[-10, 10], you type
» poly1 = @(x)’ 4*x.”2 :- 50*x + 5:
» fminbnd (poly1, -10, 10)
If you are not going to use that polynomial again, you can omit the handle definition line and type instead »fminbnd(@(x) 4*X.A2 – 50*x + 5, -10, 10) .
Mlultiple Input Arguments You can create anonymous functions having more than one input. For example, to define the function Jx2 +y2, type »sqrtsum = @(x,y) sqrt(x.A2 + y.A2);
Then »sqrtsum (3, 4)
As another example, consider the function defining a plane, ~ = Ax + By. The scalar variables A and B must. be assigned values before you create the function handle. For example, »A = 6; B = 4: »plane = @(x~y) A*x + B*y; »z = plane(2,8) Z = 44 •’0 Input Arguments- To construct a handle for an anonymous function that has
no input arguments,
use empty parentheses for the input argument list, as
shown by the following: d = @ () date ; . Use empty parentheses when invoking the function, as follows:
You must include the parentheses. If you do not, MATLAB just identifies the handle; it does not execute the function.
Calling One Function within Another one anonymous function can call another to implement function composition. Consider the function 5 sin(x3). It is composed of the functions g(y) = 5 sin(y) and I(x) = x3; In the following session the function whose handle is h calls the functions whose handles are f and g.
»f = @(x) x.A3;
»g = @(x) 5*sin(x);
»h = @(x) g(f(x));
To preserve an anonymous function from one MATLAB session to the next, save the function handle to a MAT-file. For example, to save the function associated with the handle h, type save anon. mat h. To recover it in a later session, type load anon.mat h.
Variables and Anonymous Functions
Variables can appear in anonymous functions in two ways:
• As variables specified in the argument list, as for example f = @(x) x. A 3 i ,and
• As variables specified in the body of the expression, as for example with the variables A and B in plane = @(x,y) A*x + By.In this case,when the function is created MATLAB captures the values of these variables and retains those values for the lifetime of the function handle. In this example, if the values of A or B are changed after the handle is created, their values associated with the handle do not change. This feature has both advantages and disadvantages, so you must keep it in mind.
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 sub-functions. Sub-functions are normally “visible” only to the primary function and other sub-functions 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, as we will see later in this section. .
Create the primary function first with a function definition line and its defining code, an<l’name the file with this function name as usual. Then create each sub-function with its own function definition line and defining code. The order of the sub-functions does not matter, but function names must be unique within the M-file.
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 sub-function in the file, then checks to see if it is a private function (which is a function M-file residing in the private sub-directory of the calling function). Then MATLAB checks for a standard M-file on your search path. Thus, because MATLAB checks for a sub-function before checking for private and standard M-file functions, you may use sub-functions with the same name as another.existing M-file. This feature allows you to name sub-functions 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. Note that you may even super cede a MATLAB M-function in this way. The following example shows how the MATLAB M-function mean can be
super-ceded by our own definition of the mean. one which gives the root mean square value. The function mean is a sub-function. The function sub-function demo IS the primary function
function y subfn=demo(a) y = a
y = a- mean (a)
function w = mean (x)
w = sqrt (sum(x.A2)) length(x)
A sample session follows
y = sub-function demo([4, -4])
1.1716 . -6.8284
If we had used the MATLAB M-file function mean, we would have obtained a different answer; that is,
»a=[4,-4]; »b = a – mean(a). b – 4 -4
Thus the use of sub-functions enables you to reduce the number of files that define your functions. For example, if it were not for the sub-function 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 (0 confuse .it with the MATLAB function of the same ‘name.
Sub-functions are normally visible only to the primary function and other sub-functions in the same file. However, we can use a function handle to allow access to the sub-function from outside the M-file, as the following example shows. Create the following M-file with the primary function fn_demo1 (range)and the sub-function test fun (x) to compute the zeros of the function (x2 – 4) cosx over the range specified in the input variable range. Note the use of a function
handle in the second line.
function yzero = fn 0 erange)
fun = @testfun;
[yzero,value] = fzero (fun,range)
function y = testfun (x)
y = (x.A2-4).*cos(x);
A test session gives the following results,
»yzero = fn_demo1([3, 6])
yzero = 4.7124
So the zero of (x2 – 4) cos x over 3 :5 x :5 6 occurs at x = 4.7124.
Suppose we had not used the function handle, as in
function yzero = fn_demo2(range)
[y~ero,value) = fzero(testfun,range);
function y = testfun(x)
y = (x.”2-4) .*cos(x);
Then the following session produces an error message.
»yzero= fn_demo2([3, 6))
??? Inp~t argument ‘x’ is undefined.
We get an error because the MA1LAB function’ fzero must call the function :testfun repeatedly but without the function handle, ,testlfun is not visible to fzero
with MATLAB7 you can now place the definitions one or functions within another function, Functions so defined are said to be nested within the main function. ‘You can also nest functions within other nested functions. Like any M-file function.a nested function contains the usual,comptlts 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 sub-functions, in the file with an end statement, whether or not they contain nested functions.
The following example constructs a function-handle fora nested function and then passes the handle to the MATLAB function fminbnd to find the minimum point on the 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 = @p;
function y = p(x)
y = a*x”2 + b*x + c;
In the Command window type
»f = parabola(4, -50, 5);
»fminbnd(f, -10, 10)
Nested functions might seem to be the same as sub-functions, but they are Note -than the function p (x ) can see the variables a, b, and c in the calling function’s work-space. not. Nested functions have two unique properties
- A nested function can access the work-spaces 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. In addition, a variable assigned in a nested function Can be read or overwritten by any of the functions containing that function.
- 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. •
Consider the following representation of some functions named A, B, … , E.
function A(x, y) _ % The primary function
B(x, y) i
function B(x, y) % Nested in A
C (x) i
C(x) % Nested in B
% This terminates C
% This terminates B
% ‘Nested in A
function E % Nested in 0
end % This terminates E
end % This terminates 0
end % This terminates A
You call a nested function in .several ways.
- You can call it from the level immediately above it. (In the previous code,
function A can call B or D,but not C or E.)
- You can call it from a function nested at the same level within the same
parent function. (Function B can call D, and D can call B.)
- You can call it from a function at any lower level. (Function C can call B or
D, but not E.)
If you construct a function handle for a nested function, you can call the
nested function from any MATLAB function that has access to the handle.You can call a sub-function from any nested function in the same M-file.
Private functions reside in sub-directories 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 sub-directory 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. This is useful if the main directory used by several individuals including R. Smith, but R. Smith wants .
to create a personal version of a particular function while retaining the original in the main directory. Because MATLAB looks for private functions before standard M-file functions, it will find a private function mimed, say cylinder. m,before
a non-private M-file named cylinder .m. Primary functions and sub-functions can be implemented as private functions.Create a private directory by creating a subdirectory called pri vate using the standard procedure for creating a directory or a folder on your computer, but do not place the private directory on your path