Вопрос

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?

Это было полезно?

Решение

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

Другие советы

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

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)

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);
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top