我使用 Numpy 在 Python 中有以下代码:
p = np.diag(1.0 / np.array(x))
如何转换它以获得与不先创建p2
值相同的稀疏矩阵?p
p
我使用 Numpy 在 Python 中有以下代码:
p = np.diag(1.0 / np.array(x))
如何转换它以获得与不先创建p2
值相同的稀疏矩阵?p
p
使用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)
使用 scipy.sparse 模块,
p = sparse.dia_matrix(1.0 / np.array(x), shape=(len(x), len(x)));