progfan
progfan

Reputation: 2536

Matlab: Sampling from a distribution

I need some help regarding getting samples from a given distribution in MATLAB. Suppose I have 5 bins and corresponding probabilities with which these bins are likely to produce samples.

For example, I may have .1, .2, .4, .2, .1 as the probabilities corresponding to 5 bins - (0-19),(20-39),(40-59), (60-79),(80-99).

Upvotes: 1

Views: 1909

Answers (1)

frickskit
frickskit

Reputation: 624

If you know the probabilities, what you want to do is make each bin take up proportional space to its probability on the number line and then pick a random number (from a flat distribution) from that number line.

Simple example: think of two bins, one with 40% and another with 60%. Pick a random number from 0 to 1, if it is .40 or below, you can say it "was pulled" from bin1. if above .40 "was pulled" from bin2.

This is a bad hack below, but if you can't find anything elegant....

 a = .1
 b = .2 + a
 c = .4 + b
 d = .2 + c
 e = .1 + d %cumulative probabilities (i.e. cdf)
 random = Random() %from 0 to 1 %pick random number
 if( 0 < random < = a) => bin1
 if( a < random < = b) => bin2
 if( b < random < = c) => bin3
 if( c < random <= d) => bin4
 if( d <= random) => bin5

Upvotes: 1

Related Questions