nnz — Count the number of nonzero elements in an array with MATLAB-compatible semantics.
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 nnz works in 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.
How nnz runs on the GPU
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.
GPU memory and residency
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.
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 = 3FAQ
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.
Related functions to explore
These functions work well alongside nnz. Each page has runnable examples you can try in the browser.
sum, any, find, gpuArray, gather, all, cummax, cummin, cumprod, cumsum, diff, max, mean, median, min, prod, std, var
Open-source implementation
Unlike proprietary runtimes, every RunMat function is open-source. Read exactly how nnz works, line by line, in Rust.
- View nnz.rs on GitHub
- Learn how the 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 — faster, on any GPU, with no license required.
- Simulations that took hours now take minutes. RunMat automatically optimizes your math for GPU execution on Apple, Nvidia, and AMD hardware. No code changes needed.
- Start running code in seconds. Open the browser sandbox or download a single binary. No license server, no IT ticket, no setup.
- A full development environment. GPU-accelerated 2D and 3D plotting, automatic versioning on every save, and a browser IDE you can share with a link.