Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

Thread Subject:
random number with probability

Subject: random number with probability

From: galib

Date: 16 Aug, 2010 07:13:05

Message: 1 of 3

Hi,
I want to choose a number randomly from a set with some probabilities.
I have
pby = [.673 .562 .431]
list = [2 3 1]
now, I want to pick one number from list according to the probability in pby.
Please, suggest me.

Thanks.

Galib

Subject: random number with probability

From: Roger Stafford

Date: 16 Aug, 2010 07:45:24

Message: 2 of 3

"galib " <galib.cse@gmail.com> wrote in message <i4aoe0$3nv$1@fred.mathworks.com>...
> Hi,
> I want to choose a number randomly from a set with some probabilities.
> I have
> pby = [.673 .562 .431]
> list = [2 3 1]
> now, I want to pick one number from list according to the probability in pby.
> Please, suggest me.
>
> Thanks.
>
> Galib
- - - - - - - -
pby = pby/sum(pby); % They must add up to 1
c = cumsum(pby);
edges = [0,c(end-1),1]; % Prepare the bin limits
r = rand(1,n); % Choose the desired number n of random values
[ignore,bin] = histc(r,edges); % Get their bin indices
x = list(bin); % Find the list elements accordingly

The x vector has n elements with the required probability distribution.

Roger Stafford

Subject: random number with probability

From: galib

Date: 16 Aug, 2010 13:02:26

Message: 3 of 3

"Roger Stafford" <ellieandrogerxyzzy@mindspring.com.invalid> wrote in message <i4aqak$5b3$1@fred.mathworks.com>...
> pby = pby/sum(pby); % They must add up to 1
> c = cumsum(pby);
> edges = [0,c(end-1),1]; % Prepare the bin limits
> r = rand(1,n); % Choose the desired number n of random values
> [ignore,bin] = histc(r,edges); % Get their bin indices
> x = list(bin); % Find the list elements accordingly
>
> The x vector has n elements with the required probability distribution.
>
> Roger Stafford

Hi Roger,

Thank you for your reply.
I was thinking a simple way like generating a random number and if it was between 0 and pby(i) for each i, I took the list(i) item. Otherwise, I increase i or set i to 1 if it is the end of the list.

Anyway, thank you very much again.

Galib

Tags for this Thread

What are tags?

A tag is like a keyword or category label associated with each thread. Tags make it easier for you to find threads of interest.

Anyone can tag a thread. Tags are public and visible to everyone.

Contact us