% SQP Demo using fmincon.

%************ OPTIONS ***************

% Choose the SQP option:
options = optimset('LargeScale', 'off');

% Allow for a user-defined gradient:
options = optimset(options, 'GradObj', 'on');

% Set the max number of function evaluations.
% Note: This includes function evaluations used
% for finite-differencing and line search steps.
options = optimset(options, 'MaxFunEvals', 78);

% Turn on the display of iterative output:
options = optimset(options, 'Display', 'iter'); 

% Turn on the display of diagnostic information:
options = optimset(options, 'Diagnostics', 'on'); 

%********* END OPTIONS **********

% Plot the objective (Rosenbrock's function):
rbplot
title('Function Evaluations: Major & Minor Iterations')

% Plot the feasible region:
x = -2:0.05:2;
y = -1:0.05:3;
[X, Y] = meshgrid(x, y);
Z = X.^2 + Y.^2 - 2;
[C, h] = contourf(X, Y, Z, [0, 0], 'b');
set(h, 'LineWidth', 2)
set(gca, 'clim', rblim)

% Set the initial value and run the optimization:
x0 = [-1.9, 2];
global iterations
iterations = x0;
[x, fval, exitflag, output, lambda, grad, hessian] = ...
fmincon(@rbfun, x0, [], [], [], [], [], [], @rbconfun, options)

% Plot the iterations.
% Note: This includes function evaluations used
% for finite-differencing and line search steps.
plot(iterations(:,1), iterations(:,2), ...
      'ko', 'MarkerSize', 3, 'MarkerFaceColor', 'r')
for i = 1:length(iterations)
plot3(iterations(i,1), iterations(i,2), ...
        rbfun([iterations(i,1), iterations(i,2)]) + 2000, ...
        'ko', 'MarkerSize', 3, 'MarkerFaceColor', 'w')
end

clear i rblim iterations x y X Y Z C h