function [ x, fval, output ] = fmintst;
% FMinTst
%
% This m-file is part of the material of the lectures on
%   Numerical Methods in Nonlinear Optimization
% at the Math Department of Halle University, Germany.
%
% Author :      Martin Arnold, martin.arnold@mathematik.uni-halle.de
% Version of :  Apr 11, 2006
%
% Test of Matlab's fminsearch (Rosenbrock function)
%
% Parameters:
%   x      (output) : optimal value computed by fminsearch
%   fval   (output) : optimal function value
%   output (output) : structure with statistical data of fminsearch
%
% Example:
%   [ x, fval, output ] = fmintst;

% -> problem and solver setup
fros = @(x) ( 100 * ( x(2) - x(1)^2 )^2 + ( 1 - x(1) )^2 );
x0 = [ -1.2, 1.0 ];

options = optimset (                            ...
                     'Display',     'off'       ...
                   , 'TolX',        1e-6        ...
                   , 'MaxFunEvals', 5000        ...
                   , 'MaxIter',     2000        ...
                   , 'OutputFcn',   @myoutput   ...
                   );

% -> minimization
[ x, fval, exitflag, output ] = fminsearch ( fros, x0, options );

% ----------------------------------------------------------------- %

function stop = myoutput ( x, optimValues, state );
% MyOutput
%
% Intermediate output of fminsearch
%
% Paramters:
%   x      (input)  : current iterate
%   optimValues (input) : statistical data of fminsearch
%   state  (input)  : status flag of fminsearch
%   stop   (output) : enforce emergency exit of fminsearch by stop=true

% -> prepare graphical output    
ActFontSize   = 14;
ActLineWidth  =  1;
ActMarkerSize =  8;

% -> continue iteration
stop = false;

% -> graphical output
switch state

    case 'init'

        x1min = -2.5;
        x1max =  2.0;
        x2min = -0.5;
        x2max =  3.5;

        nx = 201;
        x1 = linspace ( x1min, x1max, nx );
        x2 = linspace ( x2min, x2max, nx );
        [ X1, X2 ] = meshgrid ( x1, x2 ); 
        Fdat = 100 * ( X2 - X1.^2 ).^2 + ( 1 - X1 ).^2;

        contour ( X1, X2, Fdat, logspace ( 0, 3, 10 ) );
        xlabel ( 'x_1' );
        ylabel ( 'x_2' );

        set ( gca,               'FontSize', ActFontSize );
        set ( get(gca,'XLabel'), 'FontSize', ActFontSize );
        set ( get(gca,'YLabel'), 'FontSize', ActFontSize );
        for ach=get(gca,'Children')',
            if strcmp(get(ach,'Type'),'hggroup'),
                for ahgch=get(ach,'Children')',
                    if strcmp(get(ahgch,'Type'),'patch'),
                        set ( ach, 'LineWidth', ActLineWidth );
                    end;
                end;
            end;
        end;

    case 'iter'

        hold on;
        plot ( x(1), x(2), '+r', 'MarkerSize', ActMarkerSize );
        title ( sprintf('Step = %3i,    ||x-x*|| = %4.2e,   f(x) = %4.2e',optimValues.iteration,norm(x-[1 1]),optimValues.fval) );
        drawnow,
        hold off;


otherwise

end
