Function Handles

Function handles, as they are referred to in Matlab, are no more than pointers to functions. Given a function f, @f returns a pointer to that function, just like C.

Unlike C, to dereference the point, you must use the function feval which takes as its first argument a function pointer, and as subsequent arguments, arguments to be given to the function. For example, the following two are identical:

>> sin(3.2)

ans =

   -0.0584

>> feval( @sin, 3.2 )

ans =

   -0.0584

The function feval passes on the variable nargout as well:

>> [a b] = feval( @size, [1 2 3; 4 5 6] )

a =

     2

b =

     3

>> feval( @size, [1 2 3; 4 5 6] )        

ans =

     2     3

The following function takes as its input a function pointer and two end points. It evaluates the function at each of 100 points between a and b and returns the minimum and maximum. Save it to a file fnminmax.m:

function [m, n] = fnminmax( f, a, b )
% FNMINMAX    Minumum and maximum of a function by sampling

x = linspace( a, b, 100 );
y = ( f, x );

if nargout == 2
  m = min( y );
  n = max( y );
else
  m = [min(y), max(y)];
end

We can now call:

>> fnminmax( @sin, 2, 4 );

ans =

   -0.7568    0.9093

Now, if yhou wanted to find the sampled minimum and maximum of x^2 + 3*sin(x)*x + sin(x)^2, you would have to create a file f.m:

function y = f(x)
% F    Evaluate x^2 + 3*sin(x)*x + sin(x)^2

y = x.^2 + 3*sin(x).*x + sin(x).^2;

and then you could call:

>> fnminmax( @f, -2, 5 ) 

ans =

    0.0020   11.5357

>> x = linspace( -2, 5, 100 );
>> y = feval( @f, x );
>> plot( x, y )