fn

diagonal

Tensor
diagonal(input: Tensor, offset: int = ..., dim1: int = ..., dim2: int = ...)
source

Extract a (off-)diagonal from each matrix in a batched input.

Returns the elements of AA lying on the diagonal selected by offset from the matrix slice formed by (dim1, dim2). For a 2-D matrix and offset=0 this is

di=Ai,i.d_i \,=\, A_{i,\,i}.

Positive offset selects super-diagonals (Ai,i+offsetA_{i, i + \text{offset}}); negative offsets select sub-diagonals.

Parameters

ATensor
Input of shape (*, m, n) (or higher rank).
offsetint, keyword-only
Diagonal index relative to the main diagonal. Default 0.
dim1int, keyword-only
First matrix dimension. Default -2.
dim2int, keyword-only
Second matrix dimension. Default -1.

Returns

Tensor

Diagonal values with the two matrix axes replaced by a single axis of length min(m,n)offset\min(m, n) - |\text{offset}|.

Notes

Shares the engine kernel with the top-level lucid.diagonal; the only difference is the keyword-only / matrix-aware defaults (dim1=-2, dim2=-1) that match the standard linalg convention.

Examples

>>> import lucid
>>> from lucid.linalg import diagonal
>>> A = lucid.tensor([[1.0, 2.0], [3.0, 4.0]])
>>> diagonal(A)
Tensor([1.0000, 4.0000])
>>> diagonal(A, offset=1)
Tensor([2.0000])