% Estimating a PDF value from a single histogram bin
% Textbook: Part I, "Continuous Random Variable" (PDF definition) and
% "Statistical Plots" (pdf histogram)
%
% f_X(x0) is approximated by Pr(a < X < b)/dx, where [a,b] is a bin of
% width dx centered at x0. The probability is estimated by the fraction of
% the N samples that fall into the bin.

clearvars; close all
rng(0)

N = 1e7;                        % number of experiments
lambda = 1;
X = -log(rand(1, N))/lambda;    % Exp(lambda) samples (or exprnd(1/lambda,1,N))

m = 50;                         % number of bins over the observed range
dx = (max(X) - min(X))/m;       % bin width
a = min(X);                     % first bin, [a, b]
b = a + dx;
x0 = a + dx/2;                  % bin center

f_est = mean(a < X & X < b)/dx;
f_theory = lambda*exp(-lambda*x0);
fprintf('f_X(%.3f): theory = %.4f, single-bin estimate = %.4f\n', ...
    x0, f_theory, f_est)

% The same idea applied to all bins at once
figure
histogram(X, m, 'Normalization', 'pdf')
hold on
x = linspace(0, max(X), 200);
plot(x, lambda*exp(-lambda*x), 'r', 'LineWidth', 1.5)
hold off
xlim([0 8])
xlabel('x')
ylabel('f_X(x)')
legend('pdf histogram', 'theory')
grid on
