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 ?
p2
p
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 ...)
scipy.sparse.spdiags
scipy.sparse.dia_matrix
scipy.sparse.lil_diags
eg. using spdiags :
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)
Using the scipy.sparse module,
p = sparse.dia_matrix(1.0 / np.array(x), shape=(len(x), len(x)));