3

我正在尝试创建一个稀疏矩阵,该矩阵具有沿对角线运行的 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 似乎是一个不错的候选者,但是,我根本无法从可用的文档中弄清楚如何完成我想要的。先感谢您

4

3 回答 3

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.]]
于 2012-04-24T17:41:07.320 回答
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]]
于 2012-04-24T18:15:16.117 回答
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
于 2012-04-24T17:43:22.327 回答