function r = rank(varargin)
%MATLAB Code Generation Library Function

%   Copyright 1984-2015 The MathWorks, Inc.
%#codegen

coder.inline('always');
narginchk(1,2);
eml_invariant(isa(varargin{1},'float'), ...
    'Coder:toolbox:unsupportedClass','rank',class(varargin{1}));
irank = local_rank(varargin{:});
r = double(irank);

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

function irank = local_rank(A,tol)
coder.columnMajor;
irank = coder.internal.indexInt(0);
if ~isempty(A)
    s = svd(A);
    if nargin == 1
        tol = length(A)*eps(s(1));
    else
        eml_invariant(isa(tol,'float'), ...
            'Coder:toolbox:unsupportedClass','rank',class(tol));
        eml_invariant(isscalar(tol), ...
            'Coder:toolbox:rank_4', ...
            'IfNotConst','Fail');
    end
    ns = coder.internal.indexInt(numel(s));
    for k = 1:ns
        if s(k) > tol
            irank = irank + 1;
        else
            break
        end
    end
end

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