Using MATLAB (779505), страница 90
Текст из файла (страница 90)
This isshown in f.methods.cell.f = functions(@deblank)f =function: 'deblank'type: 'overloaded'file: 'matlabroot\toolbox\matlab\strfun\deblank.m'21-1521Function Handlesmethods: [1x1 struct]f.methodsans =cell: 'matlabroot\toolbox\matlab\strfun\@cell\deblank.m'If you evaluate the @deblank function handle with a cell argument, MATLABcalls the deblank method in the @cell directory. But, for any other argumenttypes, MATLAB calls the default M-file shown in the file field.Function MethodsThe methods field exists only for functions of type, overloaded.
This field is aseparate MATLAB structure that identifies all overloaded methods that arebound to the function handle.The structure contains one field for each method of the function handle. Thefield names are the classes that overload the function. Each field value is acharacter array holding the path and name of the source file that defines themethod.For example, a function handle for the display function may be bound to theM-files shown below.
The functions command returns a methods structurehaving a field for each class overloading the function: polynom, inline, serial,and avifile. For each class, it shows the path and name of the method sourcefile.f = functions(@display);f.methodsans =polynom: '\home\user4\@polynom\display.m'inline: 'matlabroot\toolbox\matlab\funfun\@inline\display.m'serial: 'matlabroot\toolbox\matlab\iofun\@serial\display.m'avifile: 'matlabroot\toolbox\matlab\iofun\@avifile\display.m'Note The set of methods returned by functions is determined at the time afunction handle is created. This depends on the state of the MATLAB pathand also which functions are in scope when the handle is created.21-16Displaying Function Handle InformationTypes of Function HandlesThe information returned by functions varies depending on the type offunction represented by the function handle.
This section explains what isreturned for each type of function. The categories of function handles are:• Simple function handles• Overloaded function handles• Constructor function handles• Subfunction handles• Private function handlesSimple Function HandlesThese are handles to nonoverloaded MATLAB built-in or M-file functions. Anyfunction handles for which the function type has not yet been determined (e.g.,Java methods, nonexistent functions), also fall into this category.Structure fields:function: function nametype: 'simple'file: 'MATLAB built-in function'path and name of the default M-file(there is no methods field)for built-insfor nonbuilt-insExamples:Using functions on a function handle to a built-in functionfunctions(@ones)ans =function: 'ones'type: 'simple'file: 'MATLAB built-in function'Using functions on a function handle to a nonbuilt-in functionfunctions(@fzero)ans =function: 'fzero'type: 'simple'file: 'matlabroot\toolbox\matlab\funfun\fzero.m'21-1721Function HandlesOverloaded Function HandlesThese are handles to MATLAB built-in or M-file functions that are overloadedimplementations for different classes.Structure fields:function: function nametype: 'overloaded'file: 'MATLAB built-in function'path and name of the default M-filemethods: [1x1 struct]for built-insfor nonbuilt-insExamples:Using functions on a function handle to a built-in functionfunctions(@display)ans =function: 'display'type: 'overloaded'file: 'MATLAB built-in function'methods: [1x1 struct]Using functions on a function handle to a nonbuilt-in functionfunctions(@deblank)ans =function: 'deblank'type: 'overloaded'file: 'matlabroot\toolbox\matlab\strfun\deblank.m'methods: [1x1 struct]Constructor Function HandlesThese are handles to functions that construct objects of MATLAB classes.Structure fields:function:type:file:(there is21-18function name'constructor'path and name of the constructor M-fileno methods field)Displaying Function Handle InformationExample:Using functions on a function handle to a constructor functionfunctions(@inline)ans =function: 'inline'type: 'constructor'file: 'matlabroot\toolbox\matlab\funfun\@inline\inline.m'Subfunction HandlesThese are handles to MATLAB subfunctions, which are functions definedwithin an M-file that are only visible to the primary function of that M-file.When you use functions on a subfunction handle, the file field of the returnstructure contains the path and name of the M-file in which the subfunction isdefined.Structure fields:function:type:file:(there isfunction name'subfunction'path and name of the M-file defining the subfunctionno methods field)Example:The getLocalHandle M-file, shown below, defines a primary function and asubfunction, named subfunc.% -- File GETLOCALHANDLE.M -function subhandle = getLocalHandle()subhandle = @subfunc;% return handle to subfunctionfunction subfunc()disp 'running subfunc'A call to getLocalHandle returns a function handle to the subfunction.
Whenyou pass that handle to functions, it returns the following information.fhandle = getLocalHandle;functions(fhandle)ans =function: 'subfunc'21-1921Function Handlestype: 'subfunction'file: '\home\user4\getLocalHandle.m'Private Function HandlesThese are handles to MATLAB private functions, which are functions definedin a private subdirectory that are only visible to functions in the parentdirectory. When you use functions on a private function handle, the file fieldof the return structure contains the path and name of the M-file in the privatesubdirectory that defines the function.Structure fields:function:type:file:(there isfunction name'private'path and name of the M-file in \privateno methods field)Example:The getPrivateHandle function, shown below, returns a handle to a privatefunction named privatefunc.% -- File GETPRIVATEHANDLE.M -function privhandle = getPrivateHandle()privhandle = @privatefunc;% return handle to private functionThe following function, privatefunc, resides in the \private subdirectory.% -- File \PRIVATE\PRIVATEFUNC.M -function privatefunc()disp 'running privatefunc'A call to getPrivateHandle returns a handle to the function, privatefunc,defined in \private.
When you pass that handle to functions, it returns thefollowing information.fhandle = getPrivateHandle;functions(fhandle)ans =function: 'privatefunc'type: 'private'file: '\home\user4\private\privatefunc.m'21-20Function Handle OperationsFunction Handle OperationsMATLAB provides two functions that enable you to convert between a functionhandle and a function name string. It also provides functions for testing to seeif a variable holds a function handle, and for comparing function handles.Converting Function Handles to Function NamesIf 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 instring format.
To convert a sin function handle to a stringfhandle = @sin;func2str(fhandle)ans =sinNote The func2str command does not operate on nonscalar functionhandles. Passing a nonscalar function handle to func2str results in an error.Example - Displaying the Function Name in an Error MessageThe catcherr function shown here accepts function handle and dataarguments and attempts to evaluate the function through its handle. If thefunction fails to execute, catcherr uses sprintf to display an error messagegiving the name of the failing function. The function name must be a string forsprintf to display it. The code derives the function name from the functionhandle using func2str.function catcherr(func, data)tryans = feval(func, data);disp('Answer is:');anscatchsprintf('Error executing function ''%s''\n', func2str(func))end21-2121Function HandlesThe first call to catcherr, shown below, passes a handle to the round functionand a valid data argument.
This call succeeds and returns the expectedanswer. The second call passes the same function handle and an improper datatype (a MATLAB structure). This time, round fails, causing catcherr to displayan error message that includes the failing function name.catcherr(@round, 5.432)ans =Answer is 5xstruct.value = 5.432;catcherr(@round, xstruct)Error executing function "round"Converting Function Names to Function HandlesUsing the str2func function, you can construct a function handle from a stringcontaining the name of a MATLAB function.
To convert the string, ’sin’, into ahandle for that functionfh = str2func('sin')fh =@sinIf you pass a function name string in a variable, the function that receives thevariable 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 =@sinYou can also perform the str2func operation on a cell array of function namestrings. In this case, str2func returns an array of function handles.fh_array = str2func({'sin' 'cos' 'tan'})fh_array =@sin@cos@tan21-22Function Handle OperationsExample - More Flexible Parameter CheckingIn the following example, the myminbnd function expects to receive either afunction handle or string in the first argument.
If you pass a string, myminbndconstructs a function handle from it using str2func, and then uses that handlein a call to fminbnd.function myminbnd(fhandle, lower, upper)if ischar(fhandle)disp 'converting function string to function handle ...'fhandle = str2func(fhandle);endfminbnd(fhandle, lower, upper)Whether you call myminbnd with a function handle or function name string, itis able to handle the argument appropriately.myminbnd('humps', 0.3, 1)converting function string to function handle ...ans =0.6370Testing for Data TypeThe isa function identifies the data type or class of a MATLAB variable orobject. You can see if a variable holds a function handle by using isa with thefunction_handle tag. The following function tests an argument passed in tosee if it is a function handle before attempting to evaluate it.function evaluate_handle(arg1, arg2)if isa(arg1, 'function_handle')feval(arg1, arg2);elsedisp 'You need to pass a function handle';endTesting for EqualityYou can use the isequal function to compare two function handles for equality.For example, you want to execute one particular method you have written foran overloaded function.















