Programming and Data Types | ![]() ![]() |
Function Handle Operations
MATLAB provides two functions that enable you to convert between a function handle and a function name string. It also provides functions for testing to see if a variable holds a function handle, and for comparing function handles.
Converting Function Handles to Function Names
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. To convert a sin
function handle to a string
Note
The func2str command does not operate on nonscalar function handles. Passing a nonscalar function handle to func2str results in an error.
|
Example - Displaying the Function Name in an Error Message
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) try ans = feval(func, data); disp('Answer is:'); ans catch sprintf('Error executing function ''%s''\n', func2str(func)) end
The first call to catcherr
, shown below, 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"
![]() | Types of Function Handles | Converting Function Names to Function Handles | ![]() |