我有一个 N*N 矩阵:
N=3
x = scipy.sparse.lil_matrix( (N,N) )
for _ in xrange(N):
x[random.randint(0,N-1),random.randint(0,N-1)]=random.randint(1,100)
假设矩阵如下所示:
X Y Z
X 0 [2,3] [1,4]
Y [2,3] 0 0
Z [1,4] 0 0
如何在不影响现有值的情况下添加 N+1 个顶点?
X Y Z A
X 0 [2,3] [1,4] 0
Y [2,3] 0 0 0
Z [1,4] 0 0 [1]
是否需要重新构建整个矩阵?
当我尝试使用 vstack 添加新行时,出现错误:
>>> import scipy.sparse as sp
>>> c=sp.coo_matrix(x)
>>> c.todense()
matrix([[ 1., 3., 5.],
[ 2., 6., 4.],
[ 8., 2., 10.]])
>>> sp.vstack([c,sp.coo_matrix(1,3)])
Traceback (most recent call last):
File "<pyshell#41>", line 1, in <module>
sp.vstack([c,sp.coo_matrix(1,3)])
File "c:\working\QZPkgs\eggs\scipy-0.10.1-py2.6-win32.egg\scipy\sparse\construct.py", line 293, in vstack
return bmat([ [b] for b in blocks ], format=format, dtype=dtype)
File "c:\working\QZPkgs\eggs\scipy-0.10.1-py2.6-win32.egg\scipy\sparse\construct.py", line 355, in bmat
raise ValueError('blocks[:,%d] has incompatible column dimensions' % j)
ValueError: blocks[:,0] has incompatible column dimensions