高效创建对角稀疏矩阵的方法

8 投票
2 回答
9406 浏览
提问于 2025-04-16 04:02

我有以下使用Numpy的Python代码:

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

我该如何转换它,以便直接得到稀疏矩阵p2,使其与p的值相同,而不需要先创建p呢?

2 个回答

1

使用scipy.sparse模块,

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

使用 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)

撰写回答