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.