Exercise 3

Write a python function that takes a numpy matrix as a parameter and returns its trace. We recall that the trace of a square matrix A = (ai j)i,j is the number Tr(A) = a11 + a22 + ... + ann

Solution

import numpy as np

def matrix_trace(A):
return A.trace()

#Example
A = np.array([[2,3],[1,5]])
print("Tr(A) = ", matrix_trace(A)) # output: Tr(A) = 7

Younes Derfoufi
my-courses.net

Leave a Reply