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} {} intersect (@var{a}, @var{b})
22 ## @deftypefnx {Function File} {[@var{c}, @var{ia}, @var{ib}] =} intersect (@var{a}, @var{b})
24 ## Return the elements in both @var{a} and @var{b}, sorted in ascending
25 ## order. If @var{a} and @var{b} are both column vectors return a column
26 ## vector, otherwise return a row vector.
27 ## @var{a}, @var{b} may be cell arrays of string(s).
29 ## Return index vectors @var{ia} and @var{ib} such that @code{a(ia)==c} and
33 ## @seealso{unique, union, setxor, setdiff, ismember}
35 function [c, ia, ib] = intersect (a, b, varargin)
37 if (nargin < 2 || nargin > 3)
41 [a, b] = validargs ("intersect", a, b, varargin{:});
43 if (isempty (a) || isempty (b))
46 ## form a and b into sets
48 [a, ja] = unique (a, varargin{:});
49 [b, jb] = unique (b, varargin{:});
51 a = unique (a, varargin{:});
52 b = unique (b, varargin{:});
57 [c, ic] = sortrows (c);
58 ii = find (all (c(1:end-1,:) == c(2:end,:), 2));
63 [c, ic] = sort (c); ## [a(:);b(:)](ic) == c
65 ii = find (strcmp (c(1:end-1), c(2:end)));
67 ii = find (c(1:end-1) == c(2:end));
74 ia = ja(ic(ii)); ## a(ia) == c
75 ib = jb(ic(ii+1) - len_a); ## b(ib) == c
78 if (nargin == 2 && (size (b, 1) == 1 || size (a, 1) == 1))
86 %!# Test the routine for index vectors ia and ib
88 %! a = [3 2 4 5 7 6 5 1 0 13 13];
89 %! b = [3 5 12 1 1 7];
90 %! [c,ia,ib] = intersect(a,b);
91 %! assert(c,[1 3 5 7]);
92 %! assert(ia,[8 1 7 5]);
93 %! assert(ib,[5 1 2 6]);
97 %! a = [1,1,2;1,4,5;2,1,7];
98 %! b = [1,4,5;2,3,4;1,1,2;9,8,7];
99 %! [c,ia,ib] = intersect(a,b,'rows');
100 %! assert(c,[1,1,2;1,4,5]);
103 %! assert(a(ia,:),c);
104 %! assert(b(ib,:),c);
106 %! a = [1 1 1 2 2 2];
107 %! b = [1 2 3 4 5 6];
108 %! c = intersect(a,b);
111 %! a = [1 2 3 4; 5 6 7 8; 9 10 11 12];
112 %! [b, ia, ib] = intersect(a, a, "rows");
114 %! assert(ia, [1:3]');
115 %! assert(ib, [1:3]');