
%% Exported from Jupyter Notebook
% Run each section by placing your cursor in it and pressing Ctrl+Enter

%% Markdown Cell:
% Write a *Matlab* script to generate a data set with $200$ samples and sample sizes $N\in\{10,20,100\}$ using any old distribution.
% Compare the distribution of the means for the different $N$.
% Use the sample distributions and a t-table to compute $99\%$ confidence intervals.

%% Code Cell[9]:

clear; close all;
save_figures = true; % save flag

%% Markdown Cell:
% Generate the data set.

%% Code Cell[10]:

M = 200; % # of samples
N_a = [10,20,100]; % sample sizes

mu = 27; % population mean
sigma = 9; % population std

rng(1) % seed random number generator
data_a = mu + sigma*randn(N_a(end),M); % normally distributed
size(data_a) % check size
data_a(1:10,1:5) % check first 10 rows and first five columns

%% Markdown Cell:
% Compute the means for different sample sizes.

%% Code Cell[11]:

mu_a = NaN*ones(length(N_a),M);
for i = 1:length(N_a)
    mu_a(i,:) = mean(data_a(1:N_a(i),1:M),1);
end

%% Markdown Cell:
% Plotting the distribution of the means yields \autoref{fig:student_confidence_hist}.

%% Code Cell[34]:

h = figure;
c = jet(3);
for i = 1:length(N_a)
    p = histogram(mu_a(i,:));
    hold on;
    p.Normalization = 'probability';
    p.FaceColor = c(i,:);
    p.FaceAlpha = .75;
    p.DisplayName = sprintf(...
        'interval for N = %i: ',...
        N_a(i)...
    );
end
xlabel('random variable $X$','interpreter','latex');
ylabel('probability (PMF)')
legend('show')
hgsave(h,'figures/temp');

%% Code Cell[35]:

if save_figures
    fn = 'student_confidence_hist.tex';
    h = hgload('figures/temp');
    cleanfigure;
    matlab2tikz(['figures/',fn],...
        'figurehandle',h,...
        'width','.9\linewidth',...
        'height','.33\linewidth',...
        'extraAxisOptions',...
        [...
            'scaled ticks=false,',... 
            'tick label style={/pgf/number format/fixed}'...
        ],...
        'showInfo', false...
    );
end

%% Markdown Cell:
% It makes sense that the larger the sample size, the smaller the spread.
% A quantitative metric for the spread is, of course, the standard deviation of the means for each sample size.

%% Code Cell[28]:

S_mu = std(mu_a,0,2)

%% Markdown Cell:
% Look up t-table values for different sample sizes and 99% confidence.
% Use these, the mean of means, and the standard deviation of means to compute the 99% confidence interval for each $N$.

%% Code Cell[37]:

t_a = [3.25,2.861,2.626];
for i = 1:length(N_a)
    interval = mean(mu_a(i,:)) + [-1,1]*t_a(i)*S_mu(i);
    disp(sprintf('interval for N = %i: ',N_a(i)))
    disp(interval)
end

%% Markdown Cell:
% As expected, the larger the sample size, the smaller the interval over which we have 99% confidence in the estimate.
