trace — Sum the main-diagonal elements of a square matrix.
trace(A) returns the sum of the main diagonal of a square full or sparse single- or double-precision matrix.
Syntax
t = trace(A)Inputs
A- Type
Any- Required
- Yes
- Description
- Input matrix-like value.
Returns
t- Type
NumericArray- Description
- Diagonal-sum trace result.
Errors
RunMat:trace:InvalidInput- When
- Input is unsupported or not matrix-shaped.
- Message
trace: input must be 2-D
RunMat:trace:Internal- When
- Runtime cannot materialize or transport trace results.
- Message
trace: internal runtime failure
Behavior and supported arrays
trace(A) returns the sum of the main diagonal of a square full or sparse single- or double-precision matrix.
The input must be square and two-dimensional. Rectangular matrices, nonscalar vectors, and arrays with nonsingleton trailing dimensions raise an error.
Scalars (real or complex) return their own value.
Single input returns single, double input returns double, and complex floating input retains both its real and imaginary values and floating precision.
RunMat mode additionally accepts logical, character, and native integer matrices. Integer diagonal values are accumulated exactly and converted to double only when the sum is exactly representable.
Full and sparse real or complex floating matrices are supported. Sparse inputs are read directly from their typed CSC storage.
Empty matrices yield 0. Empty complex matrices yield 0 + 0i.
gpuArray inputs stay resident when the provider supports diagonal extraction and double accumulation. Known-unavailable routes are selected before staging and compute on the host, restoring a class-preserving 1×1 GPU result.
GPU residency and provider behavior
When the input's owning provider implements diagonal extraction and reduction, trace remains resident. Otherwise it gathers once, computes on the host, and restores a 1×1 result with the original floating class through that same provider. Automatic residency and explicit gpuArray inputs use the same owner-preserving path.
1. If the owning provider implements diag_extract and reduce_sum, the reduction stays resident. 2. Otherwise the matrix gathers once and a class-preserving 1×1 result is restored through that owner. 3. Integer, logical, and character inputs follow their compatibility-mode admission rules before provider work begins.
Resident execution requires diagonal extraction and a double-accumulating reduction. If the provider certifies that route unavailable before staging, RunMat gathers once, computes on the host, and restores a class-preserving 1×1 result through the same owner. Failures after provider work starts are reported without replay.
Examples
Summing the diagonal of a square matrix
A = [1 2 3; 4 5 6; 7 8 9];
t = trace(A)Expected output:
t = 15Rejecting a rectangular matrix
B = [4 2; 1 3; 5 6];
result = trace(B)Expected output:
Error: trace requires a square matrixGetting the trace of a triangular matrix
U = [4 1 2; 0 5 3; 0 0 6];
tri_trace = trace(U)Expected output:
tri_trace = 15Working with complex-valued matrices
Z = [1+2i 2; 3 4-5i];
zTrace = trace(Z)Expected output:
zTrace = 5.0000 - 3.0000iTracing a gpuArray and gathering the scalar result
G = gpuArray(rand(1024));
gpuResult = trace(G); % gpuArray result; execution depends on the provider
scalarHost = gather(gpuResult)Handling empty matrices safely
E = zeros(0, 0);
value = trace(E)Expected output:
value = 0Using trace with coding agents
Open a RunMat example with live inputs, then ask the agent to explain how trace changes the result.
Run a small trace example, explain the result, then change one input and compare the output.
FAQ
What happens if my matrix is not square?⌄
It raises RunMat:trace:InvalidInput; trace requires a square matrix.
Does trace accept higher-dimensional arrays?⌄
Only when trailing dimensions are singleton. Otherwise it raises an error because MATLAB restricts trace to 2-D matrix slices.
How are logical inputs handled?⌄
Logical matrices are a RunMat-mode extension and return a double sum. MATLAB compatibility modes accept the documented single and double matrix classes.
What is returned for empty inputs?⌄
Empty real matrices produce 0; empty complex matrices produce 0 + 0i, exactly like MATLAB.
Does the result stay on the GPU?⌄
The result remains a gpuArray. Execution stays resident when the provider supports the required double accumulation; a known-unavailable route gathers before staging and restores the scalar afterward. A provider failure after work starts is reported without replay.
Can I call trace on complex data?⌄
Yes. Full and sparse complex inputs return the sum of the diagonal's real and imaginary parts, preserving single or double precision.
Is there any precision loss with large matrices?⌄
Single and complex-single inputs retain single precision; double and complex-double inputs retain double precision. RunMat-mode integer inputs use exact wide accumulation and reject a final sum that cannot be represented exactly as double.
Does trace modify the input matrix?⌄
No. It reads the diagonal and returns a new scalar without altering the original matrix or its residency.
How does trace interact with sparse matrices?⌄
Real and complex sparse single and double matrices are supported directly. Native sparse integer matrices are available in RunMat mode and use the same exact-sum boundary as dense integer matrices.
Can I rely on trace inside fused GPU expressions?⌄
Fused kernels treat trace as a scalar reduction boundary. The planner emits GPU kernels when hooks are available; otherwise it falls back gracefully.
Related Linalg functions
Ops
cross · ctranspose · dot · mldivide · mpower · mrdivide · mtimes · pagemtimes · pagetranspose · transpose
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
Source you can read
Every RunMat function's source is public. Read exactly how trace is executed, line by line, in Rust.
- View the source for trace 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.