Tsallaka zuwa abun ciki
Justice Tech School

Diagonals and Triangles

diag extracts or builds diagonals. triu and tril keep the upper or lower part.

Example
a = np.arange(9).reshape(3, 3)
print(np.diag(a))
print(np.diag([1, 2, 3]))
print(np.triu(a))
print(np.trace(a))

Result

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

Exercise

Main diagonal.

np.(a)

Quiz Test

What does trace give?

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