7017
|
1 ## Copyright (C) 2000, 2006, 2007 Paul Kienzle |
5820
|
2 ## |
|
3 ## This file is part of Octave. |
|
4 ## |
|
5 ## Octave is free software; you can redistribute it and/or modify it |
|
6 ## under the terms of the GNU General Public License as published by |
7016
|
7 ## the Free Software Foundation; either version 3 of the License, or (at |
|
8 ## your option) any later version. |
5820
|
9 ## |
|
10 ## Octave is distributed in the hope that it will be useful, but |
|
11 ## WITHOUT ANY WARRANTY; without even the implied warranty of |
|
12 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU |
|
13 ## General Public License for more details. |
|
14 ## |
|
15 ## You should have received a copy of the GNU General Public License |
7016
|
16 ## along with Octave; see the file COPYING. If not, see |
|
17 ## <http://www.gnu.org/licenses/>. |
5820
|
18 |
|
19 ## -*- texinfo -*- |
6248
|
20 ## @deftypefn {Function File} {} intersect (@var{a}, @var{b}) |
|
21 ## @deftypefnx {Function File} {[@var{c}, @var{ia}, @var{ib}] =} intersect (@var{a}, @var{b}) |
5820
|
22 ## |
|
23 ## Return the elements in both @var{a} and @var{b}, sorted in ascending |
|
24 ## order. If @var{a} and @var{b} are both column vectors return a column |
|
25 ## vector, otherwise return a row vector. |
|
26 ## |
|
27 ## Return index vectors @var{ia} and @var{ib} such that @code{a(ia)==c} and |
|
28 ## @code{b(ib)==c}. |
|
29 ## |
|
30 ## @end deftypefn |
|
31 ## @seealso{unique, union, setxor, setdiff, ismember} |
|
32 |
|
33 function [c, ia, ib] = intersect (a, b) |
|
34 if (nargin != 2) |
6046
|
35 print_usage (); |
5820
|
36 endif |
|
37 |
|
38 if (isempty (a) || isempty (b)) |
|
39 c = ia = ib = []; |
|
40 else |
|
41 ## form a and b into sets |
|
42 [a, ja] = unique (a); |
|
43 [b, jb] = unique (b); |
|
44 |
5821
|
45 c = [a(:); b(:)]; |
|
46 [c, ic] = sort (c); ## [a(:);b(:)](ic) == c |
5820
|
47 |
6825
|
48 if (iscellstr (c)) |
|
49 ii = find (strcmp (c(1:end-1), c(2:end))); |
|
50 else |
|
51 ii = find (c(1:end-1) == c(2:end)); |
|
52 endif |
5820
|
53 |
|
54 c = c(ii); ## The answer |
|
55 ia = ja(ic(ii)); ## a(ia) == c |
5821
|
56 ib = jb(ic(ii+1) - length (a)); ## b(ib) == c |
5820
|
57 |
|
58 |
5821
|
59 if (size (b, 1) == 1 || size (a, 1) == 1) |
5820
|
60 c = c.'; |
|
61 endif |
|
62 endif |
|
63 |
|
64 endfunction |
|
65 |
|
66 |
|
67 %!# Test the routine for index vectors ia and ib |
|
68 %!test |
|
69 %! a = [3 2 4 5 7 6 5 1 0 13 13]; |
|
70 %! b = [3 5 12 1 1 7]; |
|
71 %! [c,ia,ib] = intersect(a,b); |
|
72 %! assert( c,[1 3 5 7]); |
|
73 %! assert(ia,[8 1 7 5]); |
|
74 %! assert(ib,[5 1 2 6]); |
|
75 %! assert(a(ia),c); |
|
76 %! assert(b(ib),c); |