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

时间:2012-04-24 17:26:57

标签: python numpy scipy sparse-matrix diagonal

我正在尝试创建一个稀疏矩阵,其中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似乎是一个很好的候选者,但是,我根本无法弄清楚如何从可用的文档中完成我想要的东西。提前谢谢

3 个答案:

答案 0 :(得分:6)

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

答案 1 :(得分:1)

这是一种有趣的方式来创建这样的列表列表:

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

答案 2 :(得分:0)

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