views:

693

answers:

4

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
A: 

Hi

Does nchoosek help ? or pascal ?

Mark

High Performance Mark
+1  A: 

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.

gnovice
+1. nchoosek helps for small N. For large N it's a problem.
Jason S
@Jason: Very true. Just in case it ends up being a problem for you, I added some links to a MathWorks submission by John D'Errico which allows you to perform variable precision integer arithmetic.
gnovice
A: 

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

Jason S
+1  A: 

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.

shabbychef

related questions