Easy question with probability

1 visualización (últimos 30 días)
Steven
Steven el 7 de Dic. de 2011
Respondida: Roger Stafford el 18 de Mzo. de 2017
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

Respuesta aceptada

Andrei Bobrov
Andrei Bobrov el 7 de Dic. de 2011
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 comentarios
Oleg Komarov
Oleg Komarov el 7 de Dic. de 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 el 18 de Mzo. de 2017
can you please explain the codes?

Iniciar sesión para comentar.

Más respuestas (1)

Roger Stafford
Roger Stafford el 18 de Mzo. de 2017
Also a little late, this also works:
C = cumsum(P);
f = X(1+sum(C(end)*rand>C));

Categorías

Más información sobre Performance and Memory en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by