Calling a Function Using Its Handle

Function handles can give you access to functions you might not be able to execute. For instance, with a handle you can call a function even if it is no longer on your MATLAB® path. You can also call a local function from outside of the file that defines that function.

Calling Syntax

The syntax for calling a function using a function handle is the same as that used when calling the function directly. For example, if you call function myFun like this:

[out1, out2, ...] = myFun(in1, in2, ...);

then you would call it using a handle in the same way, but using the handle name instead:

fHandle = @myFun;
[out1, out2, ...] = fHandle(in1, in2, ...);

There is one small difference. If the function being called takes no input arguments, then you must call the function with empty parentheses placed after the handle name. If you use only the handle name, MATLAB just identifies the name of the function:

% This identifies the handle.       % This invokes the function.

fHandle = @computer;                fHandle = @computer;
fHandle                             fHandle()
ans =                               ans =
   @computer                           PCWIN

Calling a Function with Multiple Outputs

The example below returns multiple values from a call to an anonymous function. Create anonymous function f that locates the nonzero elements of an array, and returns the row, column, and value of each element in variables row, col, and val:

f = @(X)find(X);

Call the function on matrix m using the function handle f. Because the function uses the MATLAB find function which returns up to three outputs, you can specify from 0 to 3 outputs in the call:

m = [3 2 0; -5 0 7; 0 0 1]
m =
     3     2     0
    -5     0     7
     0     0     1

[row col val] = f(m);

val =

Returning a Handle for Use Outside of a Function File

As stated previously, you can use function handles to call a function that may otherwise be hidden or out of scope. This example function getHandle returns a function handle fHandle to a caller that is outside of the file:

function fHandle = getHandle
fHandle = @subFun;

function res = subFun(t1, t2, varargin);

Call getHandle to obtain a function handle with which to invoke the local function. You can now call the local function as you would any function that is in scope:

f1 = getHandle;
result = f1(startTime, endTime, procedure);

Example — Using Function Handles in Optimization

Function handles can be particularly useful in optimization work. If you have the MathWorks® Optimization Toolbox™ installed, click on any of the links below to find information and examples on this topic:

Was this topic helpful?