dgl.sparse.diag

dgl.sparse.diag(val: torch.Tensor, shape: Optional[Tuple[int, int]] = None)dgl.sparse.diag_matrix.DiagMatrix[source]

Creates a diagonal matrix based on the diagonal values.

Parameters
  • val (torch.Tensor) – Diagonal of the matrix, in shape (N) or (N, D)

  • shape (tuple[int, int], optional) – If specified, len(val) must be equal to min(shape), otherwise, it will be inferred from val, i.e., (N, N)

Returns

Diagonal matrix

Return type

DiagMatrix

Examples

Case1: 5-by-5 diagonal matrix with scaler values on the diagonal

>>> import torch
>>> val = torch.ones(5)
>>> dglsp.diag(val)
DiagMatrix(val=tensor([1., 1., 1., 1., 1.]),
           shape=(5, 5))

Case2: 5-by-10 diagonal matrix with scaler values on the diagonal

>>> val = torch.ones(5)
>>> dglsp.diag(val, shape=(5, 10))
DiagMatrix(val=tensor([1., 1., 1., 1., 1.]),
           shape=(5, 10))

Case3: 5-by-5 diagonal matrix with vector values on the diagonal

>>> val = torch.randn(5, 3)
>>> D = dglsp.diag(val)
>>> D.shape
(5, 5)
>>> D.nnz
5