% Demonstration of fmincon and Karush-Kuhn-Tucker conditions
% ME 256; January 2017; IISc, Bengaluru; G. K. Ananthasuresh
%
% Objective function: f = x^2 + y^2 - 2x
% Equality constraint: h = y - 2*x^2 + 5*x
% Inequality constraint: g = -3*x - y + 6
%
% House-keeping commands
clear all
clc
% Plot the surface and contour of f
figure(1)
clf
[X,Y] = meshgrid(-2:.2:5, -4:.4:4);
Z = X.^2 + Y.^2 - 2*X;
surfc(X,Y,Z);
hold on
xlabel('x');
ylabel('y');
zlabel('f = x^2 + y^2 - 2x');
% Plot the contours of f and curves of h and g
figure(2)
clf
% f
[C, hndl] = contour(X,Y,Z,[-0.5:0.5:3 4:1:12]);
clabel(C);
axis equal
axis square
hold on
xlabel('x');
ylabel('y');
% h
hx = linspace(-1,3.5,100);
hy = 2*hx.^2 - 5*hx;
plot(hx,hy,'-k','LineWidth',2);
gx = linspace(-1,3.5,10);
gy = -3*gx + 6;
plot(gx,gy,'--g','LineWidth',2);
% Call fmincon
x0 = [1; -3];
[x,FVAL,EXITFLAG,OUTPUT,LAMBDA,GRAD,HESSIAN] = fmincon('obj',x0,[-3 -1],[-6],[],[],[],[],'g1');
lambda = LAMBDA.eqnonlin;
% Plot the optimum point on the contour map
plot(x(1),x(2),'r.','MarkerSize',20);