nnz — Count nonzero elements in MATLAB and RunMat.
nnz(X) returns the count of nonzero elements in X. Result type and supported input classes follow MATLAB semantics.
Syntax
N = nnz(A)
N = nnz(A, dim)Inputs
A- Type
Any- Required
- Yes
- Description
- Input array.
dim- Type
NumericScalar- Required
- Yes
- Description
- Dimension selector.
Returns
N- Type
NumericArray- Description
- Count of nonzero elements.
Errors
RunMat:nnz:InvalidArgument- When
- Dimension argument grammar is invalid.
- Message
nnz: invalid argument
RunMat:nnz:InvalidInput- When
- Input type is unsupported for nnz.
- Message
nnz: invalid input
RunMat:nnz:Internal- When
- Reduction execution fails due to provider, conversion, or shape operations.
- Message
nnz: internal reduction failure
RunMat:nnz:TooManyOutputs- When
- More outputs are requested than this public form returns.
- Message
nnz: too many output arguments
Behavior
nnz(X) treats any value that is not exactly zero as nonzero. Both NaN and Inf therefore contribute to the total.
Complex numbers are counted when either the real or imaginary part is nonzero (including NaN).
Logical arrays (logical) are summed as if true were 1 and false were 0.
Character arrays use their code points; only the null character (char(0)) is considered zero.
Empty arrays return 0 because no elements are nonzero.
All eight integer classes are counted directly from authoritative native storage and return a host double scalar.
nnz(X, dim) is a gated RunMat reduction convenience, not a documented MATLAB nnz syntax. MATLAB-compatible mode rejects it before dimension gathering or provider access.
In RunMat mode, a dimension beyond ndims(X) returns a host double nonzero mask with X's shape; it does not preserve X's original magnitudes.
Forms, classes, and shapes
Zero comparison borrows native real, integer, and complex storage without constructing a floating copy. Sparse input counts stored nonzero values without densifying; explicit stored zeros do not contribute. Signed zero contributes zero and a complex value contributes once if either component is nonzero.
nnz(X) supports one host double scalar result without a host payload allocation. The gated dimension form reduces the selected axis to one, preserves other axes including character pages, and returns a host double array. A dimension beyond the stored rank returns a nonzero mask, not the original numeric magnitudes. Controls must be positive numeric scalars; empty or vector controls are rejected.
Only real floating resident input currently has a count hook. Single provider counts are admitted for slices of at most 2^24 elements. Wider single counts and native integer resident counts still require an exact resident count implementation; explicit input is rejected rather than silently gathered. The source allocation remains live, and validated count readback is the declared host result boundary.
Execution and allocation
Inputs and controls retain their invocation owners across suspension. Each call uses its selected execution context and cancellation authority. Provider outputs are checked for owner, device, physical class, shape, and forbidden input aliasing. Operational errors, cancellation, authority loss, and invalid attempted outputs remain terminal; no host replay follows them.
Eligible resident count hooks read back the declared host result, including for explicit gpuArray input. This does not authorize gathering unsupported explicit input. Automatic input fallback requires a genuine no-attempt decision and an admitted host route. Single-precision counts wider than 2^24 per slice remain unsupported without an exact resident count mechanism.
Finite host allocation is not yet implemented for this operation's array scratch, shape, and output collections. Such paths reject a Managed allocation policy before unowned work; ordinary Unbounded host execution remains available. This restriction is an unfinished allocation capability, not a promise of a bounded host implementation. Native/browser execution shares the Runtime binding; long synchronous host loops do not promise browser yielding.
These operations execute through their Runtime bindings, not a certified fused reduction. The live planner declines fused prod and nnz execution. Distributed execution is not declared by these entries.
Examples
Counting nonzero elements in a dense matrix
A = [1 0 3; 0 0 5];
count = nnz(A)Expected output:
count = 3Counting nonzero entries in each column
A = [1 0 3; 0 7 5];
perColumn = nnz(A, 1)Expected output:
perColumn = [1 1 2]Counting nonzero entries in each row
A = [1 0 3; 0 7 0];
perRow = nnz(A, 2)Expected output:
perRow = [2; 1]Recognising NaN values as nonzero
values = [0 NaN 5];
nanCount = nnz(values)Expected output:
nanCount = 2Counting GPU-resident values without manual gathers
G = gpuArray([1 0 2 0 3]);
gpuCount = nnz(G)Expected output:
gpuCount = 3Using nnz with coding agents
Open a RunMat example with live inputs, then ask the agent to explain how nnz changes the result.
Run a small nnz example, explain the result, then change one input and compare the output.
FAQ
When should I use the nnz function?⌄
Use nnz whenever you need a quick count of nonzero elements—for example when measuring sparsity or validating that an algorithm produced the expected number of nonzeros.
What data types does nnz support?⌄
Numeric, logical, complex, and character arrays are supported. Other types (structs, cell arrays, strings, objects) raise descriptive errors, as in MATLAB.
Does nnz treat NaN as nonzero?⌄
Yes. Because NaN ~= 0, each NaN contributes to the result.
How can I count nonzeros along a dimension?⌄
The documented MATLAB form is nnz(X) only. RunMat offers nnz(X,dim) as an explicitly gated convenience when RunMat extensions are enabled.
What does nnz return for logical arrays?⌄
It returns the number of true elements, effectively behaving like sum(logicalArray).
Does nnz work with GPU arrays?⌄
Eligible floating resident input uses its exact provider's count operation and reads back only the declared host result. Automatic input placement may use admitted non-destructive fallback when no hook was attempted. Explicit gpuArray input without a supported exact resident route is rejected before input gathering; integer input currently has no resident count route.
How does nnz handle character arrays?⌄
Characters are converted to their numeric code points; any character other than the null character counts as nonzero.
Can the result exceed double precision?⌄
The public result is double. Host counts use a native integer counter before conversion. Floating provider count accumulation is admitted only within its consecutive-integer range; the current single-precision route requires no more than 2^24 elements per reduced slice.
Related Math functions
Reduction
all · any · bounds · cummax · cummin · cumprod · cumsum · cumtrapz · diff · gradient · max · maxk · mean · median · min · mink · movmax · movmean · movmedian · movmin · movprod · movstd · movsum · movvar · prod · rms · std · sum · trapz · var
Elementwise
abs · angle · besselj · bsxfun · complex · conj · double · eps · erf · erfcinv · exp · expm1 · flintmax · gamma · gammaln · heaviside · hypot · imag · int16 · int32 · int64 · int8 · intmax · intmin · ldivide · log · log10 · log1p · log2 · minus · nextpow2 · plus · pow2 · power · rdivide · real · realmax · realmin · realsqrt · rescale · sign · single · sqrt · times · typecast · uint16 · uint32 · uint64 · uint8
Optim
acceptancesa · annealingboltz · annealingfast · coneprog · crossoverarithmetic · crossoverheuristic · crossoverintermediate · crossoverlaplace · crossoverscattered · crossoversinglepoint · crossovertwopoint · eqnproblem · EquationProblem.solve · EquationProblem.subsasgn · EquationProblem.subsref · evaluate · fgoalattain · fitscalingprop · fitscalingrank · fitscalingshiftlinear · fitscalingtop · fminbnd · fmincon · fminimax · fminsearch · fminunc · fseminf · fsolve · fzero · ga · gacreationlinearfeasible · gacreationnonlinearfeasible · gacreationsobol · gacreationuniform · gacreationuniformint · gaplotbestf · gaplotbestindiv · gaplotdistance · gaplotexpectation · gaplotgenealogy · gaplotmaxconstr · gaplotrange · gaplotscorediversity · gaplotscores · gaplotselection · gaplotstopping · integerConstraint · integral · intlinprog · linprog · lsqcurvefit · lsqlin · LsqlinWarmStart.subsasgn · LsqlinWarmStart.subsref · lsqnonlin · lsqnonneg · mutationadaptfeasible · mutationgaussian · mutationpositivebasis · mutationpower · mutationuniform · optimexpr · optimget · OptimizationConstraint.evaluate · OptimizationConstraint.subsasgn · OptimizationConstraint.subsref · OptimizationExitflag.double · OptimizationExitflag.eq · OptimizationExitflag.ne · OptimizationExitflag.string · OptimizationExpression.acos · OptimizationExpression.acosh · OptimizationExpression.acot · OptimizationExpression.acoth · OptimizationExpression.acsc · OptimizationExpression.acsch · OptimizationExpression.asec · OptimizationExpression.asech · OptimizationExpression.asin · OptimizationExpression.asinh · OptimizationExpression.atan · OptimizationExpression.atanh · OptimizationExpression.cat · OptimizationExpression.cos · OptimizationExpression.cosh · OptimizationExpression.cot · OptimizationExpression.coth · OptimizationExpression.csc · OptimizationExpression.csch · OptimizationExpression.ctranspose · OptimizationExpression.cumprod · OptimizationExpression.cumsum · OptimizationExpression.diag · OptimizationExpression.diff · OptimizationExpression.dot · OptimizationExpression.eq · OptimizationExpression.evaluate · OptimizationExpression.exp · OptimizationExpression.ge · OptimizationExpression.horzcat · OptimizationExpression.ldivide · OptimizationExpression.le · OptimizationExpression.log · OptimizationExpression.mean · OptimizationExpression.minus · OptimizationExpression.mldivide · OptimizationExpression.mpower · OptimizationExpression.mrdivide · OptimizationExpression.mtimes · OptimizationExpression.norm · OptimizationExpression.plus · OptimizationExpression.power · OptimizationExpression.prod · OptimizationExpression.rdivide · OptimizationExpression.reshape · OptimizationExpression.sec · OptimizationExpression.sech · OptimizationExpression.sin · OptimizationExpression.sinh · OptimizationExpression.sqrt · OptimizationExpression.subsasgn · OptimizationExpression.subsref · OptimizationExpression.sum · OptimizationExpression.tan · OptimizationExpression.tanh · OptimizationExpression.times · OptimizationExpression.trace · OptimizationExpression.transpose · OptimizationExpression.uminus · OptimizationExpression.uplus · OptimizationExpression.vertcat · OptimizationExpression.zeros · OptimizationExpression.zerosLike · OptimizationProblem.solve · OptimizationProblem.subsasgn · OptimizationProblem.subsref · OptimizationVariable.subsasgn · OptimizationVariable.subsref · optimoptions · optimplotconstrviolation · optimplotfirstorderopt · optimplotfunccount · optimplotfval · optimplotfvalconstr · optimplotmilp · optimplotstepsize · optimplotx · optimproblem · optimset · optimvar · optimwarmstart · particleswarm · patternsearch · psplotbestf · psplotbestx · psplotfuncount · psplotmaxconstr · psplotmeshsize · pswcreationuniform · pswplotbestf · quad · quadprog · QuadprogWarmStart.subsasgn · QuadprogWarmStart.subsref · saplotbestf · saplotbestx · saplotf · saplotstopping · saplottemperature · saplotx · savemilpsolutions · secondordercone · selectionremainder · selectionroulette · selectionstochunif · selectiontournament · selectionuniform · simulannealbnd · solve · surrogateopt · surrogateoptplot · temperatureboltz · temperatureexp · temperaturefast
Trigonometry
acos · acosd · acosh · acotd · acscd · asecd · asin · asind · asinh · atan · atan2 · atan2d · atand · atanh · cos · cosd · cosh · cospi · deg2rad · pol2cart · rad2deg · sin · sind · sinh · sinpi · tan · tand · tanh
Structure
bandwidth · isdiag · ishermitian · issymmetric · istril · istriu · symrcm
Signal
blackman · butter · buttord · cheb2ord · conv · conv2 · deconv · downsample · envelope · filter · filtfilt · fir1 · freqz · gauspuls · hamming · hann · hilbert · periodogram · pulstran · pwelch · rectpuls · resample · sawtooth · sinc · spectrogram · square · tripuls · unwrap · upsample · zplane
Factor
chol · decomposition · decomposition.ctranspose · decomposition.mldivide · decomposition.mrdivide · decomposition.mtimes · decomposition.rdivide · decomposition.subsref · decomposition.times · decomposition.uminus · decomposition.uplus · eig · eigs · gmres · ichol · ilu · lu · ordeig · ordqz · ordschur · pcg · qr · qz · rsf2csf · schur · svd
Ops
cross · ctranspose · dot · mldivide · mpower · mrdivide · mtimes · pagemtimes · pagetranspose · trace · transpose
Interpolation
griddedInterpolant · griddedInterpolant.subsref · interp1 · interp1q · interp2 · pchip · ppval · spline
Integer Division
Source you can read
Every RunMat function's source is public. Read exactly how nnz is executed, line by line, in Rust.
- View the source for nnz in Rust on GitHub
- Learn how the RunMat runtime works
- Found a bug? Open an issue with a minimal reproduction.
About RunMat
RunMat is a runtime that executes MATLAB-syntax code fast on any GPU. The runtime is free for individuals, including freelancers; students and faculty at an academic institution, for teaching or research there; contributors to an open-source project, for work on that project; organizations with 250 or fewer people and US$10M or less in annual revenue; and anyone, for non-production use. See runmat.com/license.
- RunMat automatically optimizes your math for GPU execution on Apple, Nvidia, and AMD hardware. No code changes needed. Simulations that took hours now take minutes.
- Start running code in seconds. RunMat runs in the browser, on the desktop, or from the CLI. No license server, no IT ticket.