# Easy question with probability

11 views (last 30 days)
Steven on 7 Dec 2011
Answered: Roger Stafford on 18 Mar 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
##### 0 CommentsShowHide -1 older comments

Sign in to comment.

### Accepted Answer

Andrei Bobrov on 7 Dec 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 CommentsShowHide 4 older comments
Jyotshna Ramashire on 18 Mar 2017
can you please explain the codes?

Sign in to comment.

### More Answers (1)

Roger Stafford on 18 Mar 2017
Also a little late, this also works:
C = cumsum(P);
f = X(1+sum(C(end)*rand>C));
##### 0 CommentsShowHide -1 older comments

Sign in to comment.

### Community Treasure Hunt

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

Start Hunting!