how to calculate the negative binomial distribution in matlab

To calculate the negative binomial distribution in MATLAB, you can use the nbinpdf and nbinrnd functions from the Statistics and Machine Learning Toolbox.

To calculate the probability mass function for a given set of parameters, use the nbinpdf function:

main.m
r = 5; % number of failures
p = 0.3; % probability of success
k = 0:10; % range of possible number of successes

prob_mass = nbinpdf(k, r, p);
143 chars
6 lines

This will return a vector prob_mass with the probability mass function for the negative binomial distribution with parameters r and p evaluated at the values in k.

To generate a random sample from the negative binomial distribution with given parameters, use the nbinrnd function:

main.m
rng(0); % for reproducibility
r = 5; % number of failures
p = 0.3; % probability of success
n_samples = 10; % number of samples to generate

samples = nbinrnd(r, p, n_samples, 1);
180 chars
7 lines

This will return a vector samples with n_samples random samples from the negative binomial distribution with parameters r and p. The rng function is used to set the seed for the random number generator, for reproducibility.

gistlibby LogSnag