str2func - Construct function handle from function name string

Syntax

str2func('str')

Description

str2func('str') constructs a function handle fhandle for the function named in the string 'str'.

You can create a function handle using either the @function syntax or the str2func command. You can create an array of function handles from strings by creating the handles individually with str2func, and then storing these handles in a cell array.

Remarks

Nested functions are not accessible to str2func. To construct a function handle for a nested function, you must use the function handle constructor, @.

Examples

Example 1

To convert the string, 'sin', into a handle for that function, type

fh = str2func('sin')
fh = 
    @sin

Example 2

If you pass a function name string in a variable, the function that receives the variable can convert the function name to a function handle using str2func. The example below passes the variable, funcname, to function makeHandle, which then creates a function handle. Here is the function M-file:

function fh = makeHandle(funcname)
fh = str2func(funcname);

This is the code that calls makdHandle to construct the function handle:

makeHandle('sin')
ans = 
    @sin

Example 3

To call str2func on a cell array of strings, use the cellfun function. This returns a cell array of function handles:

fh_array = cellfun(@str2func, {'sin' 'cos' 'tan'}, ...
                   'UniformOutput', false);

fh_array{2}(5)
ans =
   0.2837

Example 4

In the following example, the myminbnd function expects to receive either a function handle or string in the first argument. If you pass a string, myminbnd constructs a function handle from it using str2func, and then uses that handle in a call to fminbnd:

function myminbnd(fhandle, lower, upper)
if ischar(fhandle)
   disp 'converting function string to function handle ...'
   fhandle = str2func(fhandle);
end
fminbnd(fhandle, lower, upper)

Whether you call myminbnd with a function handle or function name string, the function can handle the argument appropriately:

myminbnd('humps', 0.3, 1)
converting function string to function handle ...
ans =
    0.6370

See Also

function_handle, func2str, functions

  


 © 1984-2008- The MathWorks, Inc.    -   Site Help   -   Patents   -   Trademarks   -   Privacy Policy   -   Preventing Piracy   -   RSS