I have the following code in Python using Numpy:
p = np.diag(1.0 / np.array(x))
How can I transform it to get the sparse matrix p2
with the same values as p
without creating p
first?
Use scipy.sparse.spdiags
(which does a lot, and so may be confusing, at first), scipy.sparse.dia_matrix
and/or scipy.sparse.lil_diags
. (depending on the format you want the sparse matrix in...)
E.g. 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)
Using the scipy.sparse module,
p = sparse.dia_matrix(1.0 / np.array(x), shape=(len(x), len(x)));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With