Create Function
Create Function Handle
You can create function handles to named and anonymous functions. You can store multiple function handles in an array, and save and load them, as you would any other variable.
What Is a Function Handle?
A function handle is a MATLAB® data type that stores an association to a function. Indirectly calling a function enables you to invoke the function regardless of where you call it from. Typical uses of function handles include:
Pass a function to another function (often called function functions). For example, passing a function to integration and optimization functions, such as integral and fzero.
Specify callback functions. For example, a callback that responds to a UI event or interacts with data acquisition hardware.
Construct handles to functions defined inline instead of stored in a program file (anonymous functions).
Call local functions from outside the main function.
You can see if a variable, h, is a function handle using isa(h,'function_handle').
Creating Function Handles
To create a handle for a function, precede the function name with an @ sign. For example, if you have a function called myfunction, create a handle named f as follows:
f = @myfunction;
You call a function using a handle the same way you call the function directly. For example, suppose that you have a function named computeSquare, defined as:
function y = computeSquare(x)
y = x.^2;
end
Create a handle and call the function to compute the square of four.
f = @computeSquare;
a = 4;
b = f(a)
b =
16
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 x2 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.
Overloading — If the function you specify overloads a function in a class that is not a fundamental MATLAB class, the function is not associated with the function handle at the time it is constructed. Instead, MATLAB considers the input arguments and determines which implementation to call at the time of evaluation.
Anonymous Functions
You can create handles to anonymous functions. An anonymous function is a one-line expression-based 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.
sqr = @(n) n.^2;
x = sqr(3)
x =
9
For more information, see Anonymous Functions.
Arrays of Function Handles
You can create an array of function handles by collecting them into a cell or structure array. For example, use a cell array:
C = {@sin, @cos, @tan};
C{2}(pi)
ans =
-1
Or use a structure array:
S.a = @sin; S.b = @cos; S.c = @tan;
S.a(pi/2)
ans =
1
Saving and Loading Function Handles
You can save and load function handles in MATLAB, as you would any other variable. In other words, use the save and load functions. If you save a function handle, MATLAB does not save the path information. If you load a function handle, and the function file no longer exists on the path, the handle is invalid. An invalid handle occurs if the file location or file name has changed since you created the handle. If a handle is invalid, MATLAB still performs the load successfully and without displaying a warning. However, when you invoke the handle, MATLAB issues an error.
Nested Functions
What Are Nested Functions?
A nested function is a function that is completely contained within a parent function. Any function in a program file can include a nested function.
For example, this function named parent contains a nested function named nestedfx:
function parent
disp('This is the parent function')
nestedfx
function nestedfx
disp('This is the nested function')
end
end
The primary difference between nested functions and other types of functions is that they can access and modify variables that are defined in their parent functions. As a result:
Nested functions can use variables that are not explicitly passed as input arguments.
In a parent function, you can create a handle to a nested function that contains the data necessary to run the nested function.
Requirements for Nested Functions
Typically, functions do not require an end statement. However, to nest any function in a program file, all functions in that file must use an end statement.
You cannot define a nested function inside any of the MATLAB® program control statements, such as if/elseif/else, switch/case, for, while, or try/catch.
You must call a nested function either directly by name (without using feval), or using a function handle that you created using the @ operator (and not str2func).
All of the variables in nested functions or the functions that contain them must be explicitly defined. That is, you cannot call a function or script that assigns values to variables unless those variables already exist in the function workspace. (For more information, see Variables in Nested and Anonymous Functions.)
Sharing Variables Between Parent and Nested Functions
In general, variables in one function workspace are not available to other functions. However, nested functions can access and modify variables in the workspaces of the functions that contain them.
This means that both a nested function and a function that contains it can modify the same variable without passing that variable as an argument. For example, in each of these functions, main1 and main2, both the main function and the nested function can access variable x:
function main1
x = 5;
nestfun1
function nestfun1
x = x + 1;
end
end
function main2
nestfun2
function nestfun2
x = 5;
end
x = x + 1;
end
When parent functions do not use a given variable, the variable remains local to the nested function. For example, in this function named main, the two nested functions have their own versions of x that cannot interact with each other:
function main
nestedfun1
nestedfun2
function nestedfun1
x = 1;
end
function nestedfun2
x = 2;
end
end
Functions that return output arguments have variables for the outputs in their workspace. However, parent functions only have variables for the output of nested functions if they explicitly request them. For example, this function parentfun does not have variable y in its workspace:
function parentfun
x = 5;
nestfun;
function y = nestfun
y = x + 1;
end
end
If you modify the code as follows, variable z is in the workspace of parentfun:
function parentfun
x = 5;
z = nestfun;
function y = nestfun
y = x + 1;
end
end
Using Handles to Store Function Parameters
Nested functions can use variables from three sources:
Input arguments
Variables defined within the nested function
Variables defined in a parent function, also called externally scoped variables
When you create a function handle for a nested function, that handle stores not only the name of the function, but also the values of externally scoped variables.
For example, create a function in a file named makeParabola.m. This function accepts several polynomial coefficients, and returns a handle to a nested function that calculates the value of that polynomial.
function p = makeParabola(a,b,c)
p = @parabola;
function y = parabola(x)
y = a*x.^2 + b*x + c;
end
end
The makeParabola function returns a handle to the parabola function that includes values for coefficients a, b, and c.
At the command line, call the makeParabola function with coefficient values of 1.3, .2, and 30. Use the returned function handle p to evaluate the polynomial at a particular point:
p = makeParabola(1.3,.2,30);
X = 25;
Y = p(X)
Y =
847.5000
Many MATLAB functions accept function handle inputs to evaluate functions over a range of values. For example, plot the parabolic equation from -25 to +25:
fplot(p,[-25,25])
You can create multiple handles to the parabola function that each use different polynomial coefficients:
firstp = makeParabola(0.8,1.6,32);
secondp = makeParabola(3,4,50);
range = [-25,25];
figure
hold on
fplot(firstp,range)
fplot(secondp,range,'r:')
hold off
Visibility of Nested Functions
Every function has a certain scope, that is, a set of other functions to which it is visible. A nested function is available:
From the level immediately above it. (In the following code, function A can call B or D, but not C or E.)
From a function nested at the same level within the same parent function. (Function B can call D, and D can call B.)
From a function at any lower level. (Function C can call B or D, but not E.)
function A(x, y) % Main function
B(x,y)
D(y)
function B(x,y) % Nested in A
C(x)
D(y)
function C(x) % Nested in B
D(x)
end
end
function D(x) % Nested in A
E(x)
function E(x) % Nested in D
disp(x)
end
end
end
The easiest way to extend the scope of a nested function is to create a function handle and return it as an output argument, as shown in Using Handles to Store Function Parameters. Only functions that can call a nested function can create a handle to it.
Anonymous Functions
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 inputs and return outputs, just as standard functions do. However, 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);
Variables in the Expression
Function handles can store not only an expression, but also variables that the expression requires for evaluation.
For example, create a function handle to an anonymous function that requires coefficients a, b, and c.
a = 1.3;
b = .2;
c = 30;
parabola = @(x) a*x.^2 + b*x + c;
Because a, b, and c are available at the time you create parabola, the function handle includes those values. The values persist within the function handle even if you clear the variables:
clear a b c
x = 1;
y = parabola(x)
y =
31.5000
To supply different values for the coefficients, you must create a new function handle:
a = -3.9;
b = 52;
c = 0;
parabola = @(x) a*x.^2 + b*x + c;
x = 1;
y = parabola(1)
y =
48.1000
You can save function handles and their associated values in a MAT-file and load them in a subsequent MATLAB session using the save and load functions, such as
save myfile.mat parabola
Use only explicit variables when constructing anonymous functions. If an anonymous function accesses any variable or nested function that is not explicitly referenced in the argument list or body, MATLAB throws an error when you invoke the function. Implicit variables and function calls are often encountered in the functions such as eval, evalin, assignin, and load. Avoid using these functions in the body of anonymous functions.
Multiple Anonymous Functions
The expression in an anonymous function can include another anonymous function. This is useful for passing different parameters to a function that you are evaluating over a range of values. For example, you can solve the equation
for varying values of c by combining two anonymous functions:
g = @(c) (integral(@(x) (x.^2 + c*x + 1),0,1));
Here is how to derive this statement:
Write the integrand as an anonymous function,
@(x) (x.^2 + c*x + 1)
Evaluate the function from zero to one by passing the function handle to integral,
integral(@(x) (x.^2 + c*x + 1),0,1)
Supply the value for c by constructing an anonymous function for the entire equation,
g = @(c) (integral(@(x) (x.^2 + c*x + 1),0,1));
The final function allows you to solve the equation for any value of c. For example:
g(2)
ans =
2.3333
Functions with No Inputs
If your function does not require any inputs, use empty parentheses when you define and call the anonymous function. For example:
t = @() datestr(now);
d = t()
d =
26-Jan-2012 15:11:47
Omitting the parentheses in the assignment statement creates another function handle, and does not execute the function:
d = t
d =
@() datestr(now)
Functions with Multiple Inputs or Outputs
Open This Example
Anonymous functions require that you explicitly specify the input arguments as you would for a standard function, separating multiple inputs with commas. For example, this function accepts two inputs, x and y:
myfunction = @(x,y) (x^2 + y^2 + x*y);
x = 1;
y = 10;
z = myfunction(x,y)
z =
111
However, you do not explicitly define output arguments when you create an anonymous function. If the expression in the function returns multiple outputs, then you can request them when you call the function. Enclose multiple output variables in square brackets.
For example, the ndgrid function can return as many outputs as the number of input vectors. This anonymous function that calls ndgrid can also return multiple outputs:
c = 10;
mygrid = @(x,y) ndgrid((-x:x/c:x),(-y:y/c:y));
[x,y] = mygrid(pi,2*pi);
You can use the output from mygrid to create a mesh or surface plot:
z = sin(x) + cos(y);
mesh(x,y,z)
Arrays of Anonymous Functions
Although most MATLAB fundamental data types support multidimensional arrays, function handles must be scalars (single elements). However, you can store multiple function handles using a cell array or structure array. The most common approach is to use a cell array, such as
f = {@(x)x.^2;
@(y)y+10;
@(x,y)x.^2+y+10};
When you create the cell array, keep in mind that MATLAB interprets spaces as column separators. Either omit spaces from expressions, as shown in the previous code, or enclose expressions in parentheses, such as
f = {@(x) (x.^2);
@(y) (y + 10);
@(x,y) (x.^2 + y + 10)};
Access the contents of a cell using curly braces. For example, f{1} returns the first function handle. To execute the function, pass input values in parentheses after the curly braces:
x = 1;
y = 10;
f{1}(x)
f{2}(y)
f{3}(x,y)
ans =
1
ans =
20
ans =
21