function xstart = startx(ub,lb,xstart,xstartOutOfBounds_idx)
%

%STARTX	Box-centered start point.
%
% This is a helper function.

% xstart = STARTX(ub,lb,xstart,xstartOutOfBounds_idx) sets the components
% that violate the bounds to a centered value.

%   Copyright 1990-2022 The MathWorks, Inc.

arguments
    ub
    lb
    xstart = [];
    xstartOutOfBounds_idx = [];
end

% NOTE: This function assumes that checkbounds() has been called prior. If
% so, we know that the bounds are consistent, length N, and no ub == -Inf
% and no lb == Inf.

finiteUB = isfinite(ub);
finiteLB = isfinite(lb);
finiteLBonly = finiteUB  & ~finiteLB;
finiteUBonly = ~finiteUB & finiteLB;
finiteBoth = finiteUB  & finiteLB;

if ~isempty(xstart)
    finiteLBonly = finiteLBonly & xstartOutOfBounds_idx;
    finiteUBonly = finiteUBonly & xstartOutOfBounds_idx;
    finiteBoth = finiteBoth & xstartOutOfBounds_idx;
else
    n = length(ub);
    xstart = ones(n,1);
end

%
pert = max(abs(ub),1);
xstart(finiteLBonly) = ub(finiteLBonly) - .5*pert(finiteLBonly);
%
pert = max(abs(lb),1);
xstart(finiteUBonly) = lb(finiteUBonly) + .5*pert(finiteUBonly);
%
xstart(finiteBoth) = (ub(finiteBoth) + lb(finiteBoth))/2;
