3

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

Paul
  • 20,883
  • 7
  • 57
  • 74
user1354372
  • 77
  • 2
  • 7

3 Answers3

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.]]
sega_sai
  • 8,328
  • 1
  • 29
  • 38
  • Instead of `np.zeros(N) + 1`, it might be clearer to do `np.ones(N)`. :) – Danica Apr 24 '12 at 17:41
  • 2
    :) The reason it is np.zeros(N)+1, because it is possible that the author will want to have some other value there (say 100), and then the code would be still the same np.zeros(N)+100 .But obviously it is matter of style. – sega_sai Apr 24 '12 at 17:57
  • Indeed, I do need values other than ones and twos. Thank you! It is painful how obvious this solution is, I just did not understand the dia_matrix constructor. – user1354372 Apr 25 '12 at 15:07
1

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]]
fraxel
  • 34,470
  • 11
  • 98
  • 102
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
Steve Tjoa
  • 59,122
  • 18
  • 90
  • 101