0

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. Also seeking how to compute 5 sets of those.

weswes18
  • 1
  • 1

1 Answers1

2

Although I would suspect MATLAB has a built in function for this, the documentation for randsample suggests otherwise:

Y = randsample(N,K,true,W) or randsample(POPULATION,K,true,W) returns a weighted sample, using positive weights W, taken with replacement. W is often a vector of probabilities. This function does not support weighted sampling without replacement.

So, instead, since you only are looking for a few numbers, looping isn't a terrible idea:

POP = 1:35;
W = rand(1,35); W=W/sum(W);
k = 5;

mynumbers = zeros(1,k);
for i=1:k
    mynumbers(i)    = randsample(POP,1,true,W);
    idx2remove      = find(POP==mynumbers(i));
    POP(idx2remove) = [];
    W(idx2remove)   = [];
end

The entries in W are your weights. The vector POP is your number 1 through 35. The number k is how many you'd like to choose.

The loop randomly samples one number (with weights) at a time using MATLAB's randsample, then the selected number and corresponding weight are removed from POP and W.

For larger k I hope there's a better solution...

Geoff
  • 1,202
  • 10
  • 18
  • Just found duplicate [here](http://stackoverflow.com/questions/8205443/weighted-sampling-without-replacement) – Geoff Nov 18 '15 at 02:01
  • Holy nuts, Thanks! Quick question. I'm horribly new to matlab and I'm honestly just using it for this specific problem in my life. So I don't understand quite what you're doing in your for loop. (i.e., where do i put in my assigned weights). Sorry, just horribly new to this! – weswes18 Nov 18 '15 at 02:02
  • another follow up in addition to the previous, is there any way to generate 5 different vectors of 5? – weswes18 Nov 18 '15 at 02:22
  • Yes to your first question, for your second, wrap the code in Geoff''s answer in another `for` loop. – David Nov 18 '15 at 02:26
  • @David, have no idea how to do that, painfully new to coding and I'm only using this for a specific project at work, thanks for your patience. – weswes18 Nov 18 '15 at 02:29
  • Try this Getting Started with MATLAB http://au.mathworks.com/help/matlab/getting-started-with-matlab.html – David Nov 18 '15 at 02:32
  • 1
    Also in the documentation: `To randomly sample data, with or without replacement, use datasample.` – sco1 Nov 18 '15 at 02:35
  • but you couldn't just tell me how to do the second forloop? Some buddies and I are playing around with something and this would be a huge help. – weswes18 Nov 18 '15 at 02:37