diag

Builds a diagonal matrix from a vector, or extracts a diagonal from a matrix.

Category: Language Fundamentals > Matrices and Arrays

Syntax

D = diag(v)

Square matrix with vector v on the main diagonal.

D = diag(v, k)

Places v on the k-th diagonal: k > 0 above the main one, k < 0 below.

d = diag(A)

Column vector with the main diagonal of matrix A.

d = diag(A, k)

Column vector with the k-th diagonal of A.

Description

The same name does both jobs, decided by the input: a vector builds a matrix and a matrix yields a vector. A matrix with a single row or column counts as a vector, so diag of it builds a matrix.

Applying diag twice to a vector gives back the same vector as a column.

Input arguments

v
Vector whose elements go on the diagonal.
A
Matrix to read a diagonal from.
k
Diagonal index; 0 (default) is the main diagonal.

Output arguments

D
Matrix of size numel(v)+abs(k) per side, zeros off the diagonal.
d
Column vector with the chosen diagonal.

Example

diag([1 2 3])
diag([1 2], 1)
A = [1 2 3; 4 5 6; 7 8 9];
diag(A)'
diag(A, -1)'
Output
ans = 3×3

     1     0     0
     0     2     0
     0     0     3
ans = 3×3

     0     1     0
     0     0     2
     0     0     0
ans = 1×3

     1     5     9
ans = 1×2

     4     8

See also

eye blkdiag tril triu trace