Skip to content
Justice Tech School

Special Matrices

eye makes an identity matrix, diag builds or extracts diagonals, triu and tril keep the upper or lower triangle, trace sums the diagonal.

Example
import numpy as np
print(np.eye(3))
print(np.diag([1, 2, 3]))
m = np.arange(9).reshape(3, 3)
print(np.trace(m), np.triu(m))

Result

[[1. 0. 0.]
 [0. 1. 0.]
 [0. 0. 1.]]
[[1 0 0]
 [0 2 0]
 [0 0 3]]
12 [[0 1 2]
 [0 4 5]
 [0 0 8]]

Exercise

Identity matrix.

np.(3)

Quiz Test

What is trace?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.