%% make_fig_opt_curve.m
% Figure for: "Visualizing Optimization"
% Shows a concave function, its maximum (f'(x)=0), and a flat tangent at the top.

clear; close all; clc;

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

% --- Grid for plotting ---
x = linspace(-0.5, 4.5, 400);
y = f(x);

% --- Optimum point ---
x_star = 2;
y_star = f(x_star);

% --- Build figure ---
fig = figure('Color','w','Position',[100 100 720 480]);
plot(x, y, 'LineWidth', 2); hold on;

% Mark the maximum
plot(x_star, y_star, 'o', 'MarkerSize', 8, 'LineWidth', 1.5);

% Zero-slope tangent at the maximum (horizontal line)
% Small horizontal span around x_star for clarity
dx = 1.0;
plot([x_star-dx, x_star+dx], [y_star, y_star], '--', 'LineWidth', 1.2);

% Visual helpers: annotate slope=0 and curvature < 0
text(x_star+0.1, y_star+0.2, 'slope = 0', 'FontSize', 11);
text(0.2, f(0.2)-0.5, 'curvature < 0 (concave)', 'FontSize', 11);

% Axes labels and title
xlabel('x');
ylabel('f(x)');
title('Maximum where slope = 0 and curvature < 0');

% Light formatting
grid on; box on;
xlim([min(x) max(x)]);
ylim([min(y)-0.5, max(y)+0.6]);

mkdir('Figures')
% --- Save to files for Beamer ---
out_pdf = 'Figures/fig_opt_curve.pdf';
out_png = 'Figures/fig_opt_curve.png';
print(fig, out_pdf, '-dpdf', '-r300');
print(fig, out_png, '-dpng', '-r300');

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