np.diag(v, k = 0)
一句话总结:Extract a diagonal or construct a diagonal array.
即既可以以一维数组的形式返回对角线元素,也可以将一维数组转换成方阵。
参数意义:
- v (array_like)
- When v is a 2-D array, returns a copy of its k-th diagonal.
- When v is a 1-D array, returns a 2-D array with v on its k-th diagonal.
- k(int, optional)
Default:0
k>0: diagnals above the main diagonal.
k<0: diagonals below the main diagonal.
理解:
m = np.arange(1, 10).reshape(3, 3)
n = np.arange(1, 10)
p = np.diag(m, k = 0)
q = np.diag(n, k = 0)
output:
#m
array([[1, 2, 3],
[4, 5, 6],
[7,