开发者

Efficient way to create a diagonal sparse matrix

开发者 https://www.devze.com 2023-01-15 15:44 出处:网络
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 firs

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)));
0

精彩评论

暂无评论...
验证码 换一张
取 消