开发者

How do I compute a PMF and CDF for a binomial distribution in MATLAB?

开发者 https://www.devze.com 2022-12-13 23:51 出处:网络
I need to calculate the probability mass function, and cumulative distribution function, of the开发者_高级运维 binomial distribution. I would like to use MATLAB to do this (raw MATLAB, no toolboxes).

I need to calculate the probability mass function, and cumulative distribution function, of the开发者_高级运维 binomial distribution. I would like to use MATLAB to do this (raw MATLAB, no toolboxes). I can calculate these myself, but was hoping to use a predefined function and can't find any. Is there something out there?

function x = homebrew_binomial_pmf(N,p)
    x = [1];
    for i = 1:N
       x = [0 x]*p + [x 0]*(1-p);
    end


You can use the function NCHOOSEK to compute the binomial coefficient. With that, you can create a function that computes the value of the probability mass function for a set of k values for a given N and p:

function pmf = binom_dist(N,p,k)
  nValues = numel(k);
  pmf = zeros(1,nValues);
  for i = 1:nValues
    pmf(i) = nchoosek(N,k(i))*p^k(i)*(1-p)^(N-k(i));
  end
end

To plot the probability mass function, you would do the following:

k = 0:40;
pmf = binom_dist(40,0.5,k);
plot(k,pmf,'r.');

and the cumulative distribution function can be found from the probability mass function using CUMSUM:

cummDist = cumsum(pmf);
plot(k,cummDist,'r.');

NOTE: When the binomial coefficient returned from NCHOOSEK is large you can end up losing precision. A very nice alternative is to use the submission Variable Precision Integer Arithmetic from John D'Errico on the MathWorks File Exchange. By converting your numbers to his vpi type, you can avoid the precision loss.


octave provides a good collection of distribution pdf, cdf, quantile; they have to be translated from octave, but this is relatively trivial (convert endif to end, convert != to ~=, etc;) see e.g. octave binocdf for the binomial cdf function.


looks like for the CDF of the binomial distribution, my best bet is the incomplete beta function betainc.


For PDF

x=1:15
p=.45

c=binopdf(x,15,p)

plot(x,c)

Similarly CDF

D=binocdf(x,15,p) 

plot(x,D)
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号