代码之家  ›  专栏  ›  技术社区  ›  yassin

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

  •  6
  • yassin  · 技术社区  · 14 年前

    我使用numpy在python中有以下代码:

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

    如何转换它以得到稀疏矩阵 p2 值与 p 不创建 第一?

    2 回复  |  直到 11 年前
        1
  •  8
  •   Joe Kington    14 年前

    使用 scipy.sparse.spdiags (起初,这做了很多事情,可能会让人困惑) scipy.sparse.dia_matrix 和/或 scipy.sparse.lil_diags . (取决于 format 你想要稀疏矩阵…)

    例如使用 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)
    
        2
  •  1
  •   Xatan    13 年前

    使用scipy.sparse模块,

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