
Matrix Trace in Matlab
In this lesson, I will explain how to calculate the trace of a matrix in Matlab.
So, what exactly is the trace of a matrix? It is the sum of the elements on the main diagonal of the matrix. For example, in the 3x3 matrix $$ M= \begin{pmatrix} \color{red}1 & 2 & 3 \\ 4 & \color{red}5 & 6 \\ 7 & 8 & \color{red}9 \end{pmatrix} $$ The trace is equal to 15 $$ TR(M) = 1 + 5 + 9 = 15 $$
Let's take a practical example to understand better.
First, create a 3x3 matrix and assign it to the variable M.
>> M = [ 1 2 3 ; 4 5 6 ; 7 8 9 ]
M =
1 2 3
4 5 6
7 8 9
To calculate the trace of the matrix, simply type trace(M).
>> trace(M)
ans = 15
The trace of the matrix is 15.
Verify. Now let's verify this. The sum of the elements on the main diagonal of the matrix $$ M= \begin{pmatrix} \color{red}1 & 2 & 3 \\ 4 & \color{red}5 & 6 \\ 7 & 8 & \color{red}9 \end{pmatrix} $$ The trace of matrix is 15 $$ TR(M)=1+5+9 = 15 $$
In Matlab, you can also calculate the trace of rectangular matrices.
For example, let's create a 2x3 matrix.
>> M = [ 1 2 3 ; 4 5 6 ]
M =
1 2 3
4 5 6
Then, simply type trace(M) to calculate the trace.
>> trace(M)
ans = 6
The trace of the matrix is 6.
Verify. Let's verify this. The sum of the elements on the main diagonal of the matrix $$ M= \begin{pmatrix} \color{red}1 & 2 & 3 \\ 4 & \color{red}5 & 6 \end{pmatrix} $$ The trace of matrix is 6 $$ TR(M)=1+5 = 6 $$
Using this approach, you can easily calculate the trace of any matrix in Matlab.