dpnp.diagonal

dpnp.diagonal(a, offset=0, axis1=0, axis2=1)[source]

Return specified diagonals.

This function always returns a read/write view, and writing to the returned array will alter your original array.

If you need to modify the array returned by this function without affecting the original array, we suggest copying the returned array explicitly, i.e., use dpnp.diagonal(a).copy() instead of dpnp.diagonal(a).

For full documentation refer to numpy.diagonal.

Parameters:
  • a ({dpnp.ndarray, usm_ndarray}) -- 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 (0).

  • 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 (1).

Returns:

array_of_diagonals -- Array is a read/write view. If a is 2-D, then a 1-D array containing the diagonal and of the same type as a is returned. 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.

Return type:

dpnp.ndarray

See also

dpnp.linalg.diagonal

Array API compatible version.

dpnp.diag

Extract a diagonal or construct a diagonal array.

dpnp.diagflat

Create a two-dimensional array with the flattened input as a diagonal.

dpnp.trace

Return the sum along diagonals of the array.

Examples

>>> import dpnp as np
>>> a = np.arange(4).reshape(2,2)
>>> a
array([[0, 1],
       [2, 3]])
>>> a.diagonal()
array([0, 3])
>>> a.diagonal(1)
array([1])

A 3-D example:

>>> a = np.arange(8).reshape(2,2,2)
>>> a
array([[[0, 1],
        [2, 3]],
       [[4, 5],
        [6, 7]]])
>>> a.diagonal(0,  # Main diagonals of two arrays created by skipping
...            0,  # across the outer(left)-most axis last and
...            1)  # the "middle" (row) axis first.
array([[0, 6],
       [1, 7]])

The sub-arrays whose main diagonals we just obtained; note that each corresponds to fixing the right-most (column) axis, and that the diagonals are "packed" in rows.

>>> a[:,:,0]  # main diagonal is [0 6]
array([[0, 2],
       [4, 6]])
>>> a[:,:,1]  # main diagonal is [1 7]
array([[1, 3],
       [5, 7]])

The anti-diagonal can be obtained by reversing the order of elements using either dpnp.flipud or dpnp.fliplr.

>>> a = np.arange(9).reshape(3, 3)
>>> a
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])
>>> np.fliplr(a).diagonal()  # Horizontal flip
array([2, 4, 6])
>>> np.flipud(a).diagonal()  # Vertical flip
array([6, 4, 2])

Note that the order in which the diagonal is retrieved varies depending on the flip function.