5820
|
1 ## Copyright (C) 2000 Paul Kienzle |
|
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 |
|
7 ## the Free Software Foundation; either version 2, or (at your option) |
|
8 ## any later version. |
|
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 |
|
16 ## along with Octave; see the file COPYING. If not, write to the Free |
|
17 ## Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA |
|
18 ## 02110-1301, USA. |
|
19 |
|
20 ## -*- texinfo -*- |
6248
|
21 ## @deftypefn {Function File} {} intersect (@var{a}, @var{b}) |
|
22 ## @deftypefnx {Function File} {[@var{c}, @var{ia}, @var{ib}] =} intersect (@var{a}, @var{b}) |
5820
|
23 ## |
|
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 ## |
|
28 ## Return index vectors @var{ia} and @var{ib} such that @code{a(ia)==c} and |
|
29 ## @code{b(ib)==c}. |
|
30 ## |
|
31 ## @end deftypefn |
|
32 ## @seealso{unique, union, setxor, setdiff, ismember} |
|
33 |
|
34 function [c, ia, ib] = intersect (a, b) |
|
35 if (nargin != 2) |
6046
|
36 print_usage (); |
5820
|
37 endif |
|
38 |
|
39 if (isempty (a) || isempty (b)) |
|
40 c = ia = ib = []; |
|
41 else |
|
42 ## form a and b into sets |
|
43 [a, ja] = unique (a); |
|
44 [b, jb] = unique (b); |
|
45 |
5821
|
46 c = [a(:); b(:)]; |
|
47 [c, ic] = sort (c); ## [a(:);b(:)](ic) == c |
5820
|
48 |
6825
|
49 if (iscellstr (c)) |
|
50 ii = find (strcmp (c(1:end-1), c(2:end))); |
|
51 else |
|
52 ii = find (c(1:end-1) == c(2:end)); |
|
53 endif |
5820
|
54 |
|
55 c = c(ii); ## The answer |
|
56 ia = ja(ic(ii)); ## a(ia) == c |
5821
|
57 ib = jb(ic(ii+1) - length (a)); ## b(ib) == c |
5820
|
58 |
|
59 |
5821
|
60 if (size (b, 1) == 1 || size (a, 1) == 1) |
5820
|
61 c = c.'; |
|
62 endif |
|
63 endif |
|
64 |
|
65 endfunction |
|
66 |
|
67 |
|
68 %!# Test the routine for index vectors ia and ib |
|
69 %!test |
|
70 %! a = [3 2 4 5 7 6 5 1 0 13 13]; |
|
71 %! b = [3 5 12 1 1 7]; |
|
72 %! [c,ia,ib] = intersect(a,b); |
|
73 %! assert( c,[1 3 5 7]); |
|
74 %! assert(ia,[8 1 7 5]); |
|
75 %! assert(ib,[5 1 2 6]); |
|
76 %! assert(a(ia),c); |
|
77 %! assert(b(ib),c); |