function [iqr,q1,q3] = interQuartileRange(x,lowupIn)
%MATLAB Code Generation Private Function

%   IQR with option to provide percentiles. This implemenation omits NaN.

%   Copyright 2020 The MathWorks, Inc.
%#codegen

if nargin < 2
    lowupIn = [25 75];
end
coder.internal.prefer_const(lowupIn);
lowup = lowupIn/100;

idx = coder.internal.sortIdx(x,'a');
nj = lastNonNaN(x,idx);
if isfloat(x)
    iqr = zeros('like',x);
else
    iqr = 0;
end
if nj < 1
    iqr(1) = coder.internal.nan;
    q1 = iqr;
    q3 = iqr;
elseif nj > 1
    q1 = zeros('like',iqr);
    q3 = zeros('like',iqr);
    r = lowup(1)*cast(nj,'like',lowup(1));
    i = round(r);
    if i < 1
        q1(1) = x(idx(1));
    elseif i >= nj
        q1(1) = x(idx(nj));
    else
        r = r - i;
        q1(1) = (0.5 - r)*x(idx(i)) + (0.5 + r)*x(idx(i+1));
    end
    r = lowup(2)*cast(nj,'like',lowup(2));
    i = round(r);
    if i < 1
        q3(1) = x(idx(1));
    elseif i >= nj
        q3(1) = x(idx(nj));
    else
        r = r - i;
        q3(1) = (0.5 - r)*x(idx(i)) + (0.5 + r)*x(idx(i+1));
    end
    iqr = q3 - q1;
else
    q1 = x(idx(1));
    q3 = x(idx(1));
end

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

function k = lastNonNaN(x,idx)
% Index of last non-NaN value in a sorted vector x(idx).
% The return value is 0 if all elements are NaN.
coder.inline('always');
k = coder.internal.indexInt(numel(x));
if isfloat(x)
    while k > 0
        if ~isnan(x(idx(k)))
            return
        end
        k = k - 1;
    end
end