Diagonal

Shipping
array_diag

numpy diag: 1-D input → diagonal matrix, 2-D input → extract the k-th diagonal

Signature

Inputs

  • aSignal|ArrayrequiredA 1-D array (→ build a diagonal matrix) or a 2-D array (→ extract its k-th diagonal). Anything of rank ≥ 3 is an error.

Outputs

  • resultArrayFor a 1-D input: a square Matrix with the values on the k-th diagonal. For a 2-D input: a 1-D Vector holding the extracted k-th diagonal.

Parameters

KeyTypeDefaultNotes
kint0Which diagonal: 0 = main, >0 above, <0 below. A 1-D input builds a matrix with the values on this diagonal; a 2-D input extracts this diagonal.

Description

Diagonal is numpy's dual diag operator — the only array builder with an input. Its behaviour flips on the input rank:

  • 1-D input → build a square matrix with the input values placed on the -th diagonal (zeros elsewhere). Side length is .
  • 2-D inputextract the -th diagonal as a 1-D Vector.

The Diagonal (k) offset selects which diagonal in both directions: is above the main diagonal, below. A rank-3+ input is a hard error. The build and extract paths are exact inverses on the main diagonal (). Stateless.

Mathematics

Examples

Vector → diagonal matrix

Feed the Vector with k = 0. Output is .

Matrix → its diagonal

Feed a 2×2 Matrix with k = 0. Output is the Vector . Set k = 1 on the same matrix and you get (the single super-diagonal entry).

Applications

  • Turning a vector of eigenvalues or gains into a diagonal weighting matrix.
  • Reading the diagonal (variances / self-terms) out of a covariance or Gram matrix.
  • Constructing sub/super-diagonal skeletons for banded operators.

Neat

One node, two numpy behaviours, disambiguated purely by input rank — a 1-D fixture builds, a 2-D fixture extracts, matching `np.diag`'s famous overloaded contract.

The built matrix's side length grows with |k| (len + |k|) so the whole off-diagonal band fits — an off-main diagonal never truncates the input values.

Known issues

Inputs of rank ≥ 3 are rejected with an error (diag is only defined for 1-D and 2-D).

Extraction from a non-square matrix stops at the shorter dimension, and an out-of-range k yields an empty diagonal.

The result never carries a unit (the string is emptied on both paths).

See also

arraymatrixvectordiagonalnumpytransformstateless