Skip to content
fn

diagonal

→Tensor
diagonal(A: Tensor, offset: int = 0, dim1: int = -2, dim2: int = -1)

Implementing kernel

C++ engine symbols that back this Python API.

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

Input of shape (*, m, n) (or higher rank).
offset(int, keyword - only)= 0
Diagonal index relative to the main diagonal. Default 0.
dim1(int, keyword - only)= -2
First matrix dimension. Default -2.
dim2(int, keyword - only)= -1
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., 4.])
>>> diagonal(A, offset=1)
tensor([2.])

Used by 1