generating random numbers from binomial distribution
9 次查看(过去 30 天)
显示 更早的评论
To generate Bin(4, 3/4), use the following table:
x 0 1 2 3 4
P(X=x) 1/256 3/64 54/256 27/64 81/256
I want to write the MATLAB code to generate 5 random numbers from this distribution. I must use the following algorithm:
Algorithm:
1.Generate u from UNIF(0,1).
2.If P(X <= j-1) <= u <= P(X <= j) then set X=j for j=1,2,3,4
I have written the following code. But I think this code is a general code for generating from Binomial. How can I specialize it to my algorithm?
function X = dene(n,p,N)
X = zeros(1,N); % Generate the uniform random numbers: % N variates of n trials.
U = rand(N,n); % Loop over the rows, finding the number % less than p
for i = 1:N
ind = find(U(i,:) <= p);
X(i) = length(ind);
end
end
0 个评论
采纳的回答
the cyclist
2012-1-23
OK. I was right about cumsum, but there was another error. For each trial, when you generate the uniform random, you do not need to generate a vector of 5 of those values. You should just generate 1 value, to then compare against the cumulative value of p. I've fixed it up here. I also added a little plot to illustrate the distribution. (Hope I did not just do your homework for you.)
X = zeros(1,N); % Generate the uniform random numbers: % N variates of n trials.
U = rand(N,1); % Loop over the rows, finding the number % less than p
for i = 1:N
ind = find(U(i) <= cumsum(p));
X(i) = length(ind);
end
h = hist(X,unique(X))
count = fliplr(h)/sum(h)
figure
bar(unique(X),count)
4 个评论
the cyclist
2012-1-24
When you say "generated numbers", I assume you are talking about the output "X". I do not get only 0s and 1s, so I guess we are calling the function differently. Here is what I do. First, the code as I have written above is inside the function dene.m, where the first line of the function is:
function X = dene(n,p,N)
Then, in the base workspace, I define the inputs:
n = 5; % The function does not actually use this input anymore!
N = 10000;
p = [1/256 3/64 54/256 27/64 81/256];
Then, I call dene() with the inputs:
X = dene(n,p,N);
What I get for output is a series of integers, ranging from 1 to 5. The frequency distribution is (approximately) the probability p that you input. (The ordering is reversed relative to p, which I did not quite figure out, I must admit.)
更多回答(1 个)
the cyclist
2012-1-23
I have not looked at your algorithm in detail, but here's a guess. Where you have p inside your loop, I think you might want cumsum( p ) instead. Then you are checking to see if your randomly generated value is less that the cumulative probability distribution, which I think is what you want.
2 个评论
the cyclist
2012-1-23
OK. I'll try to take a closer look. Maybe you could add a little more details about why you think the results are incorrect. How many trials are you running?
另请参阅
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!