Search code examples
pythonnumpyscipysparse-matrix

Efficient way to create a diagonal sparse matrix


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?


Solution

  • 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)