Generating random numbers from histogram data

13 views (last 30 days)
I have probability data (as in the example below), which I have turned into CDF data. I want to generate random numbers and use them to draw values from the empirical distribution. The above seems to generate solely values of '1', and I'm not sure what I'm doing wrong.
% Those are your values and the corr. probabilities:
PD =[
1.0000 0.1000
2.0000 0.3000
3.0000 0.4000
4.0000 0.2000];
% Then make it into a cumulative distribution
D = cumsum(PD(:,2));
D
%D = [0.1000 0.4000 0.8000 1.0000]'
%Now for every r generated by rand, if it is between D(i) and D(i+1),
%then it corresponds to an outcome PD(1,i+1), with the obvious
%extension at i==0.
R = rand(100,1); % Your trials
p = @(R) find(R<PD,1,'first'); % find the 1st index s.t. r<D(i);
% Now this are your results of the random trials
rR = arrayfun(p,R);
% Check whether the distribution looks right:
hist(rR,1:4)

Accepted Answer

Geoff Hayes
Geoff Hayes on 26 Aug 2014
Edited: Geoff Hayes on 26 Aug 2014
Sam - PD is a 4x2 matrix. Your values of R are in the interval (0,1). For every one of these values that you pass in to your anonymous function p, then that value is compared against all elements of PD...with the first element being 1 (at PD(1,1)). So a 1 will be returned for every input into this anonymous function.
Instead, based on your comment (the extension part I'm not too clear on)
%Now for every r generated by rand, if it is between D(i) and D(i+1),
%then it corresponds to an outcome PD(1,i+1), with the obvious
%extension at i==0.
should you be doing
p = @(R) find(R<D,1,'first');
This will ensure that p has values that are in the set {1,2,3,4}.

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!