function [b,ndx,pos] = unique(a,flag)
%UNIQUE Set unique.
%   UNIQUE(A) for the array A returns the same values as in A but
%   with no repetitions.  A will also be sorted.  A can be a cell
%   array of strings.
%
%   UNIQUE(A,'rows') for the matrix A returns the unique rows of A.
%
%   [B,I,J] = UNIQUE(...) also returns index vectors I and J such
%   that B = A(I) and A = B(J) (or B = A(I,:) and A = B(J,:)).
%   
%   See also UNION, INTERSECT, SETDIFF, SETXOR, ISMEMBER.

%   Copyright 1984-2000 The MathWorks, Inc. 
%   $Revision: 1.21 $  $Date: 2000/06/01 04:40:02 $

%   Cell array implementation in @cell/unique.m
  
if nargin==1 | isempty(flag),
  % Convert matrices and rectangular empties into columns
  if length(a) ~= prod(size(a)) | (isempty(a) & any(size(a)))
     a = a(:);
  end
  [b,ndx] = sort(a);
  % d indicates the location of matching entries
  d = b((1:end-1)')==b((2:end)');
  b(find(d)) = [];
  if nargout==3, % Create position mapping vector
    pos = zeros(size(a));
    pos(ndx) = cumsum([1;~d(:)]);
  end
else
  if ~isstr(flag) | ~strcmp(flag,'rows'), error('Unknown flag.'); end
  [b,ndx] = sortrows(a);
  [m,n] = size(a);
  if m > 1 & n ~= 0
    % d indicates the location of matching entries
    d = b(1:end-1,:)==b(2:end,:);
  else
    d = zeros(m-1,n);
  end
  d = all(d,2);
  b(find(d),:) = [];
  if nargout==3, % Create position mapping vector
    pos(ndx) = cumsum([1;~d]);
    pos = pos';
  end
end

ndx(find(d)) = [];
