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.

1 function Estimates = fitcurvedemo 2 % FITCURVEDEMO 3 % Fit curve to data where user chooses equation to fit. 4 5 % Define function and starting point of fitting routine. 6 fun = @expfun; 7 Starting = rand(1, 2); 8 9 % First, we create the data. 10 t = 0:.1:10; t=t(:); % to make 't' a column vector 11 Data = 40 * exp(-.5 * t) + randn(size(t)); 12 m = [t Data]; 13 14 % Now, we can call FMINSEARCH: 15 options = optimset('fminsearch'); % Use FMINSEARCH defaults 16 Estimates = fminsearch(fun, Starting, options, t, Data); 17 18 % To check the fit 19 plot(t, Data, '*') 20 hold on 21 plot(t, Estimates(1) * exp(-Estimates(2) * t), 'r') 22 xlabel('t') 23 ylabel('f(t)') 24 title(['Fitting to function ', func2str(fun)]); 25 legend('data', ['fit using ', func2str(fun)]) 26 hold off 27 28 % ---------------------------------------------------------- 29 30 function sse = expfun(params, t, Data) 31 % Accepts curve parameters as inputs, and outputs fitting the 32 % error for the equation y = A * exp(-lambda * t); 33 A = params(1); 34 lambda = params(2); 35 36 Fitted_Curve = A .* exp(-lambda * t); 37 Error_Vector = Fitted_Curve - Data; 38 39 % When curve fitting, a typical quantity to minimize is the sum 40 % of squares error 41 sse = sum(Error_Vector .^ 2);

Evaluating a Function Through Its Handle | Displaying Function Handle Information |