2010-09-12 48 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)));