%% Local minimum of a constrained function is not necessarily a local minimum of Lagrangian
% Example 3.2.5 Brinkhuis

syms x1 x2 a

f(x1,x2) = x1*x2
g(x1,x2) = x1 + x2 - 2

df = gradient(f,[x1 x2])
dg = gradient(g,[x1 x2])

%

sol = solve([df + a * dg == [0;0], g == [0;0]],[x1,x2,a])

x1s = sol.x1
x2s = sol.x2
as = sol.a

L = f + a*g

H = hessian(L,[x1,x2,a])

%

x1 = linspace(0,5,100);
x2 = linspace(0,5,100);

[X1,X2] = meshgrid(x1,x2);

F = X1.*X2;
G = X1 + X2 - 2;

mesh(X1,X2,G)
hold on
mesh(X1,X2,F)
hold off
xlabel('x_1')
ylabel('x_2')
zlabel('')

contour(X1,X2,G)
hold on
contour(X1,X2,F)
hold off
xlabel('x_1')
ylabel('x_2')