Generating Biased Random Number
Show older comments
I want to select a number in the interval of [0,1,2,3,....,22,23], but by a bias,
for example I want to select the 21 by the probability of 20% and 23 by %10, and the others by equal probability? what should I do?
1 Comment
Walter Roberson
on 11 Oct 2012
Do you have the statistics toolbox ?
Answers (5)
the cyclist
on 11 Oct 2012
Edited: the cyclist
on 11 Oct 2012
If you have the Statistics Toolbox, then I recommend using the randsample() command to do this type of sampling.
>> doc randsample
for details.
I'm no statistician, so I bet there's a better way but you can try this without stats toolbox:
Setup an index for each number in the vector and use randi to select the actual value. For example (3 numbers for ease of example).
myVec = [1 1 1 2 2 3 3 3 3 3]; % 1 is 30%, 2 is 20% and 3 is 50% chance
selectRand = randi(10,1); %choose the index
finalValue = myVec(selectRand) %select that number from the original vector
Since randi is uniformally distributed this should do the job. You could use:
randi(100,1);
to select the percentages with integer precision from 0 to 100%. You would need to figure out the best way to create myVec for your values.
Daniel Shub
on 11 Oct 2012
What about
y = rand;
if y < .1
x = 23;
elseif y < .3
x = 22
else
x = randi(21);
end
Without the stats toolbox:
A = 0:23; % The given array.
% Now lets sample it.
N = .5e5; % This many samples..
At = [0:20 22];
for ii = N:-1:1
B = rand;
if B>=.7 && B<.9
F(ii) = 21;
elseif B>=.9
F(ii) = 23;
else
F(ii) = At(randperm(22,1));
end
end
% Check that it worked.
hist(F,A) % should show even bars for all but two
sum(F==23)/length(F) % should be close to .1
sum(F==21)/length(F) % should be close to .2
.
.
.
EDIT
Here is a vectorized version of the above code:
A = 0:23; % The given array.
At = [0:20 22];
N = 100000; % This many samples..
F = rand(1,N);
F(F>=.7 & F<.9) = 21;
F(F>=.9 & F<1) = 23;
F(F<=1) = At(randi(22,1,sum(F<=1)));
% Check that it worked.
hist(F,A) % should show even bars for all but two
sum(F==23)/length(F) % should be close to .1
sum(F==21)/length(F) % should be close to .2
Walter Roberson
on 11 Oct 2012
N = 1000; %how many to generate
SampleVector = 0:23; %does not need to be ordered or consecutive or integer
UsualProbability = (1 - 0.20 - 0.10) ./ (24-2);
ProbabilityVector = repmat(UsualProbability,1,24);
ProbabilityVector(22) = 0.10;
ProbabilityVector(24) = 0.20;
slots = [0, cumsum(ProbabilityVector)];
[counts, slotidx] = histc(rand(1,N), slots);
randsamples = SampleVector(slotidx);
Categories
Find more on Uniform Distribution (Continuous) in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!