Search code examples
matlabprobabilityprobability-density

clean method to generate random discrete distributions in matlab


Frequently enough, I need to generate arbitrary discrete distributions in matlab. I can write this:

randDiscreteDistribution = rand(sizeOfDistribution, 1);
randDiscreteDistribution = randDiscreteDistribution / sum(randDiscreteDistribution);

although I'd like to avoid writing these two lines everywhere, encapsulating this functionality would make for cleaner software. I'd like to avoid writing a full fledged function for source control reasons, I'd need to use this across multiple repos, it certainly doesn't merit its own submodule!

Ideally I'd like a solution along the lines of an anonymous function (local functions are out since they're not allowed in a script), though I'd sooner use these two ugly lines each time I needed it than hack around something which performs a bit slower: (http://www.mathworks.com/matlabcentral/answers/50195-is-it-possible-to-write-several-statements-into-an-anonymous-function).


Solution

  • You could reduce it to one line this way:

    randDiscreteDistribution  = diff([0; sort(rand(sizeOfDistribution-1, 1)); 1]);
    

    Instead of normalizing to 1 by dividing, this takes sizeOfDistribution-1 points in the unit interval and then uses the lenghts of the obtained subintervals as the distribution values. Those lengths are automatically normalized.

    With this approach, the distribution of the obtained randDiscreteDistribution values is different from that in your original code. But perhaps that doesn't matter? (with your code the randDiscreteDistribution values are not uniform anyway).