% ProbPdfMatlab.m
%
% by Neil E. Cotter
%
% Examples of code for generating random variables with various probability
% density functions.

% Uniform distribution.
X = rand(1);

% Binomial distribution for p = prob of success, q = prob of failure = 1-p.
% = P(m successes in n trials).
n = 1;
m = 1;
Pm_of_n = factorial(n)/(factorial(m)*factorial(n-m)) * p^m * q^(n-m);

% Gaussian or Normal distribution (standard gaussian, mu = 0, sigma^2 = 1).
X = randn(1);

% Gaussian with mean = mu and variance = sigma^2.
mu = 0;
sigma = 1;
X = mu + sigma * randn(1);

% Exponential distribution with parameter beta = 1.
%  f(x) = e^(-x)   for 0 < x
% Map uniform distribution to gamma distribution as follows:
%  f(y) = 1   0 < y < 1
%  F(y) = y   0 < y < 1
%  F(x) = int(exp(-x),x,0,x) = 1 - e^(-x)   for 0 < x
%  Choose y from uniform [0,1] distribution.
%  Set F(y) = F(x) and solve for y:
%  y = 1 - e^(-x)   =>   x = -ln(1 - y)
X = -log(1 - rand(1));

% Exponential distribution with parameter beta > 0.
%  f(x) = (1/beta)*e^(-x/beta)   for 0 < x
% Map uniform distribution to gamma distribution as follows:
%  f(y) = 1   0 < y < 1
%  F(y) = y   0 < y < 1
%  F(x) = int((1/beta)*exp(-x/beta),x,0,x) = 1 - e^(-x/beta)   for 0 < x
%  Choose y from uniform [0,1] distribution.
%  Set F(y) = F(x) and solve for y:
%  y = 1 - e^(-x/beta)   =>   x = -beta*ln(1 - y)
beta = 1;
X = -beta * log(1 - rand(1));

% Gamma distribution with parameters alpha and beta.
% Sum alpha-many exponential distributions.
alpha = 1;
X = 0;
for alpha_index = 1 : alpha
  X = X + -beta * log(1 - rand(1));
end

% Chi-squared distribution with nu degrees of freedom.
% = gamma distribution with alpha = nu/2 and beta = 2.
% = distribution for sum of nu standard gaussian random variables.
nu = 1
X = 0;
for nu_index = 1 : nu
  X = X + randn(1)^2;
end

