function yi = interp1q(x,y,xi)
%MATLAB Code Generation Library Function

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

eml_invariant(nargin == 3, ...
    'Coder:toolbox:interp1q_1', ...
    'IfNotConst','Fail');
eml_invariant(isa(x,'float') && isreal(x), ...
    'Coder:toolbox:interp1q_2', ...
    'IfNotConst','Fail');
eml_invariant(isa(y,'float'), ...
    'Coder:toolbox:interp1q_3', ...
    'IfNotConst','Fail');
eml_invariant(isa(xi,'float') && isreal(xi), ...
    'Coder:toolbox:interp1q_4', ...
    'IfNotConst','Fail');
if eml_is_const(size(x)) && eml_is_const(size(y)) && eml_is_const(size(xi))
    % The purpose of interp1q is reduced overhead, so we only do these
    % checks when they can be resolved at compile time.
    eml_invariant(size(x,1)==numel(x), ...
        'Coder:toolbox:interp1q_5', ...
        'IfNotConst','Fail');
    eml_invariant(size(xi,1)==numel(xi), ...
        'Coder:toolbox:interp1q_6', ...
        'IfNotConst','Fail');
    eml_invariant(size(x,1)==size(y,1), ...
        'Coder:toolbox:interp1q_7', ...
        'IfNotConst','Fail');
end
% Determine output class.
if isa(x,'single') || isa(y,'single') || isa(xi,'single')
    outcls = 'single';
else
    outcls = 'double';
end
% Preallocate storage for output and initialize.
if isreal(y)
    yi = coder.internal.nan + zeros(numel(xi),size(y,2),outcls);
else
    yi = complex(coder.internal.nan + zeros(numel(xi),size(y,2),outcls));
end
for k = 1:numel(xi)
    t = xi(k);
    if t >= x(1) && t <= x(end)
        n = coder.internal.bsearch(x,xi(k));
        np1 = coder.internal.indexPlus(n,1);
        r = eml_rdivide(t-x(n),x(np1)-x(n));
        onemr = 1 - r;
        for j = 1:size(y,2)
            if y(n,j) == y(np1,j)
                yi(k,j) = y(n,j);
            else
                yi(k,j) = onemr*y(n,j) + r*(y(np1,j));
            end
        end
    end
end
