1 ## Copyright (C) 2000-2012 Paul Kienzle
2 ## Copyright (C) 2008-2009 Jaroslav Hajek
4 ## This file is part of Octave.
6 ## Octave is free software; you can redistribute it and/or modify it
7 ## under the terms of the GNU General Public License as published by
8 ## the Free Software Foundation; either version 3 of the License, or (at
9 ## your option) any later version.
11 ## Octave is distributed in the hope that it will be useful, but
12 ## WITHOUT ANY WARRANTY; without even the implied warranty of
13 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 ## General Public License for more details.
16 ## You should have received a copy of the GNU General Public License
17 ## along with Octave; see the file COPYING. If not, see
18 ## <http://www.gnu.org/licenses/>.
21 ## @deftypefn {Function File} {} setdiff (@var{a}, @var{b})
22 ## @deftypefnx {Function File} {} setdiff (@var{a}, @var{b}, "rows")
23 ## @deftypefnx {Function File} {[@var{c}, @var{i}] =} setdiff (@var{a}, @var{b})
24 ## Return the elements in @var{a} that are not in @var{b}, sorted in
25 ## ascending order. If @var{a} and @var{b} are both column vectors
26 ## return a column vector, otherwise return a row vector.
27 ## @var{a}, @var{b} may be cell arrays of string(s).
29 ## Given the optional third argument @samp{"rows"}, return the rows in
30 ## @var{a} that are not in @var{b}, sorted in ascending order by rows.
32 ## If requested, return @var{i} such that @code{c = a(i)}.
33 ## @seealso{unique, union, intersect, setxor, ismember}
36 ## Author: Paul Kienzle
39 function [c, i] = setdiff (a, b, varargin)
41 if (nargin < 2 || nargin > 3)
45 [a, b] = validargs ("setdiff", a, b, varargin{:});
49 [c, i] = unique (a, "rows");
51 c = unique (a, "rows");
53 if (! isempty (c) && ! isempty (b))
54 ## Form a and b into combined set.
55 b = unique (b, "rows");
56 [dummy, idx] = sortrows ([c; b]);
57 ## Eliminate those elements of a that are the same as in b.
58 dups = find (all (dummy(1:end-1,:) == dummy(2:end,:), 2));
70 if (! isempty (c) && ! isempty (b))
71 ## Form a and b into combined set.
73 [dummy, idx] = sort ([c(:); b(:)]);
74 ## Eliminate those elements of a that are the same as in b.
75 if (iscellstr (dummy))
76 dups = find (strcmp (dummy(1:end-1), dummy(2:end)));
78 dups = find (dummy(1:end-1) == dummy(2:end));
84 ## Reshape if necessary.
85 if (size (c, 1) != 1 && size (b, 1) == 1)
93 %!assert(setdiff(["bb";"zz";"bb";"zz"],["bb";"cc";"bb"],"rows"), "zz")
94 %!assert(setdiff(["b";"z";"b";"z"],["b";"c";"b"],"rows"), "z")
95 %!assert(setdiff(["b";"z";"b";"z"],["b";"c";"b"]), "z")
96 %!assert(setdiff([1, 1; 2, 2; 3, 3; 4, 4], [1, 1; 2, 2; 4, 4], "rows"), [3 3])
97 %!assert(setdiff([1; 2; 3; 4], [1; 2; 4], "rows"), 3)
98 %!assert(setdiff([1, 2; 3, 4], [1, 2; 3, 6], "rows"), [3, 4])
99 %!assert(setdiff({"one","two";"three","four"},{"one","two";"three","six"}), {"four"})
102 %! a = [3, 1, 4, 1, 5]; b = [1, 2, 3, 4];
103 %! [y, i] = setdiff (a, b.');