Programming and Data Types    

Examples of Function Handle Evaluation

This section provides two examples of how function handles are used and evaluated.

Example 1 - A Simple Function Handle

The following example defines a function, called plot_fhandle, that receives a function handle and data, and then performs an evaluation of the function handle on that data.

When you call plot_fhandle with a handle to the sin function and the argument shown below, the resulting evaluation produces the following plot.

Example 2 - Function Handles and Subfunctions

The M-file in this example defines a primary function, fitcurvedemo, and a subfunction called expfun. The subfunction, by definition, is visible only within the scope of its own M-file. This, of course, means that it is available for use only by other functions within that M-file.

The author of this code would like to use expfun outside the confines of this one M-file. This example creates a function handle to the expfun subfunction, storing access information for the subfunction so that it can be called from anywhere in the MATLAB environment. The function handle is passed to fminsearch, which successfully evaluates the subfunction outside of its usual scope.

The code shown below defines fitcurvedemo and subfunction, expfun. Line 6 constructs a function handle to expfun and assigns it to the variable, fun. In line 16, a call to fminsearch passes the function handle outside the normal scope of a subfunction. The fminsearch function uses feval to evaluate the subfunction through its handle.


  Evaluating a Function Through Its Handle Displaying Function Handle Information