function ndx = sub2ind(siz,varargin)
%MATLAB Code Generation Library Function

%   Limitations:
%   1. PROD(SIZ) > INTMAX is not supported.

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

coder.inline('always');
eml_invariant(nargin >= 2,'MATLAB:minrhs');
eml_invariant(coder.internal.isBuiltInNumeric(siz), ...
    'Coder:toolbox:sub2ind_2');
eml_invariant(eml_is_const(size(siz)),'Coder:toolbox:sub2ind_3');
coder.internal.prefer_const(siz);
ndx = double(eml_sub2ind(coder.internal.indexInt(siz),varargin{:}));

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

function idx = eml_sub2ind(siz,varargin)
% SUB2IND algorithm assuming isa(siz,coder.internal.indexIntClass).
coder.internal.prefer_const(siz);
nsiz = coder.internal.indexInt(numel(siz));
% Input checking
eml_invariant(nsiz >= 2,'MATLAB:sub2ind:InvalidSize');
nsubs = coder.internal.indexInt(nargin - 1);
m = eml_min(nsubs,nsiz);
for k = coder.unroll(1:nsubs)
    % coder.internal.prefer_const(varargin{k});
    if k > 1
        eml_invariant(isequal(size(varargin{1}),size(varargin{k})), ...
            'MATLAB:sub2ind:SubscriptVectorSize');
    end
    if k < m
        hi = siz(k);
    elseif k > m
        hi = coder.internal.indexInt(1);
    else
        hi = prodsub(siz,m,nsiz);
    end
    eml_invariant(allinrange(varargin{k},1,hi), ...
        'MATLAB:sub2ind:IndexOutOfRange');
end
% Compute linear indices
psiz = siz(1);
idx = coder.internal.indexInt(varargin{1});
for k = coder.unroll(2:m)
    idx = idx + psiz*(coder.internal.indexInt(varargin{k}) - 1);
    if k < m
        psiz = psiz*siz(k);
    end
end

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

function p = allinrange(x,lo,hi)
% p = ~any(x(:)<lo | x(:)>hi) without temporaries.
for k = 1:numel(x)
    if ~(x(k) >= lo && x(k) <= hi)
        p = false;
        return
    end
end
p = true;

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

function y = prodsub(x,lo,hi)
% y = prod(x(lo:hi)) for isa(x,coder.internal.indexIntClass).
y = coder.internal.indexInt(1);
for k = lo:hi
    y = y*x(k);
end

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