我需要创建一个对角矩阵,其对角线从中心向左或向右移动任何帮助吗?
答案 0 :(得分:1)
As the down-votes of your question suggest, you should try to explain your question in a better way. That being said, my best guess is that you're looking for superdiagonal and subdiagonal matrices; i.e.:
Superdiagonal:
0 1 0 0
0 0 1 0
0 0 0 1
0 0 0 0
Subdiagonal:
0 0 0 0
1 0 0 0
0 1 0 0
0 0 1 0
If that's the case, then you can use Numpy's indices
:
import numpy as np
superdiagonal = np.zeros((4, 4))
i, j = np.indices(superdiagonal.shape)
superdiagonal[i == j-1] = 1
print(superdiagonal)
This will give you:
array([[ 0., 1., 0., 0.],
[ 0., 0., 1., 0.],
[ 0., 0., 0., 1.],
[ 0., 0., 0., 0.]])
For subdiagonal, you just have to change the i == j-1
part to i == j+1
.