[SciPy-User] create sparse matrix from diagonal arrays

Geordie McBain gdmcbain at freeshell.org
Thu Apr 10 22:53:51 EDT 2014


2014-04-11 12:00 GMT+10:00 Darcoux Christine <bouloumag at gmail.com>:
> I would like to solve a PDE using an implicit finite volume discretization.
> Since the problem is 3D, the matrix should be septadiagonal. I have computed
> the 7 diagonals (for top, bottom, east, west, north south and central point)
> in 7 different arrays.
>
> Now, I would like to create a sparse matrix object from these arrays, but I
> feel a little lost with the documentation of scipy.sparse.spdiags.
>
> Help would be greatly appreciated.

Put the diagonals, padded to the length of the main diagonal
(postpadded for the subdiagonals and prepadded for the superdiagonals,
it doesn't matter what with) as the rows of an array, or elements of a
list or other iterable.

For example, to generate the classical tridiagonal one-dimensional Laplacian:

>>> spdiags([[1, 1, np.nan], [-2, -2, -2], [np.nan, 1, 1]], [-1, 0, 1], 3, 3).toarray()
array([[-2.,  1.,  0.],
       [ 1., -2.,  1.],
       [ 0.,  1., -2.]])



More information about the SciPy-User mailing list