Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficient way to create a diagonal sparse matrix

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?

like image 338
yassin Avatar asked Sep 12 '10 15:09

yassin


2 Answers

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)
like image 130
Joe Kington Avatar answered Sep 24 '22 23:09

Joe Kington


Using the scipy.sparse module,

p = sparse.dia_matrix(1.0 / np.array(x), shape=(len(x), len(x)));
like image 32
Xatan Avatar answered Sep 25 '22 23:09

Xatan