Python diag函数
功能:
1.二维数组取出对角线上的元素;
2.一维数组将数组中的每个元素作为对角线上元素形成二维数组;
eg1:
import numpy as np
b = np.arange(1, 10).reshape(3, 3)
b
array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
np.diag(b)
array([1, 5, 9])
eg2:
c=b.ravel()
c
array([1, 2, 3, 4, 5, 6, 7, 8, 9])
d=np.diag(c)
d
Out[34]:
array([[1, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 2, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 3, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 4, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 5, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 6, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 7, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 8, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 9]])