clear all
close all


disp('Simulated Coverage of CI for the mean')
  lw = 2; 
  set(0, 'DefaultAxesFontSize', 16);
  fs = 15;
  msize = 10;
% end of preabmle--------------------------------------

randn('state', 50)
M=10000;  %simulate M times
n = 40;        % sample size
alpha = 0.05;      %1-alpha = confidence
tquantile = tinv(1-alpha/2, n-1); 
h = waitbar(0,'Simulation running ...');
covers =[]; 
for i = 1:M
    X = 10 + 4*randn(1,n); %sample, mean=10, var =16
    xbar = mean(X); s = std(X);
    LB = xbar - tquantile * s/sqrt(n);
    UB = xbar + tquantile * s/sqrt(n);
    % cover=1 if the interval covers population mean 10
    if UB < 10 | LB > 10
            cover = 0;
    else
            cover = 1;
    end
        covers =[covers cover]; %saves cover history
        waitbar(i/M)
end
sum(covers)/M %proportion of intervals that cover the mean
close(h)
figure(1)
plot(cumsum(covers)./(1:length(covers)),'linewidth',lw )
hold on
plot(0.95*ones(size(covers)),'r-','linewidth',lw)
  %print -depsc 'C:\Springer\Estim\Estimeps\cicov.eps'