Effective way to create a diagonal sparse matrix

I have the following Python code using Numpy:

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

How can I convert it to get a sparse matrix p2 with the same values ​​as p without first creating p ?

+6
python numpy scipy sparse-matrix
source share
2 answers

Use scipy.sparse.spdiags (which does a lot, and therefore can be confusing, first), scipy.sparse.dia_matrix and / or scipy.sparse.lil_diags . (depending on the format you want the sparse matrix ...)

eg. using 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) 
+8
source share

Using the scipy.sparse module,

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

All Articles