nnz
Number of nonzero elements.
Category: Mathematics > Sparse Matrices
Syntax
n = nnz(X)
Counts the elements of X that are nonzero.
Description
For a sparse matrix, nnz is the number of entries it actually stores, which tells how sparse it is: nnz(S)/numel(S) is the density. For a full array it counts the elements that are not zero, so nnz(x > 3) counts the elements above 3.
NaN counts as nonzero.
Input arguments
X- Numeric or logical array, sparse or full.
Output arguments
n- Nonnegative integer scalar.
Example
Counting and density
S = sparse([1 2 3], [1 2 3], [4 5 6]);
nnz(S)
nnz(S) / numel(S)
nnz([0 2 0 7 NaN])
nnz([1 5 9 2] > 3)
Output
ans = 3
ans = 0.3333
ans = 3
ans = 2