Mercurial > hg > octave-lojdl
changeset 15686:9671baab36c4
powerset: always return a cell array, even when set is empty. Augmented documentation and new tests.
author | Carnë Draug <carandraug+dev@gmail.com> |
---|---|
date | Thu, 15 Nov 2012 23:02:11 +0000 |
parents | 126285fce876 |
children | 0f924f0b0be3 |
files | scripts/set/powerset.m |
diffstat | 1 files changed, 19 insertions(+), 6 deletions(-) [+] |
line wrap: on
line diff
--- a/scripts/set/powerset.m +++ b/scripts/set/powerset.m @@ -19,11 +19,17 @@ ## -*- texinfo -*- ## @deftypefn {Function File} {} powerset (@var{a}) ## @deftypefnx {Function File} {} powerset (@var{a}, "rows") +## Compute the powerset (all subsets) of the set @var{a}. ## -## Return a cell array containing all subsets of the set @var{a}. +## The set @var{a} must be a numerical matrix or a cell array of strings. The +## output will always be a cell array of either vectors or strings. ## +## With the optional second argument @code{"rows"}, each row of the set @var{a} +## is considered one element of the set. As a result, @var{a} must then be a +## numerical 2D matrix. +## +## @seealso{unique, union, setxor, setdiff, ismember} ## @end deftypefn -## @seealso{unique, union, setxor, setdiff, ismember} function p = powerset (a, byrows_arg) @@ -31,7 +37,7 @@ if (nargin == 2) if (! strcmpi (byrows_arg, "rows")) - error ('powerset: expecting third argument to be "rows"'); + error ('powerset: expecting second argument to be "rows"'); elseif (iscell (a)) warning ('powerset: "rows" not valid for cell arrays'); else @@ -40,6 +46,9 @@ elseif (nargin != 1) print_usage (); endif + if (iscell (a) && ! iscellstr (a)) + error ("powerset: cell arrays can only used for character strings"); + endif if (byrows) a = unique (a, byrows_arg); @@ -50,7 +59,7 @@ endif if (n == 0) - p = []; + p = {}; else if (n > 32) error ("powerset: not implemented for more than 32 elements"); @@ -77,8 +86,12 @@ endfunction -%!test +%!shared c, p %! c = sort (cellstr ({ [], [1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3]})); %! p = sort (cellstr (powerset ([1, 2, 3]))); -%! assert (p, c); +%!assert (p, c); +%! c = sort (cellstr ({ [], [1:3], [2:4], [3:5], [1:3; 2:4], [1:3; 3:5], [2:4; 3:5], [1:3; 2:4; 3:5]})); +%! p = sort (cellstr (powerset ([1:3;2:4;3:5], "rows"))); +%!assert (p,c); +%!assert (powerset([]), {}); # always return a cell array