1-D random number generation with any analytical expression probability density function

Version 1.4.0.0 (3.41 KB) by Hu
Generate random numbers according to given analytical expression for the PDF
610 Downloads
Updated 6 Aug 2014

View License

Given an analytical expression for probability density distribution(PDF), one can use this code to generate a sample of 1-D random numbers. One can just run rand_generator to
function [random_vector] = rand_generator(myfun,xmin,xmax,number,mode_switch)

With a recent improvement, this code now can generate 100,000 samples within 1 second on my laptop.

Here, myfun is a the PDF, xmin and xmax is the range for the variable, while number is the total number for the sample. mode_switch can be set to either 'fast' or 'slow'. This is the only optional argument, with default value set to 'fast'.

The process create a array, then a distinctive calculate the PDF use the given function, following this, the cumulative density function is calculated. An automated check is done in case that your xmin and xmax are set to far and may duce waste of calculation time, or duce problem in worse case.

Then an interpretation is done, so that a random number from U[0,1] is mapped to the cdf, and so this sample will follow the distribution of the desired function. The interpretation process use linear or spline, depending on whether 'fast' or 'slow' is used.

I write this code with git, if you are interested, you can further develop this, or contact me if any bug found. I may further improve this code so that the input could be an array instead of a function, but I feel not that motivated, if anyone specify this requirement, I'll be more than happy to do this.

Cite As

Hu (2024). 1-D random number generation with any analytical expression probability density function (https://www.mathworks.com/matlabcentral/fileexchange/40598-1-d-random-number-generation-with-any-analytical-expression-probability-density-function), MATLAB Central File Exchange. Retrieved .

MATLAB Release Compatibility
Created with R2011a
Compatible with any release
Platform Compatibility
Windows macOS Linux
Categories
Find more on Random Number Generation in Help Center and MATLAB Answers

Community Treasure Hunt

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

Start Hunting!
Version Published Release Notes
1.4.0.0

update to generalize and make the code more robust.

1.3.0.0

In this update, I change the plot, so that it will scale according to the PDF function, instead of according to the histogram, which makes more sense.

1.1.0.0

Identify a bug, and changed it

1.0.0.0