function [c,ia,ib] = union(a,b,flag)
%UNION  Set union.
%   UNION(A,B) when A and B are vectors returns the combined values
%   from A and B but with no repetitions.  The result will be sorted.
%   A and B can be cell arrays of strings.
%
%   UNION(A,B,'rows') when A are B are matrices with the same number of
%   columns returns the combined rows from A and B with no repetitions.
%
%   [C,IA,IB] = UNION(...) also returns index vectors IA and IB such
%   that C is a sorted combination of the elements A(IA) and B(IB) 
%   (or A(IA,:) and B(IB,:)).
%
%   See also UNIQUE, INTERSECT, SETDIFF, SETXOR, ISMEMBER.

%   Copyright 1984-2000 The MathWorks, Inc. 
%   $Revision: 1.17 $  $Date: 2000/06/01 04:39:58 $

%   Cell array implementation in @cell/union.m

error(nargchk(2,3,nargin));

if nargin==2
  if length(a)~=prod(size(a)) | length(b)~=prod(size(b))
    error('A and B must be vectors or ''rows'' must be specified.');
  end
  rowvec = ~((size(a,1)>1 & size(b,2)<=1) | (size(b,1)>1 & size(a,2)<=1));
  if size(a,2)>1, a = a.'; end
  if size(b,2)>1, b = b.'; end
  [c,ndx] = unique([a;b]);
  if rowvec, c = c.'; ndx = ndx.'; end
  n = prod(size(a));
else
  % Automatically pad strings with spaces
  if isstr(a) & isstr(b),
    if size(a,2) > size(b,2), 
      b = [b repmat(' ',size(b,1),size(a,2)-size(b,2))];
    end
    if size(a,2) < size(b,2), 
      a = [a repmat(' ',size(a,1),size(b,2)-size(a,2))];
    end
  end

  if size(a,2)~=size(b,2), 
    error('A and B must have the same number of columns.');
  end
  
  [c,ndx] = unique([a;b],flag);
  n = size(a,1);
end

if nargout>1, % Create index vectors.
  d = ndx > n;
  ia = ndx(~d);
  ib = ndx(d)-n;
end
