Construct function name string from function handle




func2str(fhandle) constructs a string s that holds the name of the function to which the function handle fhandle belongs.

When you need to perform a string operation, such as compare or display, on a function handle, you can use func2str to construct a string bearing the function name.

The func2str command does not operate on nonscalar function handles. Passing a nonscalar function handle to func2str results in an error.


Example 1

Convert a sin function handle to a string:

fhandle = @sin;

ans =

Example 2

The catcherr function shown here accepts function handle and data arguments and attempts to evaluate the function through its handle. If the function fails to execute, catcherr uses sprintf to display an error message giving the name of the failing function. The function name must be a string for sprintf to display it. The code derives the function name from the function handle using func2str:

function catcherr(func, data)
    ans = func(data);
    disp('Answer is:');
    disp(sprintf('Error executing function ''%s''\n', ... 

The first call to catcherr passes a handle to the round function and a valid data argument. This call succeeds and returns the expected answer. The second call passes the same function handle and an improper data type (a MATLAB® structure). This time, round fails, causing catcherr to display an error message that includes the failing function name:

catcherr(@round, 5.432)
ans =
Answer is 5

xstruct.value = 5.432;
catcherr(@round, xstruct)
Error executing function "round"

More About

expand all


Any variables and their values originally stored in a function handle when it was created are lost if you convert the function handle to a string and back again using the func2str and str2func functions.

Was this topic helpful?