mars.tensor.diag(v, k=0, sparse=None, gpu=False, chunk_size=None)[source]

Extract a diagonal or construct a diagonal tensor.

See the more detailed documentation for mt.diagonal if you use this function to extract a diagonal and wish to write to the resulting tensor

  • v (array_like) – If v is a 2-D tensor, return its k-th diagonal. If v is a 1-D tensor, return a 2-D tensor with v on the k-th diagonal.

  • k (int, optional) – Diagonal in question. The default is 0. Use k>0 for diagonals above the main diagonal, and k<0 for diagonals below the main diagonal.

  • sparse (bool, optional) – Create sparse tensor if True, False as default

  • gpu (bool, optional) – Allocate the tensor on GPU if True, False as default

  • chunk_size (int or tuple of int or tuple of ints, optional) – Desired chunk size on each dimension


out – The extracted diagonal or constructed diagonal tensor.

Return type


See also


Return specified diagonals.


Create a 2-D array with the flattened input as a diagonal.


Sum along diagonals.


Upper triangle of a tensor.


Lower triangle of a tensor.


>>> import mars.tensor as mt
>>> x = mt.arange(9).reshape((3,3))
>>> x.execute()
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])
>>> mt.diag(x).execute()
array([0, 4, 8])
>>> mt.diag(x, k=1).execute()
array([1, 5])
>>> mt.diag(x, k=-1).execute()
array([3, 7])
>>> mt.diag(mt.diag(x)).execute()
array([[0, 0, 0],
       [0, 4, 0],
       [0, 0, 8]])