Reputation: 77
So this is the question:
Suppose we only have a random number generator, which has a U(0, 1) distribution. But we want to generate a sequence of random numbers with a non-uniform distribution (e.g., Exp(2)). Now, please first use the random number generator to generate 105 uniformly (U(0, 1)) distributed samples then transform those samples to data points, which should have a Exp(2) distribution finally plot those transformed samples by using the hist function.
I am having trouble converting to exponential. I emailed my TA and he wasn't much help, but he did tell me I don't need the loop.
Here's what I have:
distnames = {'Uniform', 'Exponential'};
lower=0;
upper=1;
uds = makedist(distnames{1},'lower' ,lower, 'upper', upper);
nums = random(uds, 1, 10); %using 10 randoms for testing, needs to be 10^5
for k=1:length(nums)
mu=2;
uds = makedist(distnames{2},'mu' ,mu);
points = pdf(uds);
end
%%hist(points)
Upvotes: 2
Views: 1252
Reputation: 4519
What you're missing is the overall mathematics.
You can generate draws from a single variable probability distribution by using: (1) a uniform random number generator and (2) the inverse of the cumulative distribution function (inverse CDF) for the distribution you're trying to generate draws from.
Let F^-1 denote the inverse cdf. Let X be a random variable uniformly distributed on (0, 1). What is the distribution of Y = F^-1(X)? It turns out that Y generated this way has CDF F. Proof outline:
P(Y<= a) = P(F^-1(X) <= a)
= P(X <= F(a))
= F(a) (since X is uniform on (0,1) and 0 <= F(a) <= 1)
The CDF of Y (i.e. P(Y <= a)) is equal to F
eg. To generate a pseudo-random draw from the standard normal distribution:
y = norminv(rand(), 0, 1); % In Matlab, 'norminv' is inverse CDF function
% for normal distribution. (0 is mean, 1 is stdev)
Your code can be about 1 line long. Replace norminv with any inverse CDF.
Upvotes: 4