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.

Answers (3)

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
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)
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

Categories

Find more on Random Number Generation in Help Center and File Exchange

Asked:

on 18 Nov 2015

Answered:

on 18 Nov 2015

Community Treasure Hunt

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

Start Hunting!