Main Content

# trace

Sum of diagonal elements

## Syntax

``b = trace(A)``

## Description

example

````b = trace(A)` calculates the sum of the diagonal elements of matrix `A`: $\text{tr}\left(A\right)=\sum _{i=1}^{n}{a}_{ii}={a}_{11}+{a}_{22}+...+{a}_{nn}.$```

## Examples

collapse all

Create a 3-by-3 matrix and calculate the sum of the diagonal elements.

```A = [1 -5 2; -3 7 9; 4 -1 6]; b = trace(A)```
```b = 14 ```

The result $\mathrm{tr}\left(\mathit{A}\right)=14$ agrees with a manual calculation.

`$\mathit{A}=\left[\begin{array}{ccc}{\mathit{a}}_{11}& {\mathit{a}}_{12}& {\mathit{a}}_{13}\\ {\mathit{a}}_{21}& {\mathit{a}}_{22}& {\mathit{a}}_{23}\\ {\mathit{a}}_{31}& {\mathit{a}}_{32}& {\mathit{a}}_{33}\end{array}\right]=\left[\begin{array}{ccc}1& -5& 2\\ -3& 7& 9\\ 4& -1& 6\end{array}\right],$`

`$\mathrm{tr}\left(\mathit{A}\right)=\sum _{\mathit{i}=1}^{3}{\mathit{a}}_{\mathrm{ii}}={\mathit{a}}_{11}+{\mathit{a}}_{22}+{\mathit{a}}_{33}=1+7+6=14.$`

Verify several properties of the trace of a matrix (up to round-off error).

Create two matrices. Verify that $\mathrm{tr}\left(\mathit{A}+\mathit{B}\right)=\mathrm{tr}\left(\mathit{A}\right)+\mathrm{tr}\left(\mathit{B}\right)$.

```A = magic(3); B = rand(3); trace(A+B) ```
```ans = 17.4046 ```
`trace(A) + trace(B)`
```ans = 17.4046 ```

Verify that $\mathrm{tr}\left(\mathit{A}\right)=\mathrm{tr}\left({\mathit{A}}^{\mathit{T}\right)}\right)$.

`trace(A)`
```ans = 15 ```
`trace(A')`
```ans = 15 ```

Verify that $\mathrm{tr}\left({\mathit{A}}^{\mathit{T}}\mathit{B}\right)=\mathrm{tr}\left({\mathrm{AB}}^{\mathit{T}}\right)$.

`trace(A'*B) `
```ans = 22.1103 ```
`trace(A*B')`
```ans = 22.1103 ```

Verify that $\mathrm{tr}\left(\mathrm{cA}\right)=\mathit{c}\text{\hspace{0.17em}}\mathrm{tr}\left(\mathit{A}\right)$ for a scalar $\mathit{c}$.

```c = 5; trace(c*A) ```
```ans = 75 ```
`c*trace(A)`
```ans = 75 ```

Verify that the trace equals the sum of the eigenvalues $\mathrm{tr}\left(\mathit{A}\right)={\sum }_{\mathit{i}}{\lambda }_{\mathit{i}}$.

`trace(A)`
```ans = 15 ```
`sum(eig(A))`
```ans = 15.0000 ```

## Input Arguments

collapse all

Input matrix, specified as a square matrix. `A` can be full or sparse.

Data Types: `single` | `double`
Complex Number Support: Yes

## Algorithms

`trace` extracts the diagonal elements and adds them together with the command `sum(diag(A))`. The value of the trace is the same (up to round-off error) as the sum of the matrix eigenvalues `sum(eig(A))`.

## See Also

Introduced before R2006a

Download ebook