diag
Extract a diagonal, or build a matrix from a diagonal.
Syntax
Section titled “Syntax”X = diag(v)X = diag(v, k)v = diag(A)v = diag(A, k)Description
Section titled “Description”Dual-purpose function:
- When the input is a vector
v, returns a square matrix withvon the main diagonal (or on thek-th diagonal — positivekabove, negativekbelow). - When the input is a matrix
A, returns the column vector of its main-diagonal entries (or itsk-th diagonal).
Examples
Section titled “Examples”diag([1 2 3]) % 3×3 with 1, 2, 3 on the diagonaldiag(magic(3)) % column vector [8; 5; 2]diag([1 2 3], 1) % 4×4 with 1, 2, 3 on the +1 superdiagonal