function [p,S,mu] = polyfit(x,y,n)
%MATLAB Code Generation Library Function

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

coder.inline('never'); % For clarity in the generated code.
coder.internal.assert(nargin == 3,'MATLAB:minrhs');
coder.internal.prefer_const(n);
coder.internal.assert(coder.internal.isConst(n) || ...
    eml_option('VariableSizing'), ...
    'Coder:toolbox:polyfit_2', ...
    'IfNotConst','Fail');
coder.internal.assert(coder.internal.isBuiltInNumeric(n) && ...
    isreal(n) && isscalar(n), ...
    'Coder:toolbox:polyfit_3', ...
    'IfNotConst','Fail');
coder.internal.assert( ...
    coder.internal.isConst(isvector(x)) && ...
    coder.internal.isConst(isvector(y)), ...
    'Coder:toolbox:polyfit_4', ...
    'IfNotConst','Fail');
coder.internal.assert(isvector(x) && isvector(y), ...
    'Coder:toolbox:polyfit_5', ...
    'IfNotConst','Fail');
coder.internal.assert(length(x) == length(y), ...
    'MATLAB:polyfit:XYSizeMismatch');
if nargout > 2
    mu = [mean(x); std(x)];
    x = coder.internal.div(x-mu(1),mu(2));
end
V = coder.internal.vander(x,n);
if nargout > 1
    [p1,rr,R] = coder.internal.qrsolve(V,y(:),false,false);
else
    [p1,rr] = coder.internal.qrsolve(V,y(:),false,false);
end
if n >= numel(x)
    if ~coder.setwarningflag
        coder.internal.warning('MATLAB:polyfit:PolyNotUnique');
    end
elseif rr <= n
    if ~coder.setwarningflag
        if nargout > 2
            coder.internal.warning('MATLAB:polyfit:RepeatedPoints');
        else
            coder.internal.warning('MATLAB:polyfit:RepeatedPointsOrRescale');
        end
    end
end
if nargout > 1
    r = y(:) - V*p1;
    % S is a structure containing three elements: the triangular factor
    % from a QR decomposition of the Vandermonde matrix, the degrees of
    % freedom and the norm of the residuals.
    S.R = R;
    S.df = eml_max(0,length(y) - (n+1));
    S.normr = norm(r);
end
p = p1.'; % Polynomial coefficients are row vectors by convention.
