Documentation Center

  • Trial Software
  • Product Updates

Applications of Function Handles

Example of Passing a Function Handle

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 =

Using a function handle enables you to pass different functions for fminbnd to use in determining its final result.

Pass a Function to Another Function

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 integral on Varying Functions

Run the integral function on varying input functions:

a = 0;  b = 5;

integral(@log, a, b)
ans =

integral(@sin, a, b)
ans =

integral(@humps, a, b)
ans =

Example 2 — Run integral on Anonymous Functions

Run integral on a MATLAB built-in function or an anonymous function:

n = integral(@log, 0, 3);

n = integral(@(x)x.^2, 0, 3);

Change the parameters of the function you pass to integral with a simple modification of the anonymous function that is associated with the function handle input:

a = 3.7;
z = integral(@(x)x.^a, 0, 3);

Example 3 — Compare integral Results on Different Functions

Compare the integral of the cosine function over the interval [a, b]:

a = 0; b = 10;
int1 = integral(@cos,a,b)

int1 =

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 = integral(@(x)ppval(pp,x), a, b)

int2 =

Capture Data Values For Later Use By a Function

You can do more with a function handle than just create an association to a certain function. By using anonymous functions, you can also capture certain variables and their values from the function workspace and store them in the handle. These data values are stored in the handle at the time of its construction, and are contained within the handle for as long as it exists. Whenever you then 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 that Preserves Its Variables

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 an anonymous 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)

Because 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 handle to a nested function do not have to remain constant. The following function constructs and returns a function handle h to the anonymous 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;

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;
ans =
ans =

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;
ans = 

clear x
ans = 

Call Functions Outside of Their Normal Scope

By design, only functions within a program file are permitted to access local functions defined within that file. However, if, in this same file, you were to construct a function handle for one of the internal local functions, and then pass that handle to a variable that exists outside of the file, access to that local function would be essentially unlimited. By capturing the access to the local function in a function handle, and then making that handle available to functions external to the 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 local functions, 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.

Save the Handle in a MAT-File for Use in a Later MATLAB Session

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.

Was this topic helpful?