clear; close; clc;

% Define function
f = @(x) -(x-2).^2 + 4;

% Define grid of points
x = linspace(0, 4, 100);

% Evaluate and find maximum
y = f(x);
[~, idx] = max(y);

% Display result
x_star = x(idx)
y_star = y(idx)

%%
clear; close; clc;

f = @(x) -(x-2).^2 + 4;
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 = (a + b)/2
f_star = f(x_star)

%%
clear; close; clc;

f = @(x) -(x-2).^2 + 4;
x0 = 1;                      % starting guess
[x_star, fval] = fminsearch(@(x) -f(x), x0);
fprintf('Optimum: x = %.4f, f(x) = %.4f\n', x_star, -fval);

%%
clear; close; clc;
% Parameters
alpha = 0.3; w = 1; r = 0.02; a0 = 0.05; T = 0.1;

% Objective (negative utility for minimization)
U = @(l) -((w*l + (1+r)*a0 - T).^alpha .* (1 - l).^(1 - alpha));

% Bounds and initial guess
l0 = 0.5; lb = 0; ub = 1;

% Solve
l_star = fmincon(U, l0, [], [], [], [], lb, ub);

fprintf('Optimal labor supply: %.4f\n', l_star);

fig = figure('Color','w','Position',[100 100 720 480]);
l = linspace(0,1,100);
U_vals = -U(l);              % convert back to positive utility
plot(l, U_vals, 'LineWidth',1.5)
xlabel('Labor supply l'); ylabel('Utility');
title('Utility as a function of labor supply');
grid on
out_png = fullfile('Figures','fig_fmincon_utility.png');
print(fig, out_png, '-dpng', '-r300');

eps_c = 1e-10;                             % to avoid c=0
c = w*l + (1+r)*a0 - T;                    % >= 0 on this grid
U_vals = max(c,eps_c).^alpha .* (1 - l).^(1 - alpha);

if ~exist('Figures','dir'), mkdir('Figures'); end
fig = figure('Color','w','Position',[100 100 720 480]);
plot(l, U_vals, 'LineWidth',1.8); hold on;
xlabel('Labor supply l'); ylabel('Utility');
title('Utility as a function of labor supply');
grid on; box on;
print(fig, fullfile('Figures','fig_fmincon_utility_b.pdf'), '-dpdf', '-r300');
print(fig, fullfile('Figures','fig_fmincon_utility_b.png'), '-dpng', '-r300');

%%
clear; close; clc;

target = 0.3;

% Objective: difference between model and target
loss = @(alpha) (solve_lstar(alpha) - target)^2;

% Initial guess
alpha0 = 0.4;

% Minimize loss
alpha_star = fminsearch(loss, alpha0);

fprintf('Optimal alpha = %.4f\n', alpha_star);


alpha = linspace(0.1,0.9,50);
for i = 1:length(alpha)
  L(i) = loss(alpha(i));
end
fig = figure('Color','w','Position',[100 100 720 480]);
plot(alpha, L, 'LineWidth', 1.5)
xlabel('\alpha'); ylabel('Loss');
title('Calibration Objective Function');
grid on
print(fig, fullfile('Figures','fig_calibration_loss.png'), '-dpng', '-r300');
