<br />

|---|
| [![](https://www.tensorflow.org/images/GitHub-Mark-32px.png) View source on GitHub](https://github.com/tensorflow/tensorflow/blob/v2.21.0/tensorflow/python/ops/math_ops.py#L3431-L3472) |

Compute the trace of a tensor `x`.

#### View aliases


**Compat aliases for migration**

See
[Migration guide](https://www.tensorflow.org/guide/migrate) for
more details.

[`tf.compat.v1.trace`](https://www.tensorflow.org/api_docs/python/tf/linalg/trace)

<br />

    tf.linalg.trace(
        x, name=None
    )

`trace(x)` returns the sum along the main diagonal of each inner-most matrix
in x. If x is of rank `k` with shape `[I, J, K, ..., L, M, N]`, then output
is a tensor of rank `k-2` with dimensions `[I, J, K, ..., L]` where

`output[i, j, k, ..., l] = trace(x[i, j, k, ..., l, :, :])`

#### For example:

    x = tf.constant([[1, 2], [3, 4]])
    tf.linalg.trace(x)  # 5

    x = tf.constant([[1, 2, 3],
                     [4, 5, 6],
                     [7, 8, 9]])
    tf.linalg.trace(x)  # 15

    x = tf.constant([[[1, 2, 3],
                      [4, 5, 6],
                      [7, 8, 9]],
                     [[-1, -2, -3],
                      [-4, -5, -6],
                      [-7, -8, -9]]])
    tf.linalg.trace(x)  # [15, -15]

<br />

<br />

<br />

| ## Args ||
|---|---|
| `x` | tensor. |
| `name` | A name for the operation (optional). |

<br />

<br />

<br />

<br />

| ## Returns ||
|---|---|
| The trace of input tensor. ||

<br />