diags#
- scipy.sparse.diags(diagonals,offsets=0,shape=None,format=None,dtype=<objectobject>)[source]#
Construct a sparse matrix from diagonals.
Warning
This function returns a sparse matrix – not a sparse array.You are encouraged to use
diags_arrayto take advantageof the sparse array functionality.- Parameters:
- diagonalssequence of array_like
Sequence of arrays containing the matrix diagonals,corresponding tooffsets.
- offsetssequence 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
- shapetuple of int, optional
Shape of the result. If omitted, a square matrix large enoughto contain the diagonals is returned.
- format{“dia”, “csr”, “csc”, “lil”, …}, optional
Matrix format of the result. By default (format=None) anappropriate sparse matrix format is returned. This choice issubject to change.
- dtypedtype, optional
Data type of the matrix. Ifdtype is None, the outputdata type is determined by the data type of the input diagonals.
Up until SciPy 1.19, the default behavior will be to return a matrixwith an inexact (floating point) data type. In particular, integerinput will be converted to double precision floating point. Thisbehavior is deprecated, and in SciPy 1.19, the default behaviorwill be changed to return a matrix with the same data type as theinput diagonals. To adopt this behavior before version 1.19, usedtype=None.
- Returns:
- new_matrixdia_matrix
dia_matrixholding the values indiagonals offset from the main diagonalas indicated inoffsets.
See also
spdiagsconstruct matrix from diagonals
diags_arrayconstruct sparse array instead of sparse matrix
Notes
Repeated diagonal offsets are disallowed.
The result from
diagsis the sparse equivalent of:np.diag(diagonals[0],offsets[0])+...+np.diag(diagonals[k],offsets[k])
diagsdiffers fromdia_matrixin the way it handles off-diagonals.Specifically,dia_matrixassumes the data input includes padding(ignored values) at the start/end of the rows for positive/negativeoffset, whilediagsassumes the input data has no padding.Each value in the inputdiagonals is used.Added in version 0.11.
Examples
>>>fromscipy.sparseimportdiags>>>diagonals=[[1.0,2.0,3.0,4.0],[1.0,2.0,3.0],[1.0,2.0]]>>>diags(diagonals,[0,-1,2]).toarray()array([[1., 0., 1., 0.], [1., 2., 0., 2.], [0., 2., 3., 0.], [0., 0., 3., 4.]])
Broadcasting of scalars is supported (but shape needs to bespecified):
>>>diags([1.0,-2.0,1.0],[-1,0,1],shape=(4,4)).toarray()array([[-2., 1., 0., 0.], [ 1., -2., 1., 0.], [ 0., 1., -2., 1.], [ 0., 0., 1., -2.]])
If only one diagonal is wanted (as in
numpy.diag), the followingworks as well:>>>diags([1.0,2.0,3.0],1).toarray()array([[ 0., 1., 0., 0.], [ 0., 0., 2., 0.], [ 0., 0., 0., 3.], [ 0., 0., 0., 0.]])