function range = getVarRange(v,asCat,excl)
%getVarRange Get the variable range for one variable.

% Inputs:
%    v is the variable
%    asCat indicates the variable should be treated as categorical
%    excl is an index into the excluded values

%   Copyright 2016-2017 The MathWorks, Inc.

v(excl,:) = [];
if asCat % create a list of the unique values
    if isa(v,'categorical')
        if isordinal(v)
            % Need all categories because combining ordinal arrays requires
            % an exact match
            range = v(1:0);
            vcats = categories(v);
            range(1:length(vcats),1) = vcats;
        else
            % For non-ordinal, get the values actually present in the
            % data, not the set of possible values.
            range = removecats(unique(v(:)));
        end
        range = range(~isundefined(range)); % empty if NaNs
        
    elseif iscellstr(v)
        [~,~,range] = grp2idx(strtrim(v));
    else
        % For classes other than categorical, the list of unique values is
        % also the list of possible values.  But get it in the same order as
        % what grp2idx defines for each class.
        [~,~,range] = grp2idx(v); % leaves NaN or '' out of glevels
    end
    if ~ischar(range)
        range = range(:)'; % force a row
    end
elseif isnumeric(v) || islogical(v) % find min and max
    range = [min(v,[],1)  max(v,[],1)]; % ignores NaNs unless all NaNs
else
    range = NaN(1,2);
end
end