# dgl.sparse.diagο

dgl.sparse.diag(val: Tensor, shape: Tuple[int, int] | None = None) SparseMatrix[source]ο

Creates a sparse 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:

Sparse matrix

Return type:

SparseMatrix

Examples

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

```>>> import torch
>>> val = torch.ones(5)
>>> dglsp.diag(val)
SparseMatrix(indices=tensor([[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4]]),
values=tensor([1., 1., 1., 1., 1.]),
shape=(5, 5), nnz=5)
```

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

```>>> val = torch.ones(5)
>>> dglsp.diag(val, shape=(5, 10))
SparseMatrix(indices=tensor([[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4]]),
values=tensor([1., 1., 1., 1., 1.]),
shape=(5, 10), nnz=5)
```

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
```