%% make_fig_golden_vs_fminsearch.m
% Figure for: "Comparing Search Methods"
% Compares golden-section search and fminsearch on a simple concave function.
% Saves output to Figures/ folder.

clear; close all; clc;

% --- Ensure Figures folder exists ---
if ~exist('Figures', 'dir')
    mkdir('Figures');
end

% --- Define function ---
f = @(x) -(x-2).^2 + 4;   % concave quadratic, maximum at x=2

% --- Grid for plotting ---
x = linspace(0, 4, 200);
y = f(x);

% --- 1. Golden-section search ---
a = 0; b = 4; tol = 1e-4;
phi = (sqrt(5)-1)/2;

while (b - a) > tol
    x1 = b - phi*(b - a);
    x2 = a + phi*(b - a);
    if f(x1) < f(x2)
        a = x1;
    else
        b = x2;
    end
end
x_star_golden = (a + b)/2;
y_star_golden = f(x_star_golden);

% --- 2. fminsearch ---
[x_star_fmin, fval] = fminsearch(@(x) -f(x), 1); % start at x0=1
y_star_fmin = -fval;

% --- Plot comparison ---
fig = figure('Color','w','Position',[100 100 720 480]);
plot(x, y, 'k-', 'LineWidth', 2); hold on;
plot(x_star_golden, y_star_golden, 'ro', 'MarkerSize', 8, ...
     'DisplayName','Golden Section');
plot(x_star_fmin, y_star_fmin, 'bs', 'MarkerSize', 8, ...
     'DisplayName','fminsearch');

% Decorations
xlabel('x'); ylabel('f(x)');
title('Comparing Golden-Section Search and fminsearch');
legend('Function','Golden Section','fminsearch','Location','best');
grid on; box on;

% --- Annotate points ---
text(x_star_golden+0.1, y_star_golden-0.3, ...
    sprintf('Golden-section: x^* = %.2f', x_star_golden), 'Color','r');
text(x_star_fmin+0.1, y_star_fmin-0.6, ...
    sprintf('fminsearch: x^* = %.2f', x_star_fmin), 'Color','b');

% --- Save figure ---
out_pdf = fullfile('Figures','fig_golden_vs_fminsearch.pdf');
out_png = fullfile('Figures','fig_golden_vs_fminsearch.png');
print(fig, out_pdf, '-dpdf', '-r300');
print(fig, out_png, '-dpng', '-r300');

fprintf('Saved %s and %s\n', out_pdf, out_png);