function [b,tf] = rmoutliers(a,varargin)
%MATLAB Code Generation Library Function

%   Limitations:
%   Requires variable-sizing
%   Datetime sample points and timetables with datetime rowtimes are not 
%   supported for movmean and movmedian methods.

%   Copyright 2018-2023 The MathWorks,Inc.
%#codegen

coder.inline('always');
narginchk(1,inf);
coder.internal.prefer_const(varargin);
coder.internal.assert(ismatrix(a),'MATLAB:rmoutliers:NDArrays');
coder.internal.assert(~issparse(a), 'Coder:toolbox:SparseNotSupported',mfilename);
[method,wl,p,sp,maxno,minno,dim,dataVars] = outlierFunParser('rmoutliers',a,varargin{:});

if istabular(a)
    outLocTmp = coder.internal.applyToTableVariables(a,@(T) ...
        validateAndLocateOutliers(T,coder.internal.indexInt(1),method,wl,...
        p,sp,maxno,[]),dataVars,false,true,true,'','MATLAB:rmoutliers:DataVariablesTableSubscript');
    if isempty(outLocTmp) && height(a)~=0
        outLoc = false(height(a),1);
    else
        outLoc = outLocTmp;
    end
else
    % dim passed into rmoutliers determines how the outliers are removed.
    % Always locate outliers with first non-singleton dimension.
    locDim = coder.internal.preferConstNonSingletonDim(a);
    outLoc = locateoutliers(a,locDim,method,wl,p,sp,maxno,[]);
end

if coder.const(dim == 1)
    tf = sum(outLoc,2) >= minno; % Determine which rows to remove.
    b = a(~tf,:);
else
    tf = sum(outLoc,1) >= minno; % Determine which columns to remove.
    b = a(:,~tf);
end

%--------------------------------------------------------------------------

function tf = validateAndLocateOutliers(a,dim,...
    method,wl,p,sp,maxoutliers,replace)
coder.inline('always');
coder.internal.prefer_const(dim,method,wl,p,sp,maxoutliers,replace);
validateattributes(a,{'single','double','table'},{'real'},mfilename,'A',1);
coder.internal.assert(iscolumn(a) || isempty(a),'MATLAB:isoutlier:NonColumnTableVar');
tf = locateoutliers(a,dim,method,...
    wl,p,sp,maxoutliers,replace);
