%% Week 2 Homework — Solution
% Simulate Nsim GDP paths; compute mean/variance of final GDP; plot histogram.

clear; clc; close all;

% ---- parameters ----
G0    = 100;
g     = 0.02;
sigma = 0.03;
T     = 20;
Nsim  = 100;
seed0 = 123;          % base seed


% ---- storage for final GDP ----
finalGDP = nan(Nsim,1);

for s = 1:Nsim
    % pass a unique seed to the function so each path differs
    G = gdp_simulate(G0, g, sigma, T, seed0 + s);
    finalGDP(s) = G(end);
end

% ---- statistics ----
mu_final  = mean(finalGDP, 'omitnan');
var_final = var(finalGDP,  'omitnan');
% Optional: print to console
fprintf('Mean final GDP: %.4f\n', mu_final);
fprintf('Var  final GDP: %.4f\n', var_final);

% ---- plot histogram ----
fig = figure('Color','w');
histogram(finalGDP, 15);
grid on; box on;
xlabel('Final GDP Level'); ylabel('Frequency');
title(sprintf('Final GDP after T=%d (N=%d)', T, Nsim));

mkdir('Figures')%make directory for plots
% ---- save outputs ----
saveas(fig, 'Figures/week2_final_gdp_hist.png');
savefig(fig, 'Figures/week2_final_gdp_hist.fig');

mkdir('Output')%make directory for workspace
save('Output/week2_homework_workspace.mat', ...
     'G0','g','sigma','T','Nsim','seed0','finalGDP','mu_final','var_final');