function varargout = ndgrid(varargin)
%MATLAB Code Generation Library Function

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

eml_allow_enum_inputs;
eml_invariant(nargin > 0 && (nargin == 1 || nargout <= nargin), ...
    'MATLAB:ndgrid:NotEnoughInputs');
if nargin == 1 && nargout <= 1
    varargout{1} = varargin{1}(:);
    return
end
ONE = coder.internal.indexInt(1);
ND = coder.const(coder.internal.indexInt(eml_max(nargin,nargout)));
% Compute output size.
outsz = cell(1,ND);
if nargin == 1
    n = coder.internal.indexInt(numel(varargin{1}));    
    for k = coder.unroll(ONE:ND)
        outsz{k} = n;
    end
else
    for k = coder.unroll(ONE:ND)
        outsz{k} = coder.internal.indexInt(numel(varargin{k}));    
    end
end
% Make a "ghost" array to use with eml_expand.
szeg = coder.nullcopy(false(outsz{:}));
if coder.isRowMajor
    firstDim = ONE;
else
    firstDim = coder.internal.indexInt(eml_ndims(szeg));
end
for k = coder.unroll(ONE:nargout)
    if nargin == 1
        vin = varargin{1};
    else
        vin = varargin{k};
    end
    varargout{k} = coder.nullcopy(eml_expand( ...
        coder.internal.scalarEg(vin),size(szeg)));
    varargout{k} = looper(varargout{k},vin(:),k,firstDim);
end

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

function y = looper(y,x,repDim,dim,varargin)
% Replicate vector X(:) along dimension REPDIM of Y.
% Assumes that size(Y,REPDIM) == numel(X).
eml_allow_enum_inputs;
coder.inline('always');
coder.internal.prefer_const(repDim,dim);
ND = coder.internal.indexInt(eml_ndims(y));
ONE = coder.internal.indexInt(1);
if repDim > ND
    %This happens when there are singleton trailing dimensions
    y(:) = x(1);
elseif dim >= 1 && dim <= ND
    for k = ONE:size(y,dim)
        if coder.isRowMajor
            y = looper(y,x,repDim,dim + 1,varargin{:},k);
        else
            y = looper(y,x,repDim,dim - 1,k,varargin{:});
        end
    end
else
    y(varargin{:}) = x(varargin{repDim});
end

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