function [a,b] = padecoef(T,n)
%MATLAB Code Generation Library Function

%   Limitations:
%   The case T == 0 is not supported because the output in MATLAB has a 
%   different size when T == 0 and n > 0 (scalar) than when T > 0 and n > 0
%   (vector of length n+1).  Although supporting this degenerate case is
%   possible with variable sizing, it seems unlikely any user would want to
%   introduce a variable size result from a fixed size input in order to
%   support this special case.

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

eml_invariant(nargin > 0,'MATLAB:minrhs');
if nargin == 1
    n = 1;
end
coder.internal.prefer_const(n);
eml_invariant(eml_is_const(n) || eml_option('VariableSizing'), ...
    'Coder:toolbox:padecoef_2', ...
    'IfNotConst','Fail');
eml_invariant(coder.internal.isBuiltInNumeric(n) && ...
    isscalar(n) && isreal(n) && ...
    n >= 0 && n == floor(n), ...
    'Coder:toolbox:nMustBeRealPosIntScalar');
eml_invariant(isscalar(T), ...
    'Coder:toolbox:padecoef_4', ...
    'IfNotConst','Fail');
eml_invariant(isa(T,'float'), ...
    'Coder:toolbox:padecoef_5', ...
    'IfNotConst','Fail');
a = coder.nullcopy(eml_expand(coder.internal.scalarEg(T),[1,n+1]));
b = coder.nullcopy(a);
if T < 0
    coder.internal.error('Controllib:general:NegativeTorN');
    a(:) = coder.internal.nan;
    b(:) = coder.internal.nan;
elseif T == 0
    % This case not supported because the output when T==0 (a = b = 1) has
    % a different size than when T>0 and N>0.
    coder.internal.error('Coder:MATLAB:padecoef_TZeroNotSupported');
    a(:) = coder.internal.nan;
    b(:) = coder.internal.nan;
else
    % The coefficients of the Pade approximation are given by the
    % recursion   h[k+1] = (N-k)/(2*N-k)/(k+1) * h[k],  h[0] = 1
    % and
    %     exp(-T*s) == Sum { h[k] (-T*s)^k } / Sum { h[k] (T*s)^k }
    a(end) = 1;
    b(end) = 1;
    for k = n:-1:1
        fact = coder.internal.div(coder.internal.div(T*k,n+k),n-k+1);
        a(k) = (-fact) * a(k+1);
        b(k) = fact * b(k+1);
    end
    a = coder.internal.div(a,b(1));
    b = coder.internal.div(b,b(1));
end
