如何使用 Numpy 生成动态尺寸较低的对角矩阵?
例如,如果矩阵的大小n
为4
,我想获得这样的矩阵:
| 0 0 0 0 |
| 1 0 0 0 |
| 0 1 0 0 |
| 0 0 1 0 |
答案 0 :(得分:2)
您可以先创建一个带有零的矩阵,然后再填充一个矩阵来创建它:
import numpy as np
# create matrix with zeros
n=4
mat = np.zeros((n,n))
# create indexes for where the 1s belong
rows = np.arange(1,n)
cols = np.arange(n-1)
# fill in the 1s
mat[rows, cols] = 1
输出:
[[0. 0. 0. 0.]
[1. 0. 0. 0.]
[0. 1. 0. 0.]
[0. 0. 1. 0.]]
答案 1 :(得分:2)
我发现使用np.eye的最短方法:
import numpy as np
n = 4
np.eye(n, k=-1, dtype=int)
输出为:
array([[0, 0, 0, 0],
[1, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, 1, 0]])