function bincoeff=bincoeff(n,r) % Calculates the binomial coefficient which represents the number of % possible orders of drawing exactly r red balls in n draws. % Tomas Olofsson. Dec 2004 if r<0 bincoeff=0; return end if r>n bincoeff=0; return end if n<21 % If n larger, we will have some difficulties with the precision. bincoeff=factorial(n)/(factorial(r)*factorial(n-r)); else bincoeff=1; % A loop in which the computations are organized to avoid overflow. for k=r-1:-1:0 bincoeff=bincoeff*(n-k)/(1+k); end end