2010-09-12 23 views
6

我一直在使用numpy的Python中下面的代码对角稀疏矩阵:有效的方式来建立

p = np.diag(1.0/np.array(x)) 

我怎样才能改变它来获得稀疏矩阵p2与作为p相同的值,而无需创建p第一?

回答

8

使用scipy.sparse.spdiags(它有很多,所以可能会混淆,最初),scipy.sparse.dia_matrix和/或scipy.sparse.lil_diags。 (取决于你想要稀疏矩阵的format ...)

E.g.使用spdiags

import numpy as np 
import scipy as sp 
import scipy.sparse 

x = np.arange(10) 

# "0" here indicates the main diagonal... 
# "y" will be a dia_matrix type of sparse array, by default 
y = sp.sparse.spdiags(x, 0, x.size, x.size) 
1

使用scipy.sparse模块,

p = sparse.dia_matrix(1.0/np.array(x), shape=(len(x), len(x)));