Easy question with probability

조회 수: 6 (최근 30일)
Steven
Steven 2011년 12월 7일
답변: Roger Stafford 2017년 3월 18일
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

채택된 답변

Andrei Bobrov
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
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);
Jyotshna Ramashire
Jyotshna Ramashire 2017년 3월 18일
can you please explain the codes?

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Roger Stafford
Roger Stafford 2017년 3월 18일
Also a little late, this also works:
C = cumsum(P);
f = X(1+sum(C(end)*rand>C));

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by