How to create a diagonal sparse matrix in SciPy

2019-05-17 22:21发布

问题:

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.

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

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

回答1:

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


回答2:

Here is an amusing way to create a list of lists like that:

>>> n = 7
>>> a = n*[0] + [1, 0, 2, 0, 1] + [0]*n
>>> [a[-i+n+2:-i+2*n+2] for i in xrange(n)]
[[2, 0, 1, 0, 0, 0, 0], 
 [0, 2, 0, 1, 0, 0, 0], 
 [1, 0, 2, 0, 1, 0, 0], 
 [0, 1, 0, 2, 0, 1, 0], 
 [0, 0, 1, 0, 2, 0, 1], 
 [0, 0, 0, 1, 0, 2, 0], 
 [0, 0, 0, 0, 1, 0, 2]]


回答3:

In [27]: N = 5

In [28]: diagonalvals = [7, 8, 9]

In [29]: offsets = [-2, 0, 2]

In [30]: diagonaldata = [[v for n in range(N)] for v in diagonalvals]

In [31]: print diagonaldata
[[7, 7, 7, 7, 7], [8, 8, 8, 8, 8], [9, 9, 9, 9, 9]]

In [32]: A = scipy.sparse.dia_matrix((diagonaldata, offsets), shape=(N, N))

In [33]: print A
  (2, 0)    7
  (3, 1)    7
  (4, 2)    7
  (0, 0)    8
  (1, 1)    8
  (2, 2)    8
  (3, 3)    8
  (4, 4)    8
  (0, 2)    9
  (1, 3)    9
  (2, 4)    9