RunMat
  • Pricing
RunMat
GitHub
GitHub
DownloadSign InTry in Browser
DesktopRuntimeServer
RunMat

Run math blazing fast

GitHubX (Twitter)LinkedIn

Company

  • About
  • Pricing
  • Contact
  • License
  • Privacy

Learn

  • Docs
  • Blog
  • Benchmarks
  • RunMat vs MATLAB Online

Get product updates and release notes from the RunMat team.

© 2026 Dystr · Made withfor the scientific community.

RunMat™ is a registered trademark of Dystr, Inc. MATLAB® is a registered trademark of The MathWorks, Inc. RunMat is not affiliated with, endorsed by, or sponsored by The MathWorks, Inc.

/
See all docs
Builtin Reference
    • all
    • any
    • bounds
    • cummax
    • cummin
    • cumprod
    • cumsum
    • cumtrapz
    • diff
    • gradient
    • max
    • maxk
    • mean
    • median
    • min
    • mink
    • movmax
    • movmean
    • movmedian
    • movmin
    • movprod
    • movstd
    • movsum
    • movvar
    • nnz
    • prod
    • rms
    • std
    • sum
    • trapz
    • var

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

NameTypeRequiredDefaultDescription
AAnyYes—Input array.
dimNumericScalarNo—Dimension selector.

Returns

NameTypeDescription
NNumericArrayCount of nonzero elements.

Errors

IdentifierWhenMessage
RunMat:nnz:InvalidArgumentDimension argument grammar is invalid.nnz: invalid argument
RunMat:nnz:InvalidInputInput type is unsupported for nnz.nnz: invalid input
RunMat:nnz:InternalReduction 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. 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, 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 = 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

Using 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

Rounding

ceil · fix · floor · mod · rem · round

Factor

chol · decomposition · eig · eigs · lu · qr · svd

Solve

cond · det · inv · linsolve · norm · null · pinv · rank · rcond · rref · vecnorm

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

Symbolic

digits · int · limit · piecewise · sym · syms · vpa

Fft

fft · fft2 · fftn · fftshift · ifft · ifft2 · ifftn · ifftshift

Interpolation

griddedInterpolant · interp1 · interp1q · interp2 · pchip · ppval · spline

Discrete

lcm · primes

Ode

ode15s · ode23 · ode45

Poly

polyder · polyfit · polyint · polyval · roots

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.

Getting started · Benchmarks · Pricing

Download RunMat

Download RunMat for full performance, or use RunMat in your browser for zero setup.

Download RunMatOpen Sandbox
On this page
  • Syntax
  • Inputs
  • Returns
  • Errors
  • How nnz works
  • Does RunMat run nnz on the GPU?
  • GPU memory and residency
  • Examples
  • Counting nonzero elements in a dense matrix
  • Counting nonzero entries in each column
  • Counting nonzero entries in each row
  • Recognising NaN values as nonzero
  • Counting GPU-resident values without manual gathers
  • Using nnz with coding agents
  • FAQ
  • Related Math functions
  • Reduction
  • Elementwise
  • Trigonometry
  • Structure
  • Signal
  • Rounding
  • Factor
  • Solve
  • Optim
  • Ops
  • Symbolic
  • Fft
  • Interpolation
  • Discrete
  • Ode
  • Poly
  • Open-source implementation
  • About RunMat