%Kaplan_2_1.m
%
%Kaplan Chapter 2. Example 1. (pp. 2-3)
%Recent poll of 500 representative voters revealed that 8% supported a
%certain political candidate for the presidential nomination of his/her
%party.  If the candidate can secure 10% of the vote in next week's election
%he/she will qualify for federal campaign finances.  Does the candidate
%have a reasonable chance of achieving 10% of the vote?  Let's use
%resampling to generate an empirical cumulative probability function for
%all likely election results; then use it to estimate the likelihood of
%obtaining an election result of 10% (or better)...

clear
% seed random number generator to state zero (debugging and development)
if verLessThan('matlab', '8.0.0')
    RandStream.setDefaultStream(RandStream('mt19937ar','seed',0));
else
    RandStream.setGlobalStream(RandStream('mt19937ar','seed',0));
end

pollsize = 500;
%voter population poll results: 92% against, 8% suppurt candidate
voters = [zeros(92,1); ones(8,1)];
nIterations = 10000;
resamples = zeros(nIterations, 1);
%run the resampling simulation
for i=1:nIterations
    sample = randsample(voters, pollsize, true);
    support = sum(sample)/pollsize;
    resamples(i) = support;
end

%find values requested in original Kaplan exercise
%compute the most likely poll result
percent4 = mean(resamples);
%calculate the boundaries of the 95% confidence interval
[bounds] = prctile(resamples, [2.5 97.5]);

%now, let's go beyond Kaplan's simple 95% confidence interval computation:
%generate cumulative probability function for possible poll results
[cumprobs, pollvals] = ecdf(resamples);
%now, find the probability of obtaining 10% of votes or higher
temp = abs(pollvals - 0.10);      %subtract 10% 
index = find(temp == min(temp));  %find location of minimum difference from 10%
p10plus = 1.0 - cumprobs(index);  %compute tail probability for 10% (and above)

%plot cumulative probability function for resampling simulation
figure, clf, plot(pollvals, cumprobs);
xlabel('Poll Results (Candidate''s Percentage)');
ylabel('Cumulative Probability');
title('Resampled Political Poll Projections');
line([pollvals(index) pollvals(index)],[0 1]);  %draw line delineating upper tail
annostr = sprintf('Prob(10%% plus election result) = %6.3f', p10plus);
text(0.045,0.9,annostr);  %annotate figure with critical result
