function c = poly(x)
%MATLAB Code Generation Library Function

%   Limitations:
%   1. This version does not discard non-finite x-values.
%   2. Complex input always results in complex output.

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

eml_invariant(nargin > 0, ...
    'MATLAB:minrhs');
eml_invariant(isa(x,'float'), ...
    'Coder:toolbox:unsupportedClass','poly',class(x));
if eml_is_const(isvector(x)) && isvector(x)
    c = vector_poly(x);
else
    eml_invariant(eml_ndims(x) == 2, ...
        'Coder:toolbox:poly_3', ...
        'IfNotConst','Fail');
    eml_invariant(isscalar(x) || ~isvector(x), ...
        'Coder:toolbox:poly_vsizeMatrixIsVector');
    eml_invariant(size(x,1) == size(x,2), ...
        'MATLAB:poly:InputSize');
    % Characteristic polynomial (square x)
    c = vector_poly(eig(x));
end

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

function c = vector_poly(x)
% POLY for the vector input case.
n = cast(numel(x),coder.internal.indexIntClass);
for j = 1:n
    if ~isfinite(x(j))
        coder.internal.error('Coder:toolbox:nonfiniteValuesNotSupported');
    end
end
c = coder.nullcopy(eml_expand(coder.internal.scalarEg(x),[1,n+1]));
c(1) = 1;
for j = 1:n
    c(j+1) = -x(j)*c(j);
    for k = j:-1:2
        c(k) = c(k) - x(j)*c(k-1);
    end
end

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