Random sample generator from given pdf

2 views (last 30 days)
Hello everybody, I am a new user! I have a question regarding random sample generation in Matlab.
I have pdf function: 3/4(2x-x^2), x is on interval from 0 to 2. I have to generate sample that has the same distribution as mentioned before. What I have done so far: I calculated cdf by integrating and then obtained cdf^-1. I cannot solve the cdf^-1 equation for random x (from 0 to 1) as cdf^-1 is not solvable in Real numbers.
Am I doing something wrong? Any help would be greatly appreciated! Thanks in advance, Klemen.

Accepted Answer

Roger Stafford
Roger Stafford on 5 Feb 2014
The cdf you obtained was presumably F(x) = -1/4*x^3+3/4*x^2. It is quite possible to solve for its inverse, since that involves only the solution of the cubic equation
-1/4*x^3+3/4*x^2 = p
This particular cubic can be solved as follows:
p = rand;
a = atan2(2*sqrt(p*(1-p)),1-2*p);
x = 1+2*cos(a/3-2*pi/3);
You can verify this by checking that x always lies between 0 and 2 and comparing -1/4*x^3+3/4*x^2 with p in a number of cases.
Therefore you can generate n random values with the desired distribution as follows:
p = rand(n,1);
a = atan2(2*sqrt(p.*(1-p)),1-2*p);
x = 1+2*cos(a/3-2*pi/3);
  1 Comment
Klemen
Klemen on 5 Feb 2014
Thank you very much! The described solution worked flawlessly.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!