function fminunc_example ( )

%% FMINUNC_EXAMPLE shows an example of unconstrained minimization.
%
  global x1 x2  x3  x4 x5
%
%  Here are the data points.  We are seeking a value X which minimizes
%  the "energy", that is, the of the squares of the distances to each
%  data point.
%
  x1 = 1;
  x2 = 2;
  x3 = 10;
  x4 = 27;
  x5 = 20;
%
%  We believe the average is the correct answer.
%
  xave = ( x1 + x2 + x3 + x4 + x5 ) / 5;
  fxave = f ( xave );

  fprintf ( 1, '\n' );
  fprintf ( 1, '  The average XAVE = %f\n', xave );
  fprintf ( 1, '  and F(XAVE) = %f\n', fxave );
%
%  Now let's ask MATLAB to solve this problem using FMINUNC.
%  In that case, we give MATLAB a function F that evaluates the energy,
%  and an initial guess for the value of X.
%
  x0 = 14;
  x = fminunc ( @f, x0 );
  fx = f ( x );

  fprintf ( 1, '\n' );
  fprintf ( 1, '  The minimizer X  = %f\n', x )
  fprintf ( 1, '  and F(X)    = %f\n', fx );

  return
end
function value = f ( x )

%% F evaluates the function we want to minimize.
%
%  The GLOBAL statement allows the F(X) function to "see" the
%  values of these variables, which were set in FMINUNC_EXAMPLE.
%
  global x1 x2 x3 x4 x5

  value = ( x - x1 ).^2 ...
        + ( x - x2 ).^2 ...
        + ( x - x3 ).^2 ...
        + ( x - x4 ).^2 ...
        + ( x - x5 ).^2;

  return
end

