Matrix trace calculator
Get the trace of a square matrix without a hand-written loop: for the rows 2 1 and 1 3 the diagonal is 2 and 3, so the trace is 5. Only the diagonal counts. Free in your browser.
- Free
- Runs in your browser
- No sign-up
- Your data stays on your device
Run — free
Runs in your browser. Free, unlimited — your data never leaves this page.
The trace of a square matrix is the single scalar obtained by adding every entry that sits on the main diagonal from the top-left corner down to the bottom-right corner. Trace is a fundamental linear-algebra invariant: it is cyclic under similarity, equals the sum of eigenvalues counting multiplicity, and appears in character formulas, covariance summaries, and Frobenius inner products. This calculator accepts a nested array of finite real numbers, verifies that every row has the same length equal to the number of rows so the matrix is truly square, and returns the cleaned matrix, the extracted diagonal list, the numeric trace, its absolute value, and a short formula string. Non-square inputs, empty matrices, NaN, Infinity, and oversized grids are rejected with a clear validation error instead of a silent wrong answer.
How the matrix trace is computed
Begin with an n by n array of finite real numbers. The capability first checks that the structure is rectangular and square: every row must be an array whose length equals the number of rows. Entries may arrive as numbers or numeric strings; NaN and Infinity fail validation.
Classic textbook checks include the two-by-two matrix with rows two one and one three whose trace is five, the three-by-three identity whose trace equals three, a zero matrix whose trace is zero, and matrices with negative diagonal entries that correctly reduce the sum. Because the algorithm is a pure O of n walk after O of n squared validation, latency stays negligible for every accepted size.
Where matrix traces show up in real work
Secondary-school and college linear algebra courses constantly assign diagonal-sum drills, similarity checks that preserve trace, and comparisons between trace and eigenvalue sums; a single trusted oracle that returns tr(A) and the diagonal list speeds grading and demo setup. Programming contest problems and interview warm-ups often ask for the sum of diagonal entries, the character of a small matrix group element, or a quick invariant before expensive spectral work, and engineers need a numeric trace rather than a hand-written loop that forgets zero-based indexing.
Statistics and machine learning pipelines inspect the trace of covariance, Gram, or Hessian blocks as a scalar summary of total variance or curvature. Quantum information and representation theory use the partial trace and character formulas built on the ordinary matrix trace; classroom demos still need the plain sum first. Computer graphics and continuum mechanics encounter the trace of strain and stress tensors as volumetric measures.
If you later need determinants, eigenvalues, rank, matrix inverse, or systems of linear equations, treat those as separate search intents and landings rather than overloading this matrix trace calculator page.
What you can do with it
Homework and exam answer keys
Generate tr(A), the main-diagonal list, and formula labels for textbook 2×2, 3×3, and small n×n sets so teachers and auto-graders share one ground truth.
Invariants and similarity checks
Verify that similar matrices share the same trace, or that the sum of eigenvalues matches tr(A), before deeper spectral analysis.
Covariance and tensor summaries
Compute the trace of covariance, Gram, strain, or stress matrices as a quick scalar summary of total variance or volumetric effect.
FAQ
What is the matrix trace?
The trace tr(A) is the sum of the main-diagonal entries a11 + a22 + … + ann of a square matrix A. Off-diagonal entries are not included.
What happens if the matrix is not square?
The trace is only defined for square matrices; jagged rows or unequal row versus column counts are rejected with a message that names the failing row.
Does the order of off-diagonal entries matter?
No. Only the main-diagonal values enter the sum. Changing off-diagonal entries leaves the trace unchanged, which is why the response also returns the diagonal array for inspection.
What is the maximum matrix size?
n ≤ 32. Larger dense matrices are outside the free parse path; classroom and contest sizes are fully covered.
What does it cost?
The browser tool is free and runs locally.
Related tools
For developers — API access
Everything on this page is available programmatically. This section is for teams who want to wire it into their own systems; everyone else can just use the tool above.
API endpoint
Prefer to automate it? One authenticated POST creates the task; the result comes back by webhook or a signed link. The same capability also runs here on the web, by email and from Telegram — and soon from our app too.
Call it from your stack
curl -X POST https://api.kit.forhosting.com/algebra/matrix-trace \
-H "Authorization: Bearer $KIT_KEY" \
-H "Content-Type: application/json" \
-d '{"matrix":[[2,1],[1,3]]}'const res = await fetch("https://api.kit.forhosting.com/algebra/matrix-trace", {
method: "POST",
headers: {
"Authorization": `Bearer ${process.env.KIT_KEY}`,
"Content-Type": "application/json"
},
body: JSON.stringify({
"matrix": [
[
2,
1
],
[
1,
3
]
]
})
});
const { task_id } = await res.json();import os, requests
res = requests.post(
"https://api.kit.forhosting.com/algebra/matrix-trace",
headers={"Authorization": f"Bearer {os.environ['KIT_KEY']}"},
json={
"matrix": [
[
2,
1
],
[
1,
3
]
]
},
)
task_id = res.json()["task_id"]<?php
$res = file_get_contents("https://api.kit.forhosting.com/algebra/matrix-trace", false, stream_context_create([
"http" => [
"method" => "POST",
"header" => "Authorization: Bearer " . getenv("KIT_KEY") . "\r\nContent-Type: application/json",
"content" => '{"matrix":[[2,1],[1,3]]}',
],
]));
$task = json_decode($res, true);body := bytes.NewBufferString(`{"matrix":[[2,1],[1,3]]}`)
req, _ := http.NewRequest("POST", "https://api.kit.forhosting.com/algebra/matrix-trace", body)
req.Header.Set("Authorization", "Bearer "+os.Getenv("KIT_KEY"))
req.Header.Set("Content-Type", "application/json")
res, _ := http.DefaultClient.Do(req)Example request
{
"matrix": [
[
2,
1
],
[
1,
3
]
]
}Example response
{
"task_id": "tsk_a1b2c3d4e5f6a1b2c3d4e5f6",
"type": "algebra.matrix_trace",
"status": "queued",
"_links": {
"result": "/tasks/tsk_…/result"
}
}The API is asynchronous: the call returns a task_id immediately and the result arrives by webhook. Polling is capped at 1 req/s per task.
Pricing
Published price — no tokens, no invented credits. A failed task is never charged.
Errors
| HTTP | Code | Meaning |
|---|---|---|
401 | unauthorized | Missing or invalid API key. |
402 | insufficient_balance | Your balance doesn't cover the task price. |
404 | unknown_type | That task type doesn't exist. |
429 | rate_limited | Too many requests. Use the webhook instead of polling. |
Technical notes
For a one-by-one matrix the trace is simply that lone entry; for two-by-two it is a plus d; for three-by-three it is a11 plus a22 plus a33; in general tr(A) equals the sum of a_ii from i equals one through n.
How the matrix trace is computed
Empty matrices and dimensions above thirty-two are rejected because the empty case is an edge convention that confuses beginners and oversized dense walks do not belong on a free parse Worker path. Once the matrix is accepted, the engine walks the main diagonal only: it reads a11, a22, through a_nn, stores those n values in a diagonal array, and accumulates their sum as the trace. Off-diagonal entries never enter the sum, which is exactly the textbook definition tr(A) equals the sum of a_ii. All arithmetic is deterministic floating-point code with no random seeds, no wall-clock timestamps, no network calls, and no model drift, so identical matrices always produce identical JSON.
What you send and what you get back
Every row must have the same length, and that length must equal the number of rows so the matrix is square. Rectangular matrices such as two rows of three columns fail with a message that the matrix is not square, naming the first row whose length differs from n. If you need the determinant of the same matrix rather than the trace, use the separate matrix determinant calculator landing, which targets a different search intent and returns det(A) via cofactor expansion or LU. Send one required field named matrix: either a nested JSON array of rows of finite numbers, such as two comma one then one comma three for the classic two-by-two case, or a JSON string encoding the same nested array. Missing matrix, non-array shapes, jagged rows, non-numeric cells, NaN, Infinity, empty grids, and dimensions larger than thirty-two by thirty-two fail with invalid_input and are not charged. On success the response echoes the cleaned matrix with stable twelve-significant-digit rounding, the integer dimension n, the diagonal array of main-diagonal entries, the scalar trace, abs_trace, method diagonal_sum, and a short formula string describing tr(A) equals the sum of a_ii. Pricing for successful API calls is the published base of $0.002 per item; validation failures do not consume prepaid balance.
Where matrix traces show up in real work
Because this capability is a pure parse engine, API pricing is the published base of $0.002 per successful item and failed validation does not consume balance.