| MATLAB® | ![]() |
| On this page… |
|---|
Calling a Function Using Its Handle Handling Values Returned From a Call Applications of Function Handles Saving and Loading Function Handles |
A function handle is a callable association to a MATLAB® function. It contains an association to that function that enables you to invoke the function regardless of where you call it from. This means that, even if you are outside the normal scope of a function, you can still call it if you use its handle.
With function handles, you can:
Pass a function to another function
Capture data values for later use by a function
Call functions outside of their normal scope
Make function calls more efficiently
Save the handle in a MAT-file to be used in a later MATLAB session
See Applications of Function Handles for an explanation of each of these applications.
You construct a handle for a specific function by preceding the function name with an @ sign. The syntax is:
h = @functionname
where h is the variable to which the returned function handle is assigned.
Use only the function name, with no path information, after the @ sign. If there is more than one function with this name, MATLAB associates with the handle the one function source it would dispatch to if you were actually calling the function.
Create a handle h for a function plot that is on your MATLAB path:
h = @plot;
Once you create a handle for a function, you can invoke the function by means of the handle instead of using the function name. Because the handle contains the absolute path to its function, you can invoke the function from any location that MATLAB is able to reach, as long as the M-file for the function still exists at this location. This means that functions in one M-file can call functions that are not on the MATLAB path, subfunctions in a separate M-file, or even functions that are private to another directory, and thus not normally accessible to that caller.
Function names used in handles are unique up to N characters, where N is the number returned by the function namelengthmax. If the function name exceeds that length, MATLAB truncates the latter part of the name.
For function handles created for Sun™ Java™ constructors, the length of any segment of the package name or class name must not exceed namelengthmax characters. (The term segment refers to any portion of the name that lies before, between, or after a dot. For example, java.lang.String has three segments). The overall length of the string specifying the package and class has no limit.
At the time you create a function handle, MATLAB must decide exactly which function it is to associate the handle to. In doing so, MATLAB uses the same rules used to determine which M-file to invoke when you make a function call. To make this determination, MATLAB considers the following:
Scope — The function named must be on the MATLAB path at the time the handle is constructed.
Precedence — MATLAB selects which function(s) to associate the handle with, according to the function precedence rules described under Determining Which Function Gets Called.
Overloading — If additional M-files on the path overload the function for any of the standard MATLAB classes, such as double or char, then MATLAB associates the handle with these M-files, as well.
M-files that overload a function for classes other than the standard MATLAB classes are not associated with the function handle at the time it is constructed. Function handles do operate on these types of overloaded functions, but MATLAB determines which implementation to call at the time of evaluation in this case.
Function handles also serve as the means of invoking anonymous functions. An anonymous function is a one-line expression-based MATLAB function that does not require an M-file.
For example, the statement
sqr = @(x) x.^2;
creates an anonymous function that computes the square of its input argument x. The @ operator makes sqr a function handle, giving you a means of calling the function:
sqr(20) ans = 400
See Anonymous Functions for more information on anonymous functions.
To create an array of function handles, you must use a cell array:
trigFun = {@sin, @cos, @tan};
To plot the cosine of the range -pi to pi at 0.01 intervals, use
plot(trigFun{2}(-pi:0.01:pi))To execute a function associated with a function handle, use the syntax shown here. In this example, h is a variable that has a function handle as its value:
h(arg1, arg2, ..., argn)
If the function being called takes no input arguments, then use empty parentheses after the handle name to call the function:
h()
If you use only the variable name, not followed by parentheses, MATLAB just identifies the name of the associated function and does not invoke the function:
h = @computer; % Construct the handle h.
h
h = % h alone just identifies the handle.
@computer
h() % h with parentheses invokes the function.
ans =
PCWIN
The following example creates a handle for a function supplied by MATLAB called humps and assigns it to the variable h. (The humps function returns a strong maxima near x = 0.3 and x = 0.9).
h = @humps;
After constructing the handle, you can pass it in the argument list of a call to some other function, as shown here. This example passes the function handle h that was just created as the first argument in a call to fminbnd. This function then minimizes over the interval [0.3, 1].
x = fminbnd(h, 0.3, 1)
x =
0.6370Using a function handle enables you to pass different functions for fminbnd to use in determining its final result.
When you invoke a function using a function handle, you can capture any or all values returned from the call in the same way you would if you were calling the function directly. Just list the output variables to the left of the equals (=) sign. When assigning to multiple outputs, enclose the output variables within square brackets:
[out1 out2 ...] = h(arg1, arg2, arg3, ...)
The example below returns multiple values from a call to an anonymous function. Create anonymous function f that locates the nonzero elements of an array, and returns the row, column, and value of each element in variables row, col, and val:
f = @(X)find(X);
Call the function on matrix m using the function handle f. Because the function uses the MATLAB find function which returns up to three outputs, you can specify from 0 to 3 outputs in the call:
m = [3 2 0; -5 0 7; 0 0 1]
m =
3 2 0
-5 0 7
0 0 1
[row col val] = f(m);
val
val =
3
-5
2
7
1The following sections discuss the advantages of using function handles:
The ability to pass variables to a function enables you to run the function on different values. In the same way, you can pass function handles as input arguments to a function, thus allowing the called function to change the operations it runs on the input data.
Example 1 — Run quad on Varying Functions. Run the quadrature function on varying input functions:
a = 0; b = 5;
quad(@log, a, b)
ans =
3.0472
quad(@sin, a, b)
ans =
0.7163
quad(@humps, a, b)
ans =
12.3566
Example 2 — Run quad on Anonymous Functions. Run quad on a MATLAB built-in function or an anonymous function:
n = quad(@log, 0, 3); n = quad(@(x)x.^2, 0, 3);
Change the parameters of the function you pass to quad with a simple modification of the anonymous function that is associated with the function handle input:
a = 3.7; z = quad(@(x)x.^a, 0, 3);
Example 3 — Compare quad Results on Different Functions. Compare the integral of the cosine function over the interval [a, b]:
a = 0; b = 10; int1 = quad(@cos,a,b) int1 = -0.5440
with the integral over the same interval of the piecewise polynomial pp that approximates the cosine function by interpolating the computed values x and y:
x = a:b; y = cos(x); pp = spline(x,y); int2 = quad(@(x)ppval(pp,x), a, b) int2 = -0.5485
You can do more with a function handle than just create an association to a certain function. By using function handles with nested functions, you can also capture certain variables and their values from the workspace of a function to its handle. These data values are stored within the handle at the time of its construction, and are contained within the handle for as long as it exists. (Although data values within a function handle are held constant, you can replace any or all of these values by reinvoking the handle constructor with different inputs.) Whenever you invoke the function by means of its handle, MATLAB supplies the function with all variable inputs specified in the argument list of the function call, and also any constant inputs that were stored in the function handle at the time of its construction.
Storing some or all input data in a function handle enables you to reliably use the same set of data with that function regardless of where or when you invoke the handle. You can also interrupt your use of a function and resume it with the same data at a later time simply by saving the function handle to a MAT-file.
Example 1 — Constructing a Function Handle to Hold Data. Compare the following two ways of implementing a simple plotting function called draw_plot. The first case creates the function as one that you would call by name and that accepts seven inputs specifying coordinate and property information:
function draw_plot(x, y, lnSpec, lnWidth, mkEdge, mkFace, mkSize)
plot(x, y, lnSpec, ...
'LineWidth', lnWidth, ...
'MarkerEdgeColor', mkEdge, ...
'MarkerFaceColor', mkFace, ...
'MarkerSize', mkSize)The second case implements draw_plot as a nested function to be called by a function handle, h. The draw_plot function has only two inputs now; the remaining five are specified only on a call to the handle constructor function, get_plot_handle:
function h = get_plot_handle(lnSpec, lnWidth, mkEdge, mkFace, mkSize)
h = @draw_plot;
function draw_plot(x, y)
plot(x, y, lnSpec, ...
'LineWidth', lnWidth, ...
'MarkerEdgeColor', mkEdge, ...
'MarkerFaceColor', mkFace, ...
'MarkerSize', mkSize)
end
endBecause these input values are required by the draw_plot function, but are not made available in its argument list, MATLAB supplies them by storing them in the function handle for draw_plot at the time it is constructed. Construct the function handle h, also supplying the values to be stored in handle:
h = get_plot_handle('--rs', 2, 'k', 'g', 10);
Now call the function, specifying only the x and y inputs:
x = -pi:pi/10:pi; y = tan(sin(x)) - sin(tan(x)); h(x, y) % Draw the plot
The later section on Examining a Function Handle continues this example by showing how you can examine the contents of the function and workspace contents of this function handle.
Example 2 — Varying Data Values Stored in a Function Handle. Values stored within a function handle do not have to remain constant. The following function constructs and returns a function handle h to the nested function addOne. In addition to associating the handle with addOne, MATLAB also stores the initial value of x in the function handle:
function h = counter x = 0; h = @addOne; function y = addOne; x = x + 1; y = x; end end
The addOne function that is associated with handle h increments variable x each time you call it. This modifies the value of the variable stored in the function handle:
h = counter; h() 1 h() 2
Example 3 — You Cannot Vary Data in a Handle to an Anonymous Function. Unlike the example above, values stored within a handle to an anonymous function do remain constant. Construct a handle to an anonymous function that just returns the value of x, and initialize x to 300. The value of x within the function handle remains constant regardless of how you modify x external to the handle:
x = 300; h = @()x; x = 50; h() ans = 300 clear x h() ans = 300
By design, only functions within an M-file are permitted to access subfunctions defined within that file. However, if, in this same M-file, you were to construct a function handle for one of the internal subfunctions, and then pass that handle to a variable that exists outside of the M-file, access to that subfunction would be essentially unlimited. By capturing the access to the subfunction in a function handle, and then making that handle available to functions external to the M-file (or to the command line), the example extends that scope. An example of this is shown in the preceding section, Capture Data Values For Later Use By a Function.
Private functions also have specific access rules that limit their availability with the MATLAB environment. But, as with subfunctions, MATLAB allows you to construct a handle for a private function. Therefore, you can call it by means of that handle from any location or even from the MATLAB command line, should it be necessary.
When you invoke any function, MATLAB must spend some amount of time locating each instance of the function that exists on the path, in a private subdirectory, or in the same M-file. Having found each instance, it must then determine which of these takes precedence over the others.
Because a function handle contains the absolute path to its function, neither of these tasks is necessary when you invoke a function by means of its handle. This can give you a minor improvement in performance when calling functions.
If you have one or more function handles that you would like to reuse in a later MATLAB session, you can store them in a MAT-file using the save function and then use load later on to restore them to your MATLAB workspace.
You can save and load function handles in a MAT-file using the MATLAB save and load functions. If you load a function handle that you saved in an earlier MATLAB session, the following conditions could cause unexpected behavior:
Any of the M-files that define the function have been moved, and thus no longer exist on the path stored in the handle.
You load the function handle into an environment different from that in which it was saved. For example, the source for the function either doesn't exist or is located in a different directory than on the system on which the handle was saved.
In both of these cases, the function handle is now invalid because it is no longer associated with any existing function code. Although the handle is invalid, MATLAB still performs the load successfully and without displaying a warning. Attempting to invoke the handle, however, results in an error.
If you create a handle to a function that is not on the MATLAB path, or if you load a handle to a function that is no longer on the path, MATLAB catches the error only when the handle is invoked. You can assign an invalid handle and use it in such operations as func2str. MATLAB catches and reports an error only when you attempt to use it in a runtime operation.
Advanced operations include:
Use the functions function to examine the contents of a function handle.
Caution MATLAB provides the functions function for querying and debugging purposes only. Because its behavior may change in subsequent releases, you should not rely upon it for programming purposes. |
The following example is a continuation of the example shown in Example 1 — Constructing a Function Handle to Hold Data. The example constructs a function handle that contains both a function association, and data required by that function to execute. The function shown here constructs the function handle, h:
function h = get_plot_handle(lnSpec, lnWidth, mkEdge, mkFace, mkSize)
h = @draw_plot;
function draw_plot(x, y)
plot(x, y, lnSpec, ...
'LineWidth', lnWidth, ...
'MarkerEdgeColor', mkEdge, ...
'MarkerFaceColor', mkFace, ...
'MarkerSize', mkSize)
end
endUse functions to examine the contents of the returned handle:
f = functions(h)
f =
function: 'get_plot_handle/draw_plot'
type: 'nested'
file: 'D:\matlab\work\get_plot_handle.m'
workspace: {[1x1 struct]}
The call to functions returns a structure with four fields:
function — Name of the function or subfunction to which the handle is associated. (Function names that follow a slash character (/) are implemented in the program code as subfunctions.)
type — Type of function (e.g., simple, nested, anonymous)
file — Filename and path to the M-file. (For built-in functions, this is the string 'MATLAB built-in function')
workspace — Variables in the function workspace at the time the handle was constructed, along with their values
Examine the workspace variables that you saved in the function handle:
f.workspace{:}
ans =
h: @get_plot_handle/draw_plot
lnSpec: '--rs'
lnWidth: 2
mrkrEdge: 'k'
mrkrFace: 'g'
mrkrSize: 10Two functions, str2func and func2str enable you to convert between a string containing a function name and a function handle that is associated with that function name.
Converting a String to a Function Handle. Another means of creating a function handle is to convert a string that holds a function name to a handle for the named function. You can do this using the str2func function:
handle = str2func('functionname');The example below takes the name of a function as the first argument. It compares part of the name to see if this is a polynomial function, converts the function string to a function handle if it is not, and then calls the function by means of its handle:
function run_function(funcname, arg1, arg2)
if strncmp(funcname, 'poly', 4)
disp 'You cannot run polynomial functions on this data.'
return
else
h = str2func(funcname);
h(arg1, arg2);
endNote Nested functions are not accessible to str2func. To construct a function handle for a nested function, you must use the function handle constructor, @. |
Converting a Function Handle to a String. You can also convert a function handle back into a string using the func2str function:
functionname = func2str(handle);
This example converts the function handle h to a string containing the function name, and then uses the function name in a message displayed to the user:
function call_h(h, arg1, arg2)
sprintf('Calling function %s ...\n', func2str(h))
h(arg1, arg2)
This section describes how MATLAB determines whether or not separate function handles are equal to each other:
Comparing Handles Constructed from a Named Function. MATLAB considers function handles that you construct from the same named function (e.g., handle = @sin) to be equal. The isequal function returns a value of true when comparing these types of handles:
func1 = @sin;
func2 = @sin;
isequal(func1, func2)
ans =
1
If you save these handles to a MAT-file, and then load them back into the workspace later on, they are still equal.
Comparing Handles to Anonymous Functions. Unlike handles to named functions, any two function handles that represent the same anonymous function (i.e., handles to anonymous functions that contain the same text) are not equal. This is because MATLAB cannot guarantee that the frozen values of nonargument variables (such as A, below) are the same.
A = 5;
h1 = @(x)A * x.^2;
h2 = @(x)A * x.^2;
isequal(h1, h2)
ans =
0Note In general, MATLAB may underestimate the equality of function handles. That is, a test for equality may return false even when the functions happen to behave the same. But in cases where MATLAB does indicate equality, the functions are guaranteed to behave in an identical manner. |
If you make a copy of an anonymous function handle, the copy and the original are equal:
h1 = @(x)A * x.^2; h2 = h1;
isequal(h1, h2)
ans =
1Comparing Handles to Nested Functions. MATLAB considers function handles to the same nested function to be equal only if your code constructs these handles on the same call to the function containing the nested functions. Given this function that constructs two handles to the same nested function:
function [h1, h2] = test_eq(a, b, c) h1 = @findZ; h2 = @findZ; function z = findZ z = a.^3 + b.^2 + c'; end end
function handles constructed from the same nested function and on the same call to the parent function are considered equal:
[h1 h2] = test_eq(4, 19, -7);
isequal(h1, h2),
ans =
1
while those constructed from different calls are not considered equal:
[q1 q2] = test_eq(3, -1, 2);
isequal(h1, q1),
ans =
0
Comparing Handles Saved to a MAT-File. If you save equivalent anonymous or nested function handles to separate MAT-files, and then load them back into the MATLAB workspace, they are no longer equal. This is because saving the function handle loses track of the original circumstances under which the function handle was created. Reloading it results in a function handle that compares as being unequal to the original function handle.
Create two equivalent anonymous function handles:
h1 = @(x) sin(x);
h2 = h1;
isequal(h1, h2)
ans =
1
Save each to a different MAT-file:
save fname1 h1; save fname2 h2;
Clear the MATLAB workspace, and then load the function handles back into the workspace:
clear all load fname1 load fname2
The function handles are no longer considered equal:
isequal(h1, h2)
ans =
0
Note, however, that equal anonymous and nested function handles that you save to the same MAT-file are equal when loaded back into MATLAB.
MATLAB provides the following functions for working with function handles. See the reference pages for these functions for more information.
Function | Description |
|---|---|
Return information describing a function handle. | |
Construct a function name string from a function handle. | |
Construct a function handle from a function name string. | |
Save a function handle from the current workspace to a MAT-file. | |
Load a function handle from a MAT-file into the current workspace. | |
Determine if a variable contains a function handle. | |
Determine if two function handles are handles to the same function. |
![]() | Cell Arrays | MATLAB® Classes | ![]() |
| © 1984-2008- The MathWorks, Inc. - Site Help - Patents - Trademarks - Privacy Policy - Preventing Piracy - RSS |