Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get binomial coefficients

In an attempt to vectorize a particular piece of Matlab code, I could not find a straightforward function to generate a list of the binomial coefficients. The best I could find was nchoosek, but for some inexplicable reason this function only accepts integers (not vectors of integers). My current solution looks like this:

mybinom = @(n) arrayfun(@nchoosek, n*ones(1,n), 1:n)

This generates the set of binomial coefficients for a given value of n. However, since the binomial coefficients are always symmetric, I know that I am doing twice as much work as necessary. I'm sure that I could create a solution that exploits the symmetry, but I'm sure that it would be at the expense of readability.

Is there a more elegant solution than this, perhaps using a Matlab function that I am not aware of? Note that I am not interested in using the symbolic toolbox.

like image 916
nispio Avatar asked Sep 16 '25 18:09

nispio


1 Answers

If you want to minimize operations you can go along these lines:

n = 6;

k = 1:n;
result = [1 cumprod((n-k+1)./k)]

>> result

result =

     1     6    15    20    15     6     1

This requires very few operations per coefficient, because each cofficient is obtained exploiting the previously computed one.

You can reduce the number of operations by approximately half if you take into account the symmetry:

m1 = floor(n/2);
m2 = ceil(n/2);
k = 1:m2;
result = [1 cumprod((n-k+1)./k)];
result(n+1:-1:m1+2) = result(1:m2);
like image 171
Luis Mendo Avatar answered Sep 18 '25 12:09

Luis Mendo