8

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?

2 Answers 2

11

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)
Sign up to request clarification or add additional context in comments.

Comments

1

Using the scipy.sparse module,

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.