% Listing 13.1 of the book for Figure 13.5 
% "Principles of System Identification: Theory and Practice"

% Arun K. Tangirala
% September 04, 2015
% Freely distributed under no warranty

%% Generate data and compute CIs
% Initialize variables
ybar = []; var_y = []; ci_low = []; ci_up = [];

% Generate data and compute CIs
for i = 1:1000,
 	yi = randn(1000,1);
    ybar = [ybar; mean(yi)];
    var_y = [var_y; var(yi)];
    ci_low = [ci_low ; ybar(i) - 1.96*std(yi)/sqrt(1000)];
    ci_up = [ci_up ; ybar(i) + 1.96*std(yi)/sqrt(1000)];
end

%% Plot the CIs

% Plot the CIs in 2-D space
figure; plot(ci_low,ci_up,'x') 
hold on
plot([-0.2 0.05],[0 0],'r--')
plot([0 0],[-0.05 0.2],'g--')

% Plot the intervals that miss the true mean
figure
ind_neg = find(ci_up < 0); ind_pos = find(ci_low > 0);
ind_tot = [ind_neg ; ind_pos];
plot([ci_low(ind_tot) ci_up(ind_tot)]',[ind_tot ind_tot]','-o')
hold on; plot([0 0],[0 1000],'k--');