What does the nnz function do in MATLAB / RunMat?
nnz(X) returns the number of elements of X that are nonzero. The result is always a
double-precision value, matching MATLAB, and the builtin works for dense tensors, logical arrays,
complex inputs, and character data.
How does the nnz function behave in MATLAB / RunMat?
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. nnz(X, dim)counts nonzeros along the specified dimension, returning a tensor whose size in that dimension becomes1(mirroringsum(X ~= 0, dim)).- Dimensions larger than
ndims(X)leave the result unchanged, again following MATLAB's reduction rules for singleton trailing dimensions.
nnz Function GPU Execution Behaviour
When RunMat Accelerate is active, nnz keeps work on the GPU whenever the provider implements
reduce_nnz / reduce_nnz_dim. The WGPU provider ships with dedicated kernels that count nonzero
elements without gathering intermediate data. The resulting scalar or tensor is then downloaded to
the host so the return value matches MATLAB's CPU-resident doubles. If a provider lacks these hooks
RunMat falls back to gathering the input and computing on the CPU.
Examples of using the nnz function in MATLAB / RunMat
Counting nonzero elements in a dense matrix
A = [1 0 3; 0 0 5];
count = nnz(A);
Expected output:
count = 3;
Counting 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 = 2;
Counting GPU-resident values without manual gathers
G = gpuArray([1 0 2 0 3]);
gpuCount = nnz(G);
Expected output:
gpuCount = 3;
GPU residency in RunMat (Do I need gpuArray?)
You usually do not need to call gpuArray explicitly. RunMat's auto-offload planner tracks
residency automatically. For nnz, the runtime inspects the active provider and, when available,
invokes device-side reduction kernels to count nonzeros on the GPU before downloading the final
result. When a provider cannot supply those kernels, RunMat gathers the tensor and computes on the
CPU, preserving MATLAB semantics.
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?
Use nnz(X, dim)—it behaves like sum(X ~= 0, dim) and returns a tensor whose size in the
specified dimension becomes 1.
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. The builtin dispatches to provider kernels when possible and downloads the MATLAB-compatible double result. When a provider lacks specialised kernels, RunMat gathers the tensor and counts on the CPU.
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.
See Also
sum, any, find, gpuArray, gather
Source & Feedback
- The full source code for the implementation of the
nnzfunction is available at:crates/runmat-runtime/src/builtins/math/reduction/nnz.rs - Found a bug or behavioural difference? Please open an issue with details and a minimal repro.