MATLAB Answers

generate random number from a function that serves as PDF ?

25 ビュー (過去 30 日間)
Hakim Jemaa
Hakim Jemaa 2020 年 4 月 8 日
回答済み: Torsten 2020 年 4 月 8 日
Hello! I have mean zero second order gaussian distribution model and I want to generate random variables from this distribution within a specific interval [ -pi/2, pi/2 ]. the PDF depends on 4 parameters that are 2 variances and 2 other coefficients for the seocnd order. I built the PDF within a mtlab function and I would like to know how can I generate random numbers from this PDF ??

  2 件のコメント

Ameer Hamza
Ameer Hamza 2020 年 4 月 8 日
Can you share your pdf function?
Hakim Jemaa
Hakim Jemaa 2020 年 4 月 8 日
Of course
sorry for the bad equation writing. my parameters are w1, w2, sigma1 and sigma2 which are the variances


回答 (2 件)

Ameer Hamza
Ameer Hamza 2020 年 4 月 8 日
You can use the inverse transform sampling method: to generate a random number from your specified distribution. See my answer on this question for details:

  2 件のコメント

Hakim Jemaa
Hakim Jemaa 2020 年 4 月 8 日
Thanks. If I understood correctly, I have to get the CDF out of my PDF function, inverse it, generate a random number and compute its value ??
how to get the cdf ? and how to shrink the results to a specific segment ?
Thank you for your time
Ameer Hamza
Ameer Hamza 2020 年 4 月 8 日
Hakim, the pdf function you shared cannot be inverted in closed-form, so the method I mentioned cannot be directly applied to it. There are ways to apply this method, but it will be a bit more complicated. The easiest way is to use this package from FEX: This package will also restrict the random number in the specified range. Download this package and place it in MATLAB's path. Then run the following code. The variable rand_num contains 100000 random samples from the pdf you gave.
w1 = 0.5;
w2 = 0.5;
sigma1 = 1;
sigma2 = 0.1;
pdf = @(x) (w1/(sqrt(2*pi)*sigma1))*exp(-(x.^2/(2*sigma1^2)))+(w2/(sqrt(2*pi)*sigma2))*exp(-(x.^2/(2*sigma2^2)));
sample = linspace(-pi/2, pi/2, 1000);
pdf_sample = pdf(sample);
rand_num = randpdf(pdf_sample, sample, [100000 1]);


Torsten 2020 年 4 月 8 日
N = 1000;
U = rand(N,1);
n1 = numel(U(U<=w1));
n2 = N - n1;
X1 = sigma1*randn(n1,1);
X2 = sigma2*randn(n2,1);
X = [X1,X2];
X = X(abs(X)<=pi/2);

  0 件のコメント


Community Treasure Hunt

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

Start Hunting!

Translated by