What is the trace of a matrix?
Let’s say there is an nxn matrix A. If Ai,j represents the element in the ith row and jth column of the matrix A, then the elements Ai,i for all i between 1 to n will form the principal diagonal of the matrix.
Let’s look at an example.
Hence, the principal diagonal of the matrix will consist of the elements 1, 5, and 9.
The trace of a matrix is the sum of the elements of its principal diagonal. So,
How to calculate the trace of a matrix using Python NumPy?
We can use the following Python code to calculate the trace of a square matrix using NumPy.
import numpy n = 4 A = numpy.random.randint(low=1, high=10, size=(n, n)) trace = A.trace() print("A: \n", A) print("Trace of A: ", trace)
We are first creating a sqaure matrix that contains random integers. We are using the numpy.random.randint() function for that purpose. The generated random integers will be within the range [low, high).
The size argument specifies the shape of the matrix. Here, size=(n, n) specifies that the created matrix will have n rows and n columns.
We are now using the trace() function to calculate the trace of the matrix A. The output of the mentioned program will be:
A: [[5 7 9 1] [8 8 4 4] [8 5 3 9] [6 4 1 4]] Trace of A: 20
0 Comments