function varargout = eigSvdInfOrNaN(isvec, type, codistr)
% eigSvdInfOrNaN Return NaN outputs when at least one of the inputs of EIG or SVD contains Inf or NaN.

%   Copyright 2021 The MathWorks, Inc.

m = codistr.Cached.GlobalSize(1);
n = codistr.Cached.GlobalSize(2);
k = min(m, n);

% First set singular/eigen-values. As SVD only supports 'econ' we return a
% a vector of size [k 1] or square matrix of size [k k].
if isvec
    S = NaN(k, 1, type, codistr.hGetNewForSize([k 1]));
else
    if isa(codistr, 'codistributor1d')
        S = diag(NaN(k, 1, type, codistr.hGetNewForSize([k 1])));
    else % DIAG doesn't support 2dbc.
        codS = codistr.hGetNewForSize([k k]);
        S = zeros(k, k, type, codS);
        diagIdx = codS.hFindDiagElementsInLocalPart();
        localS = getLocalPart(S);
        localS(diagIdx) = NaN;
        S = codistributed.pDoBuildFromLocalPart(localS, codS);
    end
end

% As distributed/SVD only supports 'econ' when A is rectangular, the output
% sizes are [m k] for U (1st input when nargout >= 2), and [n k] for V
% (3rd input). Note that EIG only supports square, in which case all the
% outputs are square of the size of A - same for SVD of a square matrix.
if nargout == 1
    varargout{1} = S;
elseif nargout >= 2
    varargout{1} = NaN(m, k, type, codistr.hGetNewForSize([m k]));
    varargout{2} = S;
    if nargout == 3
        varargout{3} = NaN(n, k, type, codistr.hGetNewForSize([n k]));
    end
end
end