Matrix Operations
- Matrix trace. Given a square matrix $A$, we find the sum of its diagonal elements, called the trace of the matrix, and denote it as $\text{tr}(A)$ (
\text{tr}(A)
).
Input: A square matrix $A_{n}$.
Output: $s = \text{tr}(A) = \sum_{i=1}^n a_{i,i}$ (usually, $s \in \mathbb{Z}$ or $s \in \mathbb{R}$.)
Algorithm:
- Declare $s = 0$.
- For every $1 \le i \le n$, set $s = s + a_{i,i}$. Then, return $s$.
Runtime analysis:
The index $i$ goes from $1$ to $n$, so there are $n$ additions and assignments (there is also a constant-time assignment $s = 0$ and increments of $i$, but they won't change the runtime). This results in an overall runtime of $\Theta(n)$.