MATLAB: How to get a random value in a matrix, given a probability of each value being chosen

probabilityrandom number generator

I've a matrix with two columns. The first column is the number I want to get and the second column is the probability that number has to be chosen (0 to 1).
I'm trying to make a function that returns one of the values of the first column. And the probability of each value of the first column to be chosen is given in the second column (0 -> less chance; 1 -> more chance).
234,6591 0,4028
416,1825 0,7144
433,2481 0,7436
566,2786 0,9720
472,4878 0,8110
582,1153 0,9992
545,5523 0,9364
565,2468 0,9702
Does anyone know how to do this?

Best Answer

Note that your probabilities should sum up to 1. Otherwise, they're not probabilities. So you need to divide them by the sum of column 2.
There are probably something in the Stats and Machine learning toolbox but, if like me, you don't have it, this would do:
M = [234.6591 0.4028
416.1825 0.7144
433.2481 0.7436
566.2786 0.9720
472.4878 0.8110
582.1153 0.9992
545.5523 0.9364
565.2468 0.9702];
numsamples = 1000; % however many you want
bins = [0; cumsum(M(:, 2)) / sum(M(:, 2))]; %create bins whose width is the probability

samples = M(discretize(rand(numsamples, 1), bins), 1);
You can easily check that the samples are generated according to your probability:
>>numsamples = 1e8;
>>bins = [0; cumsum(M(:, 2)) / sum(M(:, 2))]; %create bins whose width is the probability
>>samples = M(discretize(rand(numsamples, 1), bins), 1); %generate lots of samples
>>[~, idx] = ismember(samples, M(:, 1));
>>prob = accumarray(idx, 1) / numsamples; %generate histogram of each sample
>>notaprob = prob * sum(M(:, 2)) %to convert back to your 'not probabilities' in column 2
notaprob =
0.4029
0.7146
0.7436
0.9721
0.8109
0.9992
0.9364
0.9699