Using MATLAB (779505), страница 89
Текст из файла (страница 89)
Included in this information is the repmat.msource file path, toolbox\matlab\elmat\repmat.m.Once you create a function handle, it is not affected by certain changes youmight make in your MATLAB environment. For example, if you construct ahandle to the repmat function and, later, write additional repmat.m methods tooverload the function, the handle still sees only the original function. Also, ifyou remove the path to repmat.m from the search path, MATLAB is still ableto locate and evaluate the function using the handle that you created prior tothe path change.21-521Function HandlesSince repmat is not an overloaded function in this case, evaluation of thefunction through its handle is fairly simple.
You call feval on the functionhandle, also passing any arguments the function should act upon. MATLABexecutes the one function whose access information is stored in the handle.21-6Constructing a Function HandleConstructing a Function HandleConstruct a function handle in MATLAB using the at sign, @, before thefunction name. The following example creates a function handle for the humpsfunction and assigns it to the variable fhandle.fhandle = @humps;Pass the handle to another function in the same way you would pass anyargument. This example passes the function handle just created to fminbnd,which then minimizes over the interval [0.3, 1].x = fminbnd(fhandle, 0.3, 1)x =0.6370The fminbnd function evaluates the @humps function handle using feval.
Asmall portion of the fminbnd M-file is shown below. In line 1, the funfcn inputparameter receives the function handle, @humps, that was passed in. The fevalstatement, in line 113, evaluates the handle.1113function [xf,fval,exitflag,output] = ...fminbnd(funfcn,ax,bx,options,varargin)...fx = feval(funfcn,x,varargin{:});Note When creating a function handle, you may only use the function nameafter the @ sign. This must not include any path information. The followingsyntax is invalid: fhandle = @\home\user4\humps.Maximum Length of a Function NameFunction names used in handles are unique up to 31 characters. If the functionname exceeds that length, MATLAB truncates the latter part of the name.fhandle = @function_name_that_exceeds_thirty_one_charactersfhandle =@function_name_that_exceeds_thir21-721Function HandlesFor function handles created for Java constructors, the length of any segmentof the package name or class name must not exceed 31 characters.
(The termsegment refers to any portion of the name that lies before, between, or after adot. For example, there are three segments in java.lang.String.) There is nolimit to the overall length of the string specifying the package and class.The following statement is valid, even though the length of the overall packageand class specifier exceeds 31 characters.fhandle = @java.awt.datatransfer.StringSelection21-8Evaluating a Function Through Its HandleEvaluating a Function Through Its HandleExecute the target function of a function handle using the MATLAB fevalcommand.
The syntax for using this command with a function handle isfeval(fhandle, arg1, arg2, ..., argn)This acts similarly to a direct call to the function represented by fhandle,passing arguments arg1 through argn. The principal differences are:• A function handle can be evaluated from within any function that you passit to.• The code source that MATLAB selects for evaluation depends upon whichoverloaded methods of the function were on the MATLAB path and in scopeat the time the handle was constructed.
(Argument types also affect methodselection.) Path and scope are not considered at the time of evaluation.• MATLAB does the work of initial function lookup at the time the functionhandle is constructed. This does not need to be done each time MATLABevaluates the handle.Note The feval command does not operate on nonscalar function handles.Passing a nonscalar function handle to feval results in an error.Function Evaluation and OverloadingTo understand the relationship between function handles and overloading, it ishelpful to review, briefly, the nature of MATLAB function calls. Because ofoverloading, it is useful to think of a single MATLAB function as comprising anumber of code sources (for example, built-in code, M-files). When you call aMATLAB function without feval, the choice of which source is called dependsupon two factors:• The methods that are visible on the path at the time of the call• The classes of the arguments to the functionMATLAB evaluates function handles in a similar manner.
In most cases, afunction handle represents a collection of methods that overload the function.21-921Function HandlesWhen you evaluate a function handle using feval, the choice of the particularmethod called depends on:• The methods that were visible on the path at the time the handle wasconstructed• The classes of the arguments passed with the handle to the feval commandExamples of Function Handle EvaluationThis section provides two examples of how function handles are used andevaluated.Example 1 - A Simple Function HandleThe following example defines a function, called plot_fhandle, that receives afunction handle and data, and then performs an evaluation of the functionhandle on that data.function x = plot_fhandle(fhandle, data)plot(data, feval(fhandle, data))When you call plot_fhandle with a handle to the sin function and theargument shown below, the resulting evaluation produces the following plot.plot_fhandle(@sin, -pi:0.01:pi)21-10Evaluating a Function Through Its HandleExample 2 - Function Handles and SubfunctionsThe M-file in this example defines a primary function, fitcurvedemo, and asubfunction called expfun.
The subfunction, by definition, is visible only withinthe scope of its own M-file. This, of course, means that it is available for useonly by other functions within that M-file.The author of this code would like to use expfun outside the confines of this oneM-file. This example creates a function handle to the expfun subfunction,storing access information for the subfunction so that it can be called fromanywhere in the MATLAB environment. The function handle is passed tofminsearch, which successfully evaluates the subfunction outside of its usualscope.The code shown below defines fitcurvedemo and subfunction, expfun.
Line 6constructs a function handle to expfun and assigns it to the variable, fun. Inline 16, a call to fminsearch passes the function handle outside the normalscope of a subfunction. The fminsearch function uses feval to evaluate thesubfunction through its handle.1function Estimates = fitcurvedemo2% FITCURVEDEMO3% Fit curve to data where user chooses equation to fit.45% Define function and starting point of fitting routine.6fun = @expfun;7Starting = rand(1, 2);89% First, we create the data.10 t = 0:.1:10;t=t(:);% to make 't' a column vector11 Data = 40 * exp(-.5 * t) + randn(size(t));12 m = [t Data];1314 % Now, we can call FMINSEARCH:15 options = optimset('fminsearch'); % Use FMINSEARCH defaults16 Estimates = fminsearch(fun, Starting, options, t, Data);1718 % To check the fit19 plot(t, Data, '*')20 hold on21 plot(t, Estimates(1) * exp(-Estimates(2) * t), 'r')22 xlabel('t')21-1121Function Handles23 ylabel('f(t)')24 title(['Fitting to function ', func2str(fun)]);25 legend('data', ['fit using ', func2str(fun)])26 hold off2728 % ---------------------------------------------------------2930 function sse = expfun(params, t, Data)31 % Accepts curve parameters as inputs, and outputs fitting the32 % error for the equation y = A * exp(-lambda * t);33 A = params(1);34 lambda = params(2);3536 Fitted_Curve = A .* exp(-lambda * t);37 Error_Vector = Fitted_Curve - Data;3839 % When curve fitting, a typical quantity to minimize is the sum40 % of squares error41 sse = sum(Error_Vector .^ 2);21-12Displaying Function Handle InformationDisplaying Function Handle InformationThe functions command returns information about a function handle thatmight be useful for debugging.
Calling functions on a function handle returnsthe function name, type, filename, and all of the methods for the function thatwere in scope at the time the function handle was created.The information returned from functions is in the form of a MATLABstructure. The fields of this structure are listed in the following table.Field NameField DescriptionfunctionFunction name.typeFunction type. See the table in section, “Function Type”on page 21-14.fileThe file to be executed when the function handle isevaluated with a nonoverloaded data type.
For built-infunctions, it reads 'MATLAB built-in function.'methodsAll overloaded methods of the function that are bound tothe function handle. This field exists only for functionsof type, overloaded.For example, to obtain information on a function handle for the displayfunction,f = functions(@display)ans =function: 'display'type: 'overloaded'file: 'MATLAB built-in function'methods: [1x1 struct]Individual fields of the structure are accessible using the dot selection notationused to access MATLAB structure fields.f.typeans ='overloaded'21-1321Function HandlesThe methods field is a separate structure containing one fieldname for eachclass that overloads the function. The value of each field is the path and nameof the file that defines the function.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'f.methods.polynomans =polynom: '\home\user4\@polynom\display.m'Note The functions command does not operate on nonscalar functionhandles.
Passing a nonscalar function handle to functions results in an error.Fields Returned by the Functions CommandThe functions command returns a MATLAB structure with the fieldsfunction, type, file, and, for overloaded functions, methods. This sectiondescribes each of those fields.Function NameThe function field is a character array that holds the name of the functioncorresponding to the function handle.Function TypeThe type field is a character array that holds one of five possible strings listedin the following table.21-14Displaying Function Handle InformationFunction TypeType DescriptionsimpleNonoverloaded MATLAB built-in or M-file, or anyfunction for which the type cannot be determined untilit is evaluatedsubfunctionMATLAB subfunctionprivateMATLAB private functionconstructorConstructor to a MATLAB classoverloadedOverloaded built-in, M-file function, or constructorThe contents of the next two fields, file and methods, depend upon thefunction type.Function FileThe file field is a character array that holds one of the following:• The string, ’MATLAB built-in function’, for built-in functions• The path and name of the file that implements the default function, fornonbuilt-in functionsThe default function is the one function implementation that is not specializedto operate on any particular data type.
Unless the arguments in the functioncall specify a class that has a specialized version of the function defined, it isthe default function that gets called.The example below operates on a function handle for the deblank function. Thefunction has a default implementation in the strfun directory. This is shownin f.file. It also has an overloaded method in the @cell directory.
















