Adds up the entries that run from the top-left corner to the bottom-right corner of a square matrix.
The trace totals the entries along the line that starts at the top-left corner and ends at the bottom-right one. For [[2, 7], [5, 3]] that is 2 plus 3, which is 5.
An identity matrix has a trace equal to its size, and a covariance matrix has a trace equal to the combined variance of all its series. It also equals the total of the eigenvalues, a cheap cross-check for matrix.eigenvalues(). Non-square input is not accepted.
Syntax
matrix.trace(id: matrix<int/float>) -> series float
matrix.trace(id: matrix<int>) -> series int
matrix.trace() -> series float
matrix.trace() -> series intArguments
| Name | Type | Default | Description |
|---|---|---|---|
| id | matrix<int/ | required | The square matrix whose top-left to bottom-right entries are totalled; non-square input is rejected. |
Returns
series float: The trace as a float, for example 5.0 for [[2.0, 7.0], [5.0, 3.0]].series int: The trace as a whole number, because the matrix holds ints.series float: The trace of the receiving matrix as a float.series int: The trace of the receiving matrix as a whole number.
Example
//@version=6
indicator("matrix.trace: diagonal sum", overlay = false)
matrix<float> cov = matrix.new<float>(2, 2, 0.0)
matrix.set(cov, 0, 0, 1.5)
matrix.set(cov, 1, 1, 2.5)
plot(matrix.trace(cov), "Total variance")See also
Runs on Sidechair