1 ## Copyright (C) 1994-2012 John W. Eaton
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} {} union (@var{a}, @var{b})
22 ## @deftypefnx {Function File} {} union (@var{a}, @var{b}, "rows")
23 ## Return the set of elements that are in either of the sets @var{a} and
24 ## @var{b}. @var{a}, @var{b} may be cell arrays of string(s).
29 ## union ([1, 2, 4], [2, 3, 5])
30 ## @result{} [1, 2, 3, 4, 5]
34 ## If the optional third input argument is the string "rows" each row of
35 ## the matrices @var{a} and @var{b} will be considered an element of sets.
40 ## union ([1, 2; 2, 3], [1, 2; 3, 4], "rows")
47 ## @deftypefnx {Function File} {[@var{c}, @var{ia}, @var{ib}] =} union (@var{a}, @var{b})
49 ## Return index vectors @var{ia} and @var{ib} such that @code{a(ia)} and
50 ## @code{b(ib)} are disjoint sets whose union is @var{c}.
52 ## @seealso{intersect, setdiff, unique}
57 function [y, ia, ib] = union (a, b, varargin)
59 if (nargin < 2 || nargin > 3)
63 [a, b] = validargs ("union", a, b, varargin{:});
67 na = numel (a); nb = numel (b);
68 if (size (a, 1) == 1 || size (b, 1) == 1)
73 na = rows (a); nb = rows (b);
77 y = unique (y, varargin{:});
79 [y, i] = unique (y, varargin{:});
86 %!assert(all (all (union ([1, 2, 4], [2, 3, 5]) == [1, 2, 3, 4, 5])));
88 %!assert(all (all (union ([1; 2; 4], [2, 3, 5]) == [1, 2, 3, 4, 5])));
90 %!assert(all (all (union ([1, 2, 3], [5; 7; 9]) == [1, 2, 3, 5, 7, 9])));
94 %!error union (1, 2, 3);
97 %! a = [3, 1, 4, 1, 5]; b = [1, 2, 3, 4];
98 %! [y, ia, ib] = union (a, b.');
99 %! assert(y, [1, 2, 3, 4, 5]);
100 %! assert(y, sort([a(ia), b(ib)]));