% CDA6530 (Fall 2013)
% Example code to show generating random variable
%===================================================

% Example 1:  discrete R.V. of loaded dice
P_theory = [0.1 0.1 0.1 0.1 0.3 0.3];  sampleSpaceNum = 6;
RV = [1 2 3 4 5 6]; % random variable values (sample points)
sampleNum = 5000;
Sample = zeros(1, sampleNum);
Bucket = P_theory;
SampleCount = zeros(1,sampleSpaceNum);

for i = 2:sampleSpaceNum,
    Bucket(i) = sum(P_theory(1:i));
end
for i=1:sampleNum,
    U = rand;
    for j= 1:sampleSpaceNum,
        if U <= Bucket(j), 
            Sample(i) = RV(j);
            SampleCount(j) = SampleCount(j)+1;
            break;  % break the j loop
        end
    end
end
P_simulation = SampleCount/sampleNum;
plot(RV, P_theory, 'ro-');
hold on;
plot(RV, P_simulation, 'k^-.');
legend('theory', 'simulation');
xlabel('Dice Number'); ylabel('Probability');
title('Generate discrete random variable: Loaded dice');
        

