function numNonZero = nnz(A)
%NNZ Number of nonzero codistributed matrix elements
%   N = NNZ(D)
%   
%   Example:
%   spmd
%       N = 1000;
%       D = codistributed.speye(N);
%       n = nnz(D)  % n = N
%   end
%   
%   See also NNZ, CODISTRIBUTED, CODISTRIBUTED/SPEYE.


%   Copyright 2006-2022 The MathWorks, Inc.

% If already known, get it from the metadata, otherwise calculate and cache
if A.Metadata.Nnz.isKnown()
    numNonZero = A.Metadata.Nnz.get();
elseif ismatrix(A) && ~issparse(A)
    % For dense 2D, let getFillPattern collect lots of metadata at once.
    [~,numNonZero] = getFillPattern(A);
else
    % For >2D, we need to calculate it ourselves. For sparse, it is faster 
    % to call nnz directly.
    numNonZero = spmdPlus(nnz(getLocalPart(A)));
    A.Metadata.Nnz.set(numNonZero);
end
