]> Creatis software - CreaPhase.git/blob - octave_packages/statistics-1.1.3/combnk.m
Add a useful package (from Source forge) for octave
[CreaPhase.git] / octave_packages / statistics-1.1.3 / combnk.m
1 ## Copyright (C) 2010 Soren Hauberg <soren@hauberg.org>
2 ##
3 ## This program is free software; you can redistribute it and/or modify it under
4 ## the terms of the GNU General Public License as published by the Free Software
5 ## Foundation; either version 3 of the License, or (at your option) any later
6 ## version.
7 ##
8 ## This program is distributed in the hope that it will be useful, but WITHOUT
9 ## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
10 ## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
11 ## details.
12 ##
13 ## You should have received a copy of the GNU General Public License along with
14 ## this program; if not, see <http://www.gnu.org/licenses/>.
15
16 ## -*- texinfo -*-
17 ## @deftypefn {Function File} {@var{c} =} combnk (@var{data}, @var{k})
18 ## Return all combinations of @var{k} elements in @var{data}.
19 ## @end deftypefn
20
21 function retval = combnk (data, k)
22   ## Check input
23   if (nargin != 2)
24     print_usage;
25   elseif (! isvector (data))
26     error ("combnk: first input argument must be a vector");
27   elseif (!isreal (k) || k != round (k) || k < 0)
28     error ("combnk: second input argument must be a non-negative integer");
29   endif
30
31   ## Simple checks
32   n = numel (data);
33   if (k == 0 || k > n)
34     retval = resize (data, 0, k);
35   elseif (k == n)
36     retval = data (:).';
37   else
38     retval = __combnk__ (data, k);
39   endif
40
41   ## For some odd reason Matlab seems to treat strings differently compared to other data-types...
42   if (ischar (data))
43      retval = flipud (retval);
44   endif
45 endfunction
46
47 function retval = __combnk__ (data, k)
48   ## Recursion stopping criteria
49   if (k == 1)
50     retval = data (:);
51   else
52     ## Process data
53     n = numel (data);
54     if iscell (data)
55       retval = {};
56     else
57       retval = [];
58     endif
59     for j = 1:n
60       C = __combnk__ (data ((j+1):end), k-1);
61       C = cat (2, repmat (data (j), rows (C), 1), C);
62       if (!isempty (C))
63         retval = [retval; C];
64       endif
65     endfor
66   endif
67 endfunction
68
69 %!demo
70 %! c = combnk (1:5, 2);
71 %! disp ("All pairs of integers between 1 and 5:");
72 %! disp (c);
73
74 %!test
75 %! c = combnk (1:3, 2);
76 %! assert (c, [1, 2; 1, 3; 2, 3]);
77
78 %!test
79 %! c = combnk (1:3, 6);
80 %! assert (isempty (c));
81
82 %!test
83 %! c = combnk ({1, 2, 3}, 2);
84 %! assert (c, {1, 2; 1, 3; 2, 3});
85
86 %!test
87 %! c = combnk ("hello", 2);
88 %! assert (c, ["lo"; "lo"; "ll"; "eo"; "el"; "el"; "ho"; "hl"; "hl"; "he"]);