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

11 views (last 30 days)
Mikael Gyllenswärd on 16 Mar 2020
Edited: the cyclist on 16 Mar 2020
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!
##### 2 CommentsShowHide 1 older comment
Mikael Gyllenswärd on 16 Mar 2020
Okay, do you have any idea what distribution that would come from then?

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.
Mikael Gyllenswärd on 16 Mar 2020
Thank you!!

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)
Mikael Gyllenswärd on 16 Mar 2020
Thanks a lot!