7

我使用 Numpy 在 Python 中有以下代码:

p = np.diag(1.0 / np.array(x))

如何转换它以获得与不先创建p2值相同的稀疏矩阵?pp

4

2 回答 2

10

使用scipy.sparse.spdiags(它做了很多,所以一开始可能会令人困惑)scipy.sparse.dia_matrix和/或scipy.sparse.lil_diags. (取决于你想要稀疏矩阵的格式......)

例如使用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)
于 2010-09-12T16:06:30.363 回答
1

使用 scipy.sparse 模块,

p = sparse.dia_matrix(1.0 / np.array(x), shape=(len(x), len(x)));
于 2010-12-10T22:13:48.377 回答