Random weighted numbers without repeating
Afficher commentaires plus anciens
I'm trying to calculate 5 numbers at random. The numbers 1-35 have set probability weights that are assigned to each number. I'm wondering how, in Matlab, to compute 5 random numbers with weights WITHOUT repeats.
Réponses (3)
Walter Roberson
le 18 Nov 2015
0 votes
If you happen to be using a version of the Statistics toolbox too old to have datasample() then see http://www.mathworks.com/matlabcentral/answers/27515-random-sample-without-replacement#answer_35757
the cyclist
le 18 Nov 2015
If you have a recent version of the Statistics and Machine Learning Toolbox ...
M = 5; % Number in sample
N = 35; % Number in population
population = 1:N;
% Create some pretend weights. Put your real weights here.
w = rand(1,N);
w = w/sum(w);
x = datasample(population,M,'Replace',false,'Weights',w)
the cyclist
le 18 Nov 2015
If you have a version of the S & ML toolbox that predates datasample, you could do use randsample. But it does not support non-replacement, so you may need to use the rejection method if you choose non-unique elements. How inefficient this is depends on your weights.
M = 5; % Number in sample
N = 35; % Number in population
population = 1:N;
% Create some pretend weights. Put your real weights here.
w = rand(1,N);
w = w/sum(w);
% Preallocate
y = zeros(1,M);
% Generate values until you have M with no repeats
while numel(unique(y)) ~= M
y = randsample(population,M,true,w);
end
Catégories
En savoir plus sur Random Number Generation dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!