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
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
A | Any | Yes | — | Input matrix-like value. |
Returns
| Name | Type | Description |
|---|---|---|
t | NumericArray | Diagonal-sum trace result. |
Errors
| Identifier | When | Message |
|---|---|---|
RunMat:trace:InvalidInput | Input is unsupported or not matrix-shaped. | trace: input must be 2-D |
RunMat:trace:Internal | Runtime cannot materialize or transport trace results. | trace: internal runtime failure |
How trace works
- 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 floating matrices are supported. Complex sparse storage is not yet represented by the runtime.
- Empty matrices yield
0. Empty complex matrices yield0 + 0i. gpuArrayinputs stay on the device when the provider implements diagonal extraction and sum reductions; otherwise RunMat gathers once, computes on the host, and uploads a 1×1 scalar.
Does RunMat run trace on the GPU?
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.
GPU memory and residency
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.
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 without gathering
G = gpuArray(rand(1024));
gpuResult = trace(G); % stays on the GPU
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?⌄
Yes, when the provider implements the required hooks. Otherwise RunMat re-uploads the scalar so later GPU-friendly code still sees a gpuArray.
Can I call trace on complex data?⌄
Absolutely. The result is a complex scalar containing the sum of the diagonal's real and imaginary parts.
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 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
Open-source implementation
Unlike proprietary runtimes, every RunMat function is open-source. 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 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.