Anonymous Functions
In this section...
“What Are Anonymous Functions?” on page 20-20
“Variables in the Expression” on page 20-21
“Multiple Anonymous Functions” on page 20-21
“Functions with No Inputs” on page 20-22
“Functions with Multiple Inputs or Outputs” on page 20-22
“Arrays of Anonymous Functions” on page 20-23
What Are Anonymous Functions?
An anonymous function is a function that is not stored in a program file, but is associated with a
variable whose data type is function_handle. Anonymous functions can accept multiple inputs and
return one output. They can contain only a single executable statement.
For example, create a handle to an anonymous function that finds the square of a number:
sqr = @(x) x.^2;
Variable sqr is a function handle. The @ operator creates the handle, and the parentheses ()
immediately after the @ operator include the function input arguments. This anonymous function
accepts a single input x, and implicitly returns a single output, an array the same size as x that
contains the squared values.
Find the square of a particular value (5) by passing the value to the function handle, just as you
would pass an input argument to a standard function.
a = sqr(5)
a =
25
Many MATLAB functions accept function handles as inputs so that you can evaluate functions over a
range of values. You can create handles either for anonymous functions or for functions in program
files. The benefit of using anonymous functions is that you do not have to edit and maintain a file for a
function that requires only a brief definition.
For example, find the integral of the sqr function from 0 to 1 by passing the function handle to the
integral function:
q = integral(sqr,0,1);
You do not need to create a variable in the workspace to store an anonymous function. Instead, you
can create a temporary function handle within an expression, such as this call to the integral
function:
q = integral(@(x) x.^2,0,1);
20 Function Basics
20-20
Précédent

- 728/1450

Suivant