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