rank — Compute the numerical rank of a matrix using SVD with MATLAB-compatible tolerance handling.
r = rank(A) returns the numerical rank of a real or complex matrix A. The rank is the number of singular values above a tolerance derived from matrix size and scale, with MATLAB-compatible default and explicit-tolerance behavior.
Syntax
k = rank(A)
k = rank(A, tol)Inputs
A- Type
Any- Required
- Yes
- Description
- Input matrix.
tol- Type
NumericScalar- Required
- No
- Description
- Singular-value threshold.
Returns
k- Type
NumericScalar- Description
- Estimated matrix rank.
Errors
RunMat:rank:InvalidArgument- When
- Optional tolerance argument is malformed or outside accepted bounds.
- Message
rank: invalid argument
RunMat:rank:InvalidInput- When
- Input shape/type cannot be processed for rank evaluation.
- Message
rank: invalid input
RunMat:rank:Internal- When
- Runtime fails while computing rank or executing fallback/upload paths.
- Message
rank: internal runtime failure
Behavior
Inputs must behave like 2-D matrices. Trailing singleton dimensions are accepted; other higher ranks result in "rank: inputs must be 2-D matrices or vectors".
The default tolerance is tol = max(size(A)) * eps(max(s)), where s are the singular values from an SVD of A. You can override this by supplying a second argument: rank(A, tol).
When you provide an explicit tolerance it must be a finite, non-negative scalar. Non-scalars, NaN, Inf, or negative values raise MATLAB-compatible errors.
Public MATLAB matrix classes are single and double. RunMat mode separately admits logical matrices and all eight real integer classes through named extensions; integer matrix values cross only after exact binary64 representability checks.
rank([]) returns 0. Rank is always reported as a double scalar (e.g., 2.0).
Complex inputs use a complex SVD so that conjugate transposes and magnitudes follow MATLAB’s conventions.
A typed-integer tolerance is a separate RunMat extension because the public scalar tolerance does not enumerate integer classes. It must be exactly representable as binary64 before threshold computation; logical tolerance is independently gated.
Resident integer input bypasses floating provider rank kernels, gathers through its exact owner, and restores the double rank scalar to that owner when supported.
Acceleration and residency
Providers may implement a dedicated rank hook; current backends gather to the host and reuse the shared SVD path.
When a GPU acceleration provider is active, RunMat first offers the computation through the reserved rank provider hook. Backends that implement it can stay fully on-device and return a gpuTensor scalar. Providers without that hook—including today’s WGPU backend—gather the matrix to host memory, reuse the shared SVD logic, and then re-upload the scalar rank so downstream kernels continue on the GPU without user intervention. Auto-offload treats the builtin as an eager sink, so any fused producers flush before rank executes and residency bookkeeping remains consistent.
RunMat’s planner automatically keeps matrices on the GPU when a provider implements the rank hook. If the hook is missing, the builtin transparently gathers the matrix, computes the SVD on the CPU, and uploads the scalar result so later GPU work remains resident. You can still seed residency manually with gpuArray for MATLAB compatibility, but it is rarely required.
Implementation and validation
Original GPU declarations: precisions f32, f64; elementwise false; reduction false; broadcasting none.
Original fusion declarations: elementwise false; reduction false; max inputs 1; constants inline.
Examples
Determining the rank of a full matrix
A = [1 2; 3 4];
rk = rank(A)Expected output:
rk = 2Detecting rank deficiency in a singular matrix
B = [1 2; 2 4];
rk = rank(B)Expected output:
rk = 1Applying a custom tolerance to suppress tiny singular values
C = diag([1, 1e-12]);
rk_default = rank(C); % counts both singular values (rank 2)
rk_custom = rank(C, 1e-9); % treats the small value as zero (rank 1)Computing the rank of a tall matrix
A = [1 0; 0 0; 0 1];
rk = rank(A)Expected output:
rk = 2Evaluating the rank of a complex matrix
Z = [1+1i 0; 0 2-3i];
rk = rank(Z)Expected output:
rk = 2Checking the rank of an empty matrix
E = [];
rk = rank(E)Expected output:
rk = 0Using rank with gpuArray data
G = gpuArray([1 2 3; 3 6 9; 0 1 0]);
rk = rank(G); % Computation stays on the GPU when the provider supports it
rk_host = gather(rk)Expected output:
rk_host = 2Using rank with coding agents
Open a RunMat example with live inputs, then ask the agent to explain how rank changes the result.
Run a small rank example, explain the result, then change one input and compare the output.
FAQ
How is the default tolerance chosen?⌄
RunMat computes the default tolerance exactly as MATLAB: max(size(A)) * eps(max(s)), where s are the singular values of A. This scales the cutoff with matrix size and magnitude.
What does rank([]) return?⌄
The rank of the empty matrix is 0. This matches MATLAB’s convention that an empty product has neutral value.
Does rank return an integer or a double?⌄
rank returns a double-precision scalar, mirroring MATLAB’s numeric tower. The value is always an integer-valued double.
How does rank behave for vectors or scalars?⌄
Scalars are treated as 1×1 matrices. rank([0]) returns 0, while rank([5]) returns 1. Row or column vectors behave as matrices with one dimension equal to 1.
Can rank detect symbolic rank or exact arithmetic?⌄
No. Like MATLAB, RunMat’s rank relies on floating-point SVD and is subject to the chosen tolerance. For symbolic or exact arithmetic you would use a computer algebra system.
Will rank participate in fusion or auto-offload?⌄
No. rank is a residency sink that eagerly computes an SVD. Fusion groups terminate before the call, and the planner treats the builtin as a scalar reduction.
Is the tolerance argument optional?⌄
Yes. rank(A) uses the default tolerance and mirrors MATLAB. Supplying rank(A, tol) overrides the cutoff. Non-scalar or negative tolerances raise MATLAB-compatible errors.
What happens if the matrix contains NaNs or Infs?⌄
Singular values involving NaN propagate and typically produce a rank of 0. Infinite values yield infinite singular values and therefore produce a rank equal to the number of infinite entries above tolerance, matching MATLAB’s behaviour.
Does rank allocate large temporary buffers?⌄
Only enough memory for the SVD factors. For host execution this is handled by nalgebra (and LAPACK when enabled). GPU providers are free to reuse buffers or stream the computation.
Related Linalg functions
Structure
bandwidth · isdiag · ishermitian · issymmetric · istril · istriu · symrcm
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
Source you can read
Every RunMat function's source is public. Read exactly how rank is executed, line by line, in Rust.
- View the source for rank 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.