1 ## Copyright (C) 2010 Soren Hauberg <soren@hauberg.org>
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
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
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/>.
17 ## @deftypefn {Function File} {@var{c} =} combnk (@var{data}, @var{k})
18 ## Return all combinations of @var{k} elements in @var{data}.
21 function retval = combnk (data, k)
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");
34 retval = resize (data, 0, k);
38 retval = __combnk__ (data, k);
41 ## For some odd reason Matlab seems to treat strings differently compared to other data-types...
43 retval = flipud (retval);
47 function retval = __combnk__ (data, k)
48 ## Recursion stopping criteria
60 C = __combnk__ (data ((j+1):end), k-1);
61 C = cat (2, repmat (data (j), rows (C), 1), C);
70 %! c = combnk (1:5, 2);
71 %! disp ("All pairs of integers between 1 and 5:");
75 %! c = combnk (1:3, 2);
76 %! assert (c, [1, 2; 1, 3; 2, 3]);
79 %! c = combnk (1:3, 6);
80 %! assert (isempty (c));
83 %! c = combnk ({1, 2, 3}, 2);
84 %! assert (c, {1, 2; 1, 3; 2, 3});
87 %! c = combnk ("hello", 2);
88 %! assert (c, ["lo"; "lo"; "ll"; "eo"; "el"; "el"; "ho"; "hl"; "hl"; "he"]);