Easy question with probability
1 回表示 (過去 30 日間)
古いコメントを表示
Hi,
Let's say
P = [0.1 0.3 0.4 0.2]
X = [1 2 3 4]
where P(n) is the probability to select the X(n) element. I wish to make a function that select an "random" element of X according to its probability, like
f = myfun(P,X)
>> f = 2
thx a lot
0 件のコメント
採用された回答
Andrei Bobrov
2011 年 12 月 7 日
function F = myfun(P,X)
x = cumsum([0 P(:).'/sum(P(:))]);
x(end) = 1e3*eps + x(end);
[a a] = histc(rand,x);
F = X(a);
5 件のコメント
Oleg Komarov
2011 年 12 月 7 日
Andrei's function should read:
function F = myfun(P,X)
p = cumsum([0; P(1:end-1).'; 1+1e3*eps]);
[a a] = histc(rand,p);
F = X(a);
その他の回答 (1 件)
Roger Stafford
2017 年 3 月 18 日
Also a little late, this also works:
C = cumsum(P);
f = X(1+sum(C(end)*rand>C));
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Performance and Memory についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!