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

3 vues (au cours des 30 derniers jours)
Mikael Gyllenswärd
Mikael Gyllenswärd le 16 Mar 2020
Modifié(e) : the cyclist le 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!
Thanks in advance!
  2 commentaires
Jeff Miller
Jeff Miller le 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 le 16 Mar 2020
Okay, do you have any idea what distribution that would come from then?

Connectez-vous pour commenter.

Réponses (2)

Ameer Hamza
Ameer Hamza le 16 Mar 2020
Modifié(e) : Ameer Hamza le 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 le 16 Mar 2020
Modifié(e) : the cyclist le 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!

Translated by