Random weighted numbers without repeating

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.

Respuestas (3)

Walter Roberson
Walter Roberson el 18 de Nov. de 2015

0 votos

You can use datasample() from the Statistics toolbox.
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
the cyclist el 18 de Nov. de 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
the cyclist el 18 de Nov. de 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

Categorías

Más información sobre Random Number Generation en Centro de ayuda y File Exchange.

Preguntada:

el 18 de Nov. de 2015

Respondida:

el 18 de Nov. de 2015

Community Treasure Hunt

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

Start Hunting!

Translated by