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

问题描述:

我正在尝试创建一个稀疏矩阵,该矩阵具有沿对角线排列的2D模式.举个简单的例子,这可能最容易解释.

I am trying to create a sparse matrix which has a 2D pattern run down the diagonal. This is probably easiest to explain with a quick example.

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

Say my pattern is: [1,0,2,0,1]...

我想创建一个稀疏矩阵:

I want to create a sparse matrix:

    [[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似乎是一个不错的选择,但是,我根本无法从现有文档中弄清楚如何完成我想要的工作.预先谢谢你

The scipy.sparse.dia_matrix seems like a good candidate, however, I simply cannot figure out how to accomplish what I want from the documentation available. Thank you in advance

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.]]