1

Is there any function on Matlab/Octave that randomly picks a value from a list accordingly to a given probability?

For example: we have the vector [1 3 7]. The function I am looking for should pick one of those numbers with probability .25 for 1, .35 for 3 and .4 for 7.

I am trying to implement it myself, but I'd like to know if there is some build-in function for the next time I need something like this.

carllacan
  • 310
  • 3
  • 10

2 Answers2

1

What you described is like a Generalized Bernoulli Distribution. So, you can use the Multinomial Distribution to generate this data.

The MATLAB help page is here.

In your case, n=1 and p=[.25 .35 .4].

mnrnd(n,p)

will return a 1 x 3 vector which has only one non-zero element which corresponds to the random variable which should be chosen.


TL;DR Version:

To generate the required output, you can simply do dot([1 3 7], mnrnd(1,[.25 .35 .4]))

Nitish
  • 6,358
  • 1
  • 15
  • 15
1

You are looking for a function statistics toolbox called randsample. It samples k values out of n with replacement (without replacement is not supported). You want to select one value, which can be done as follows:

nSamplesToChoose=1;
weightVector=[0.2 0.5 0.3];%weights some to one so as to represent probability distribution
yourArray=[5 6 7]; %length of the array should be same as the length of weightVector.
chosenSample=randsample(yourArray,nSamplesToChoose,true,weightVector)

P.S. I encourage you to implement this by yourself. You may refer to this question.

Community
  • 1
  • 1
Autonomous
  • 8,935
  • 1
  • 38
  • 77
  • I did implement it `function pick = randompick(vector, probs) r = rand() c = 0 for i in 1:size(vector)(2) if c < r and r < c + probs(i) pick = vector(i) c = c + probs(i) end end endfunction ` I just wanted to know if there was anything don in case I ever need it again. randsample sounds perfect, many thanks :-) – carllacan Feb 22 '14 at 21:15
  • It seems that replacement is supported. [http://octave.sourceforge.net/statistics/function/randsample.html](http://octave.sourceforge.net/statistics/function/randsample.html). _Returns k random elements from a vector v with n elements, sampled without or with replacement._ – jbarrameda Jun 18 '16 at 18:06
  • Note that _weightVector_ has not to sum 1, so if you mean probabilities, you must make sure that it does sum one. For instance, the example of Parag, _`weightVector=[0.25 0.5 0.7];`_ does not sum 1, thus its values do not represent the probabilities of the elements. The actual probabilities in that case are `[0.25 0.5 0.7] / 1.45`. – jbarrameda Jun 18 '16 at 18:09
  • @JB I have edited the answer so that weights sum to one. Thanks. – Autonomous Jun 18 '16 at 21:41