Calculate The Trace Of A Matrix
Goal¶
This post aims to show how to calculate the trace of a matrix using numpy i.e., $tr(A)$
$tr(A)$ is defined as
$$ tr(A) = \sum_{i=1}^{n} a_{ii} = a_{11} + a_{22} + \cdots + a_{nn} $$Reference:
Libraries¶
In [1]:
import numpy as np
Create a matrix¶
In [2]:
arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
arr
Out[2]:
Calculate the trace¶
In [4]:
arr.trace()
Out[4]:
In [7]:
sum([arr[i, i] for i in range(len(arr))])
Out[7]: