Learning machine learning? Try my machine learning flashcards or Machine Learning with Python Cookbook.

# Getting The Diagonal Of A Matrix

## Preliminaries

```
# Load library
import numpy as np
```

## Create Matrix

```
# Create matrix
matrix = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
```

## Get The Diagonal

```
# Return diagonal elements
matrix.diagonal()
```

```
array([1, 5, 9])
```

## Calculate The Trace

```
# Calculate the tracre of the matrix
matrix.diagonal().sum()
```

```
15
```

#### Find an error or bug?

Everything on this site is available on GitHub. Head to and submit a suggested change. Include the tutorial's URL in the issue.