mindspore.numpy.diag

mindspore.numpy.diag(v, k=0)[source]

Extracts a diagonal or construct a diagonal array.

Parameters
  • v (Tensor) – If v is a 2-D array, return a copy of its k-th diagonal. If v is a 1-D array, return a 2-D array 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.

Returns

Tensor, the extracted diagonal or constructed diagonal array.

Raises

ValueError – if input is not 1-D or 2-D.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore.numpy as np
>>> x = np.arange(9).reshape((3,3))
>>> print(x)
[[0 1 2]
[3 4 5]
[6 7 8]]
>>> output = np.diag(x)
>>> print(output)
[0 4 8]
>>> output = np.diag(x, k=1)
>>> print(output)
[1 5]
>>> output = np.diag(x, k=-1)
>>> print(output)
[3 7]