[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: Choose index into array of probabilities
From: |
Paul Kienzle |
Subject: |
Re: Choose index into array of probabilities |
Date: |
Sat, 2 Sep 2006 00:23:26 -0400 |
On Aug 24, 2006, at 2:18 PM, Søren Hauberg wrote:
tor, 24 08 2006 kl. 23:38 +0530, skrev Masatran (Deepak), R.:
I have an array, of probabilities which add up to 1. How can I
generate an
index into this array with each array cell being chosen with
probability
equal to the cell value?
Assuming p is the array of probabilities:
cs = cumsum(a);
idx = find(cs >= rand());
This should do it. I think I've written those line of code 100 times
(it's a central part of the particle filter)
You can use the lookup function to generate a bunch of indices at the
same time:
# Generate some unnormalized density function
pdf = abs(cos(2*pi*linspace(0,1,41)));
# Turn it into a normalized cdf
cdf = cumsum(pdf); cdf = cdf/cdf(end);
# Generate random indices according to the cdf
y = lookup(cdf(1:end-1),rand(100000,1))+1;
# Show the unnormalized density function of the random values
hist(y,1:length(pdf))
- Paul
[Prev in Thread] |
Current Thread |
[Next in Thread] |
- Re: Choose index into array of probabilities,
Paul Kienzle <=