function rCond = reciprocalConditionNumberFromDiagonal(localDiagA)
% Calculate reciprocal condition number (rCond) for triangular or diagonal
% matrices. For both, rCond can be calculated from the entries on the main
% diagonal.

%   Copyright 2018-2019 The MathWorks, Inc.

% Make input vector dense do avoid sparse computations and ensure rCond is
% returned as non-sparse scalar.
localDiagA = full(localDiagA);

% Find max element, -min element, and if any NaNs exist along the diagonal.
if ~isempty(localDiagA)
    absLocalDiag = abs(localDiagA);
    localMaxMinNan = [max(absLocalDiag), -min(absLocalDiag), ...
        any(isnan(absLocalDiag))];
else
    % For an empty localDiagA set values that do not influence the
    % calculation.
    localMaxMinNan = [0, -Inf, 0];
end
% Collect max from all workers
maxMinNan = spmdReduce(@max, localMaxMinNan);

% isSingular is true if either the max or -min of the diagonal is 0 and if
% neither of those values is NaN. Notice, that those values can only be NaN
% if the entire diagonal is NaN and, therefore, both are NaN.
isSingular = ~isnan(maxMinNan(1)) && ~(maxMinNan(1) && maxMinNan(2));
hasNans = maxMinNan(3);

% Keep the following order: isSingular has higher priority than hasNans
if isSingular
    rCond = 0;
elseif hasNans
    rCond = NaN;
else
    rCond = -maxMinNan(2)/maxMinNan(1);
end
end
