5827
|
1 ## Copyright (C) 2001 Rolf Fabian and Paul Kienzle |
|
2 ## |
|
3 ## This file is part of Octave. |
|
4 ## |
|
5 ## Octave is free software; you can redistribute it and/or modify it |
|
6 ## under the terms of the GNU General Public License as published by |
|
7 ## the Free Software Foundation; either version 2, or (at your option) |
|
8 ## any later version. |
|
9 ## |
|
10 ## Octave is distributed in the hope that it will be useful, but |
|
11 ## WITHOUT ANY WARRANTY; without even the implied warranty of |
|
12 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU |
|
13 ## General Public License for more details. |
|
14 ## |
|
15 ## You should have received a copy of the GNU General Public License |
|
16 ## along with Octave; see the file COPYING. If not, write to the Free |
|
17 ## Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA |
|
18 ## 02110-1301, USA. |
|
19 |
|
20 ## -*- texinfo -*- |
|
21 ## @deftypefn {Function File} {@var{c} =} nchoosek (@var{n}, @var{k}) |
|
22 ## |
|
23 ## Compute the binomial coeeficient or all combinations of @var{n}. |
|
24 ## If @var{n} is a scalar then, calculate the binomial coefficient |
|
25 ## of @var{n} and @var{k}, defined as |
|
26 ## |
|
27 ## @iftex |
|
28 ## @tex |
|
29 ## $$ |
|
30 ## {n \choose k} = {n (n-1) (n-2) \cdots (n-k+1) \over k!} |
|
31 ## $$ |
|
32 ## @end tex |
|
33 ## @end iftex |
|
34 ## @ifinfo |
|
35 ## |
|
36 ## @example |
|
37 ## @group |
|
38 ## / \ |
|
39 ## | n | n (n-1) (n-2) ... (n-k+1) |
|
40 ## | | = ------------------------- |
|
41 ## | k | k! |
|
42 ## \ / |
|
43 ## @end group |
|
44 ## @end example |
|
45 ## @end ifinfo |
|
46 ## |
|
47 ## If @var{n} is a vector generate all combinations of the elements |
|
48 ## of @var{n}, taken @var{k} at a time, one row per combination. The |
|
49 ## resulting @var{c} has size @code{[nchoosek (length (@var{n}), |
|
50 ## @var{k}), @var{k}]}. |
|
51 ## |
|
52 ## @end deftypefn |
|
53 |
|
54 ##AUTHORS Rolf Fabian <fabian@tu-cottbus.de> |
|
55 ## Paul Kienzle <pkienzle@users.sf.net> |
|
56 |
|
57 ## XXX FIXME XXX This function is identical to bincoeff for scalar |
|
58 ## values, and so should probably be combined with bincoeff. |
|
59 |
|
60 function A = nchoosek (v, k) |
|
61 |
|
62 n = length (v); |
|
63 |
|
64 if (n == 1) |
|
65 A = round (exp (sum (log (k+1:v)) - sum (log (2:v-k)))); |
|
66 elseif (k == 0) |
|
67 A = []; |
|
68 elseif (k == 1) |
|
69 A = v(:); |
|
70 elseif (k == n) |
|
71 A = v(:).'; |
|
72 else |
|
73 m = round (exp (sum (log (k:n-1)) - sum (log (2:n-k)))); |
|
74 A = [v(1)*ones(m,1), nchoosek(v(2:n),k-1); |
|
75 nchoosek(v(2:n),k)]; |
|
76 endif |
|
77 |
|
78 endfunction |