Anonymous user
Evaluate binomial coefficients: Difference between revisions
→{{header|MATLAB}}: works fine with Octave, too. Verified with Octave 3.4.3. Alternative implementations added.
(→{{header|PHP}}: alternate version) |
(→{{header|MATLAB}}: works fine with Octave, too. Verified with Octave 3.4.3. Alternative implementations added.) |
||
Line 683:
(Local) Out[1]= 10</lang>
=={{header|MATLAB}} / {{header|Octave}}==
This is a built-in function in MATLAB called "nchoosek(n,k)". But, this will only work for scalar inputs. If "n" is a vector then "nchoosek(v,k)" finds all combinations of choosing "k" elements out of the "v" vector (see [[Combinations#MATLAB]]).
Solution:
<lang MATLAB>>> nchoosek(5,3)
ans =
10</lang>
Alternative implementations are:
<lang MATLAB>function r = binomcoeff1(n,k)
r = diag(rot90(pascal(n+1))); % vector of all binomial coefficients for order n
r = r(k);
end; </lang>
<lang MATLAB>function r = binomcoeff2(n,k)
prod((n-k+1:n)./(1:k))
end; </lang>
<lang MATLAB>function r = binomcoeff3(n,k)
m = pascal(max(n-k,k)+1);
r = m(n-k+1,k+1);
end; </lang>
If you want a vectorized function that returns multiple binomial coefficients given vector inputs, you must define that function yourself. A sample implementation is given below. This function takes either scalar or vector inputs for "n" and "v" and returns either a: scalar, vector, or matrix. Where the columns are indexed by the "k" vector and the rows indexed by the "n" vector.
|