How can I generate a random number from a chi square distribution?

4 views (last 30 days)
How can I generate a random number from a chi square distribution?
Example: I have a very bias die which is more likely to roll a 2, how can I create a RNG between 1-6 which is more likely to be 2?
I tried chi2rnd but I did not get it to work!
Thanks in advance!
  2 Comments
Jeff Miller
Jeff Miller on 16 Mar 2020
It is a little unclear what you want, because the numbers in your example with a biased die would not come from a chi square distribution.
Mikael Gyllenswärd
Mikael Gyllenswärd on 16 Mar 2020
Okay, do you have any idea what distribution that would come from then?

Sign in to comment.

Answers (2)

Ameer Hamza
Ameer Hamza on 16 Mar 2020
Edited: Ameer Hamza on 16 Mar 2020
You can download the random number generator from here: https://www.mathworks.com/matlabcentral/fileexchange/34101-random-numbers-from-a-discrete-distribution and place it in MATLAB's path. It can generate probability according to a specified distribution. For example
p = [1 10 1 1 1 1]; % specify your own probability distribution
p = p./sum(p);
x = gendist(p, 1, 100000);
histogram(x);
Vector p controls the weight given to each element. If p = [1 10 1 1 1 1], then 2 is ten times more likely than other numbers
When p = [1 1 1 1 1 1]
when p = [1 10 1 1 1 1]
BTW, following code will also work without the need to download any external function
p = [1 2*ones(1,10) 3 4 5 6]; % specify your own probability distribution
index = randi([1 numel(p)], 1, 100000);
x = p(index);
histogram(x);
However, the way to specify the probability distribution is a bit different here.

the cyclist
the cyclist on 16 Mar 2020
Edited: the cyclist on 16 Mar 2020
If you have the Statistics and Machine Learning Toolbox, you can use the randsample command to do weighted probabilities. In the code below, I assign half of the probability to the number 2, and distribute the rest to the other numbers.
% Set random seed, for reproducibility
rng default
% Generated random values for a 6-sided die, with weight probability
r = randsample(1:6,10000,true,[0.1 0.5 0.1 0.1 0.1 0.1]);
% Plot the results
figure
histogram(r)

Community Treasure Hunt

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

Start Hunting!