Department of Engineering

IT Services

Matlab function handles

Function Handles

Sometimes (for instance when using the ODE function ode23) you need to pass the name of a function as an argument to another function. The context of a function call affects which function is actually called - if you pass the function name "fun" to ode23, ode23 might not use the "fun.m" file you expect - for example, the ode23 function may have a sub-function or private function called "fun" (see Finding Matlab functions for details).

This is a situation where 'function handles' are useful. Rather than pass the name 'fun' you pass @fun. This ensures that the "fun" routine that would be called from your own code is the one that ode23 will call.

Once you create a function handle, it is not affected by subsequent changes to your MATLAB environment - changing the PATH or adding other functions with the same name as the original won't make a difference.

The feval command

The MATLAB feval command has to be used to run the function in a function handle. The syntax for using this command is

feval(fhandle, arg1, arg2, ..., argn)

The functions command

The functions command returns information about a function handle that might be useful for debugging. It returns in a structure the function name, type, filename, and all of the methods for the function that were in scope at the time the function handle was created.

The func2str command

If you need to perform string operations, such as string comparison or display, on a function handle, you can use func2str to obtain the function name in string format.

An example

If you put this in a file called foo.m and run foo, several features relating to function handles are demonstrated

function foo
% Call subfoo1 twice, first giving a function name, then a function handle
subfoo1('subfoo2')

fhandle=@subfoo2;
subfoo1(fhandle)

% A subfunction 
function subfoo1(funname)
disp('I am subfoo1.')
if isa(funname,'function_handle')
  disp('You gave me a function handle. Calling ''functions'' on it gives')
  functions(funname)
  str=func2str(funname);
else
  disp('You gave me a function name.')
  str=funname;
end

disp(['I am going to call ' str])
feval(funname)

% Another subfunction 
function subfoo2
disp('I am subfoo2')