Programming and Data Types | ![]() ![]() |
Constructing a Function Handle
Construct a function handle in MATLAB using the at sign, @
, before the function name. The following example creates a function handle for the humps
function and assigns it to the variable, fhandle
.
Pass the handle to another function in the same way you would pass any argument. This example passes the function handle just created to fminbnd
, which then minimizes over the interval [0.3,
1]
.
The fminbnd
function evaluates the @humps
function handle using feval
. A small portion of the fminbnd
M-file is shown below. In line 1, the funfcn
input parameter receives the function handle, @humps
, that was passed in. The feval
statement, in line 113, evaluates the handle.
1 function [xf,fval,exitflag,output] = ... fminbnd(funfcn,ax,bx,options,varargin).
.
.
113 fx = feval(funfcn,x,varargin{:});
Note
When creating a function handle, you may only use the function name after the @ sign. This must not include any path information. The following syntax is invalid: fhandle = @\home\user4\humps .
|
Maximum Length of a Function Name
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 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, there are three segments in java.lang.String.) There is no limit to the overall length of the string specifying the package and class.
![]() | A Simple Function Handle | Evaluating a Function Through Its Handle | ![]() |