如何创建SciPy的对角稀疏矩阵(How to create a diagonal sparse m

2019-09-16 17:24发布

我想创造出具有向下运行对角线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似乎是一个不错的人选,但是,我根本无法弄清楚如何完成我从提供的文档需要。 先感谢您

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


Answer 2:

下面是创建这样一个列表的列表一个有趣的方法:

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


Answer 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


文章来源: How to create a diagonal sparse matrix in SciPy