mindspore.numpy.diagonal
- mindspore.numpy.diagonal(a, offset=0, axis1=0, axis2=1)[源代码]
Returns specified diagonals.
If a is 2-D, returns the diagonal of a with the given offset, i.e., the collection of elements of the form
a[i, i+offset]
. If a has more than two dimensions, then the axes specified by axis1 and axis2 are used to determine the 2-D sub-array whose diagonal is returned. The shape of the resulting array can be determined by removing axis1 and axis2 and appending an index to the right equal to the size of the resulting diagonals.- Parameters
a (Tensor) – Array from which the diagonals are taken.
offset (int, optional) – Offset of the diagonal from the main diagonal. Can be positive or negative. Defaults to main diagonal.
axis1 (int, optional) – Axis to be used as the first axis of the 2-D sub-arrays from which the diagonals should be taken. Defaults to first axis (0).
axis2 (int, optional) – Axis to be used as the second axis of the 2-D sub-arrays from which the diagonals should be taken. Defaults to second axis.
- Returns
Tensor, if a is 2-D, then a 1-D array containing the diagonal. If
a.ndim > 2
, then the dimensions specified by axis1 and axis2 are removed, and a new axis inserted at the end corresponding to the diagonal.- Raises
ValueError – If the input tensor has less than two dimensions.
- Supported Platforms:
Ascend
GPU
CPU
Examples
>>> import mindspore.numpy as np >>> a = np.arange(4).reshape(2,2).astype(np.float32) >>> print(a) [[0. 1.] [2. 3.]] >>> output = np.diagonal(a) >>> print(output) [0. 3.] >>> output = np.diagonal(a, 1) >>> print(output) [1.] >>> a = np.arange(8).reshape(2, 2, 2).astype(np.float32) >>> print(a) [[[0. 1.] [2. 3.]] [[4. 5.] [6. 7.]]] >>> output = np.diagonal(a, 0, 0, 1) >>> print(output) [[0. 6.] [1. 7.]]