Generate N random number from weighted groups
Show older comments
Hi,
I am wanting to generate numbers from weighted groups, for example this could be a set of 10 numbers from the ranges 0:50 and 100:150.
I have tried
>> randsample([0:50, 100:150],10,true,[0.3 0.7])
But cannot seem to get the randsample function working for weighted groups, any help would be appreciated
Thanks
Answers (2)
KALYAN ACHARJYA
on 18 Dec 2020
Edited: KALYAN ACHARJYA
on 18 Dec 2020
w, of the same length as the vector population
randsample([0:50, 100:150],10,true,rand(1,102));
%.......................................102 vector population length (example)
groupProbs = [0.3 0.7];
groupVal = rand(10, 1);
whichGroup = groupVal <= groupProbs(1); % for more groups, use discretize
results = zeros(size(whichGroup));
results(whichGroup == 1) = randi([0 50], nnz(whichGroup == 1), 1); % For more groups, for loop
results(whichGroup == 0) = randi([100 150], nnz(whichGroup == 0), 1);
finalResults = table(groupVal, results)
Categories
Find more on Triangular Distribution 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!