Efficient Matlab implementation of Multinomial Coefficient

后端 未结 4 845
栀梦
栀梦 2021-02-11 07:35

I want to calculate the multinomial coefficient:

\"enter

where it is satisifed

相关标签:
4条回答
  • 2021-02-11 07:52

    Sorry to resurrect an old post, but for future searchers, you should almost certainly just write your multinomial coefficient as a product of binomial coefficients and use a built-in method to compute binomial coefficients (or write your own, either using Pascal's triangle or another method). The relevant formula appears in the first paragraph of the Wikipedia section on multinomial coefficients. (I'd write it here, but there doesn't seem to be a way to render LaTeX.)

    Another benefit of this approach is that it's as good as you can possibly get about overflow since the factors are all integers. There's no intrinsic need to divide when computing multinomial coefficients.

    0 讨论(0)
  • 2021-02-11 07:59

    using the tip provided by @jemidiah,

    and here is the code

    function c = multicoeff (k), 
        c = 1; 
        for i=1:length(k), 
          c = c* bincoeff(sum(k(1:i)),k(i)); 
        end; 
    end
    

    and some usage examples:

    octave:88> multicoeff([2 2 2])
    ans =  90
    octave:89> factorial(6)/(factorial(2)*factorial(2)*factorial(2))
    ans =  90
    octave:90> multicoeff([5 4 3])
    ans =  27720
    octave:91> factorial(12)/(factorial(5)*factorial(4)*factorial(3))
    ans =  27720
    
    0 讨论(0)
  • 2021-02-11 08:07

    Another approach is to use Yannis Manolopoulos iterative method. Suppose we have a vector k with the multinomial entries.

    function N = multicoeff (k),
      n=sum(k); 
      [_,imax]=max(k); 
      num=[n:-1:n-k(imax)-1]; 
      den=[]; k(imax)=[]; 
      for i=1:length(k), den=[den 1:k(i)]; endfor; 
      N=prod(num./den);
    endfunction
    

    example

    octave:2> k = [5 4 3];
    octave:3> multicoeff (k)
    ans =  27720
    

    Reference: Yannis Manolopoulos. Binomial coefficient computation. ACM SIGCSE Bulletin, 34(4):65, December 2002. doi: 10.1145/820127.820168. URL https: //doi.org/10.1145/820127.820168.

    0 讨论(0)
  • 2021-02-11 08:12

    Why not use this? It's fast and doesn't suffer from overflow:

    N = prod([1:n]./[1:n0 1:n1 1:n2]);
    
    0 讨论(0)
提交回复
热议问题