其他分享
首页 > 其他分享> > 如何在SciPy中创建对角稀疏矩阵

如何在SciPy中创建对角稀疏矩阵

作者:互联网

我正在尝试创建一个稀疏矩阵,其中2D图案沿着对角线向下延伸.用一个简单的例子来解释这可能是最容易的.

说我的模式是:[1,0,2,0,1] …

我想创建一个稀疏矩阵:

    [[2,0,1,0,0,0,0...0],
     [0,2,0,1,0,0,0...0],
     [1,0,2,0,1,0,0...0],
     [0,1,0,2,0,1,0...0],
     [0,0,1,0,2,0,1...0],
     [...]]

scipy.sparse.dia_matrix似乎是一个很好的候选者,但是,我根本无法弄清楚如何从可用的文档中完成我想要的东西.先感谢您

解决方法:

N = 10
diag = np.zeros(N) + 2
udiag = np.zeros(N) + 1
ldiag = np.zeros(N) + 1
mat = scipy.sparse.dia_matrix(([diag, udiag, ldiag], [0, 2, -2]), shape=(N, N))
print mat.todense()
[[ 2.  0.  1.  0.  0.  0.  0.  0.  0.  0.]
[ 0.  2.  0.  1.  0.  0.  0.  0.  0.  0.]
[ 1.  0.  2.  0.  1.  0.  0.  0.  0.  0.]
[ 0.  1.  0.  2.  0.  1.  0.  0.  0.  0.]
[ 0.  0.  1.  0.  2.  0.  1.  0.  0.  0.]
[ 0.  0.  0.  1.  0.  2.  0.  1.  0.  0.]
[ 0.  0.  0.  0.  1.  0.  2.  0.  1.  0.]
[ 0.  0.  0.  0.  0.  1.  0.  2.  0.  1.]
[ 0.  0.  0.  0.  0.  0.  1.  0.  2.  0.]
[ 0.  0.  0.  0.  0.  0.  0.  1.  0.  2.]]

标签:diagonal,python,numpy,scipy,sparse-matrix
来源: https://codeday.me/bug/20190729/1573489.html