If the function does not require any inputs, then you can call the function with empty parentheses,
such as
h = @ones;
a = h()
a =
1
Without the parentheses, the assignment creates another function handle.
a = h
a =
@ones
Function handles are variables that you can pass to other functions. For example, calculate the
integral of x
2
on the range [0,1].
q = integral(f,0,1);
Function handles store their absolute path, so when you have a valid handle, you can invoke the
function from any location. You do not have to specify the path to the function when creating the
handle, only the function name.
Keep the following in mind when creating handles to functions:
• Name length — Each part of the function name (including package and class names) must be less
than the number specified by namelengthmax. Otherwise, MATLAB truncates the latter part of
the name.
• Scope — The function must be in scope at the time you create the handle. Therefore, the function
must be on the MATLAB path or in the current folder. Or, for handles to local or nested functions,
the function must be in the current file.
• Precedence — When there are multiple functions with the same name, MATLAB uses the same
precedence rules to define function handles as it does to call functions. For more information, see
“Function Precedence Order” on page 20-37.
• Overloading — When a function handle is invoked with one or more arguments, MATLAB
determines the dominant argument. If the dominant argument is an object, MATLAB determines if
the object’s class has a method which overloads the same name as the function handle’s
associated function. If it does, then the object’s method is invoked instead of the associated
function.
Anonymous Functions
You can create handles to anonymous functions. An anonymous function is a one-line expressionbased MATLAB function that does not require a program file. Construct a handle to an anonymous
function by defining the body of the function, anonymous_function, and a comma-separated list of
input arguments to the anonymous function, arglist. The syntax is:
h = @(arglist)anonymous_function
For example, create a handle, sqr, to an anonymous function that computes the square of a number,
and call the anonymous function using its handle.
Create Function Handle
13-3
Précédent

- 561/1450

Suivant