如何更改矩阵的偏移量 python numpy

How to change offset of matrix python numpy

我想得到一个形状为 100x100 的矩阵,如下所示:

[-2,1,0,0]
[1,-2,1,0]
[0,1,-2,1]
[0,0,1,-2]

我从创建对角线开始:

import numpy as np
diagonal= (100)
diagonal= np.full(diagonal, -2)
A100 = (100,100)
A100 = np.zeros(A100)
np.fill_diagonal(A100, diagonal)

现在我尝试更改偏移量:

off1=(99)
off1=np.ones(off1)
off1=np.diagonal(A100, offset=1)

但这行不通。 感谢您的帮助!

从三个单位矩阵构建矩阵:

np.eye(100, k=1) + np.eye(100, k=-1) - 2 * np.eye(100)

P.S。此解决方案比 scipy.sparse 解决方案快 7 倍。

您可以使用scipy.sparse.diags

from scipy.sparse import diags
A100 = diags([-2, 1, 1], [0, -1, 1], shape = (100, 100))
A100.A

Out[]: 
array([[-2.,  1.,  0., ...,  0.,  0.,  0.],
       [ 1., -2.,  1., ...,  0.,  0.,  0.],
       [ 0.,  1., -2., ...,  0.,  0.,  0.],
       ...,
       [ 0.,  0.,  0., ..., -2.,  1.,  0.],
       [ 0.,  0.,  0., ...,  1., -2.,  1.],
       [ 0.,  0.,  0., ...,  0.,  1., -2.]])