You are viewing an older version (2.4.3). Go to latest (2.4.4)
{ } Raw JSON

bundles / numpy 2.4.3 / numpy / linalg / diagonal

_ArrayFunctionDispatcher

numpy.linalg:diagonal

source: /numpy/linalg/_linalg.py :3065

Signature

def   diagonal ( x / offset = 0 )

Summary

Returns specified diagonals of a matrix (or a stack of matrices) x.

Extended Summary

This function is Array API compatible, contrary to numpy.diagonal, the matrix is assumed to be defined by the last two dimensions.

Parameters

x : (...,M,N) array_like

Input array having shape (..., M, N) and whose innermost two dimensions form MxN matrices.

offset : int, optional

Offset specifying the off-diagonal relative to the main diagonal, where

* offset = 0: the main diagonal.
* offset > 0: off-diagonal above the main diagonal.
* offset < 0: off-diagonal below the main diagonal.

Returns

out : (...,min(N,M)) ndarray

An array containing the diagonals and whose shape is determined by removing the last two dimensions and appending a dimension equal to the size of the resulting diagonals. The returned array must have the same data type as x.

Examples

a = np.arange(4).reshape(2, 2); a
np.linalg.diagonal(a)
A 3-D example:
a = np.arange(8).reshape(2, 2, 2); a
np.linalg.diagonal(a)
Diagonals adjacent to the main diagonal can be obtained by using the `offset` argument:
a = np.arange(9).reshape(3, 3)
a
np.linalg.diagonal(a, offset=1)  # First superdiagonal
np.linalg.diagonal(a, offset=2)  # Second superdiagonal
np.linalg.diagonal(a, offset=-1)  # First subdiagonal
np.linalg.diagonal(a, offset=-2)  # Second subdiagonal
The anti-diagonal can be obtained by reversing the order of elements using either `numpy.flipud` or `numpy.fliplr`.
a = np.arange(9).reshape(3, 3)
a
np.linalg.diagonal(np.fliplr(a))  # Horizontal flip
np.linalg.diagonal(np.flipud(a))  # Vertical flip
Note that the order in which the diagonal is retrieved varies depending on the flip function.

See also

numpy.diagonal

Aliases

  • numpy.linalg.diagonal

Referenced by