%% Chapter M-file for Optimization Chapter

fminsearch(@(x) x^4 - 4*x^2, 1)

%

format long
fzero(@(x) exp(x) - 3*x, 1)
fplot(@exp, [0, 2]); hold on
fplot(@(x) 3*x, [0, 2]); hold off

%

fzero(@(x) exp(x) - 3*x, 1.5)

%

format
syms x y real; fcontour(x^2 - y^2, [-3,3,-3,3], 'LevelList', -3:3)

%

fminsearch(@(x) x(1).^4 - 4*x(1).*x(2) + x(2).^2, [1, 1])

%

a = sqrt(2);
fcontour(x^4 - 4*x*y + y^2, [-3,3,-3,3], ...
    'LevelList', [-4:2:4, 10, 20], 'MeshDensity',120), hold on
plot([-a, 0, a], [-2*a, 0, 2*a], 'ok', 'MarkerFaceColor', 'k') 
gradf = -jacobian(x^4 - 4*x*y + y^2, [x, y])
[xx, yy] = meshgrid(-2:0.25:2, -3:0.5:3);
u = -4*xx.^3 + 4*yy; v = -2*yy + 4*xx;
ll=sqrt(u.^2+v.^2);
quiver(xx, yy, u./ll, v./ll, 0.3)
hold off, axis([-2.2 2.2 -3.1 3.1])% equal

%
% This runs only with the optimization toolbox.

fsolve(@(x) [exp(x(1))+exp(x(2))-6, x(1)+x(2)-2], [0, 1])