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

 Akzeptierte Antwort

Andrei Bobrov
Andrei Bobrov am 7 Dez. 2011

2 Stimmen

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 Kommentare

Steven
Steven am 7 Dez. 2011
it works perfect, but may you comment why this line:
x(end) = 1e3*eps + x(end);
Steven
Steven am 7 Dez. 2011
wait, should not it be F = X(a) instead ? in this case, probabily are not good...
Andrei Bobrov
Andrei Bobrov am 7 Dez. 2011
My typo! Corrected.
Oleg Komarov
Oleg Komarov am 7 Dez. 2011
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);
Jyotshna Ramashire
Jyotshna Ramashire am 18 Mär. 2017
can you please explain the codes?

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

Roger Stafford
Roger Stafford am 18 Mär. 2017

1 Stimme

Also a little late, this also works:
C = cumsum(P);
f = X(1+sum(C(end)*rand>C));

Kategorien

Community Treasure Hunt

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

Start Hunting!

Translated by