3

I need to draw random numbers following a distribution I chose.

Example: draw 7 numbers from 1 to 7 with those probabilities:

  • 1: 0.3
  • 2: 0.2
  • 3: 0.15
  • 4: 0.15
  • 5: 0.1
  • 6: 0.05
  • 7: 0.05

Since in my actual application I need to draw potentially 1000 numbers I need this to be as much efficient as possible (ideally linear). I know there is a function in MATLAB that draws random numbers from a normal distribution; is there any way to adapt it?

chappjc
  • 30,359
  • 6
  • 75
  • 132
Maik Xhani
  • 65
  • 8
  • 3
    See also [Weighted random numbers in MATLAB](http://stackoverflow.com/questions/2977497/weighted-random-numbers-in-matlab). – chappjc Mar 14 '14 at 19:28

4 Answers4

8

Think you can use randsample too from Statistics Toolbox as referenced here.

%%// Replace 7 with 1000 for original problem
OUT = randsample([1:7], 7, true, [0.3 0.2 0.15 0.15 0.1 0.05 0.05]) 
Community
  • 1
  • 1
Divakar
  • 218,885
  • 19
  • 262
  • 358
1
numbers = 1:7;
probs = [.3 .2 .15 .15 .1 .05 .05];
N = 1000; %// how many random numbers you want

cumProbs = cumsum(probs(:)); %// will be used as thresholds
r = rand(1,N); %// random numbers between 0 and 1
output = sum(bsxfun(@ge, r, cumProbs))+1; %// how many thresholds are exceeded
Luis Mendo
  • 110,752
  • 13
  • 76
  • 147
1

You can use gendist from matlab file exchange: http://www.mathworks.com/matlabcentral/fileexchange/34101-random-numbers-from-a-discrete-distribution/content/gendist.m

This generates 1000 random numbers: gendist([.3,.2,.15,.15,.1,.05,.05],1000,1)

Daniel
  • 36,610
  • 3
  • 36
  • 69
0

If you do not have randsample, you can use histc like it does internally, just without all the fluff:

N = 100;
nums = 1:7;
p = [.3 .2 .15 .15 .1 .05 .05];

cdf = [0 cumsum(p(:).'/sum(p))]; cdf(end)=1; %' p is pdf
[~, isamps] = histc(rand(N,1),cdf);
out = nums(isamps);
chappjc
  • 30,359
  • 6
  • 75
  • 132