Selecting a "random" element from an array with each element having it's own weighting
12 ビュー (過去 30 日間)
古いコメントを表示
Hi,
I am trying to write code that will permit me to select a "random" element from an array with each element having it's own weighting.
For example, assume array A = [1;2;3;4], where there is a 10% chance for 1, 20% chance for 2, 30% chance for 3 and 40% chance for 4 to be chosen.
I suppose I could just have number 2 added twice, number 3 three times and 4 four times, but trying to find something more robust since the data I'm working with is very large.
How would I go about writing this code?
Thanks
0 件のコメント
採用された回答
Bruno Luong
2021 年 1 月 26 日
A=[1,2,3,4];
p=[10 20 30 40];
c=cumsum(p);
[~,r]=histc(rand(1,1e6),[0 c/c(end)]); % generate 1e6 numbers
r=A(r);
% Check
histogram(r)
7 件のコメント
その他の回答 (1 件)
Jeff Miller
2021 年 1 月 26 日
編集済み: Jeff Miller
2021 年 1 月 26 日
% Wts is your vector of weights.
Wts = Wts / sum(Wts); % make sure they sum to 1
cumPrs = cumsum(Wts); % cumPr is the cumulative probability of selecting each vector position or smaller
r = rand; % a random number between 0 and 1
randVecPos = find(cumPrs>r,1); % select this random vector position from your array
4 件のコメント
Bruno Luong
2021 年 1 月 26 日
編集済み: Bruno Luong
2021 年 1 月 26 日
This code is buggy, it returns empty with 10% chance.
Need to put 0 in front of the array of FIND command as with my code.
参考
カテゴリ
Help Center および File Exchange で Random Number Generation についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!