This is a pre-release version (2.0.0.dev0+git20260907.41eeb59).Go to latest (1.18.0)
{ } Raw JSON

bundles / scipy 2.0.0.dev0+git20260907.41eeb59 / scipy / sparse / _construct / diags

function

scipy.sparse._construct:diags

source: build-install/usr/lib/python3.14/site-packages/scipy/sparse/_construct.py:467

Signature

def diags(diagonals, offsets = 0, shape = None, format = None, dtype = None)

Summary

Construct a sparse matrix from diagonals.

Extended Summary

Parameters

diagonals : sequence of array_like

Sequence of arrays containing the matrix diagonals, corresponding to offsets.

offsets : sequence of int or an int, optional

Diagonals to set (repeated offsets are not allowed):

  • k = 0 the main diagonal (default)

  • k > 0 the kth upper diagonal

  • k < 0 the kth lower diagonal

shape : tuple of int, optional

Shape of the result. If omitted, a square matrix large enough to contain the diagonals is returned.

format : {"dia", "csr", "csc", "lil", ...}, optional

Matrix format of the result. By default (format=None) an appropriate sparse matrix format is returned. This choice is subject to change.

dtype : dtype, optional

Data type of the matrix. If dtype is None, the output data type is determined by the data type of the input diagonals.

Returns

new_matrix : dia_matrix

dia_matrix holding the values in diagonals offset from the main diagonal as indicated in offsets.

Notes

Repeated diagonal offsets are disallowed.

The result from diags is the sparse equivalent of

np.diag(diagonals[0], offsets[0])
+ ...
+ np.diag(diagonals[k], offsets[k])

diags differs from dia_matrix in the way it handles off-diagonals. Specifically, dia_matrix assumes the data input includes padding (ignored values) at the start/end of the rows for positive/negative offset, while diags assumes the input data has no padding. Each value in the input diagonals is used.

Examples

from scipy.sparse import diags
diagonals = [[1.0, 2.0, 3.0, 4.0], [1.0, 2.0, 3.0], [1.0, 2.0]]
✓
Broadcasting of scalars is supported (but shape needs to be specified): If only one diagonal is wanted (as in `numpy.diag`), the following works as well:

See also

diags_array

construct sparse array instead of sparse matrix

spdiags

construct matrix from diagonals

Aliases

  • scipy.sparse.diags

Referenced by