Exercise 4

Resume the previous exercise (Exercise3) without using the trace() method.

Solution

import numpy as np

def matrix_trace(A):
n = len(A)
# initialization of trace of A
trace = 0
for i in range(0, n):
#trace = trace + aii
trace = trace + A[i][i]
return trace

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

Younes Derfoufi
my-courses.net

Leave a Reply