| Programming and Data Types | ![]() |
Converting Function Names to Function Handles
Using the str2func function, you can construct a function handle from a string containing the name of a MATLAB function. To convert the string, 'sin', into a handle for that function
fh = str2func('sin')
fh =
@sin
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.
function fh = makeHandle(funcname)
fh = str2func(funcname);
% -- end of makeHandle.m file --
makeHandle('sin')
ans =
@sin
You can also perform the str2func operation on a cell array of function name strings. In this case, str2func returns an array of function handles.
fh_array = str2func({'sin' 'cos' 'tan'})
fh_array =
@sin @cos @tan
Example - More Flexible Parameter Checking
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, it is able to handle the argument appropriately.
myminbnd('humps', 0.3, 1)
converting function string to function handle ...
ans =
0.6370
| Function Handle Operations | Testing for Data Type | ![]() |