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
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
A | Any | Yes | — | Input array. |
dim | NumericScalar | No | — | Dimension selector. |
Returns
| Name | Type | Description |
|---|---|---|
N | NumericArray | Count of nonzero elements. |
Errors
| Identifier | When | Message |
|---|---|---|
RunMat:nnz:InvalidArgument | Dimension argument grammar is invalid. | nnz: invalid argument |
RunMat:nnz:InvalidInput | Input type is unsupported for nnz. | nnz: invalid input |
RunMat:nnz:Internal | Reduction execution fails due to provider, conversion, or shape operations. | nnz: internal reduction failure |
How nnz works
nnz(X)treats any value that is not exactly zero as nonzero. BothNaNandInftherefore 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 iftruewere1andfalsewere0. - Character arrays use their code points; only the null character (
char(0)) is considered zero. - Empty arrays return
0because 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 MATLABnnzsyntax. MATLAB-compatible mode rejects it before dimension gathering or provider access.- In RunMat mode, dimensions larger than
ndims(X)leave the convenience result unchanged, following ordinary singleton-dimension reduction geometry.
Does RunMat run nnz on the GPU?
For documented nnz(X), floating resident input may use reduce_nnz; the returned handle must be fresh, owned by the same provider, real floating, correctly shaped, and physically consistent with its metadata before download. Integer input follows an exact owner-aware gather fallback. The RunMat-only dimension form can use reduce_nnz_dim for floating input after its compatibility gate.
GPU memory and residency
You usually do not need to call gpuArray explicitly. RunMat selects the exact provider that owns the source handle, validates fresh floating reduction results, and uses non-destructive authoritative fallback when the provider hook is unavailable or the payload is integer. The source handle and metadata remain intact and the count is returned as a host double scalar.
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?⌄
Yes. Floating input uses a validated owning-provider reduction when available. Integer input uses an exact non-destructive gather fallback so native and packed integer storage is never interpreted as floating data. The result is a host double scalar.
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?⌄
Counts are stored in double precision (like MATLAB). Extremely large arrays share MATLAB's limitation where values above 2^53 may lose the least significant bit, but RunMat still returns a finite double.
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 · bsxfun · complex · conj · double · erf · erfcinv · exp · expm1 · factorial · flintmax · gamma · gammaln · heaviside · hypot · idivide · imag · intmax · intmin · ldivide · log · log10 · log1p · log2 · minus · nextpow2 · plus · pow2 · power · rdivide · real · realmax · realmin · realsqrt · rescale · sign · single · sqrt · swapbytes · times · typecast · uint16 · uint32 · uint8
Trigonometry
acos · acosh · asin · asinh · atan · atan2 · 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
Optim
coneprog · fminbnd · fminunc · fsolve · fzero · integral · linprog · lsqcurvefit · lsqnonlin · optimoptions · optimset · quad · secondordercone
Ops
cross · ctranspose · dot · mldivide · mpower · mrdivide · mtimes · pagemtimes · pagetranspose · trace · transpose
Open-source implementation
Unlike proprietary runtimes, every RunMat function is open-source. 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 an open-source runtime that executes MATLAB-syntax code blazing on any GPU. It is licensed under the Apache 2.0 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.