Main Content

diag

Create diagonal matrix or get diagonals from symbolic matrices

Description

example

D = diag(v) returns a square diagonal matrix with vector v as the main diagonal.

example

D = diag(v,k) places vector v on the kth diagonal. k = 0 represents the main diagonal, k > 0 is above the main diagonal, and k < 0 is below the main diagonal.

example

x = diag(A) returns the main diagonal of A.

example

x = diag(A,k) returns the kth diagonal of A.

Examples

collapse all

Create a symbolic matrix with the main diagonal specified by the vector v.

syms a b c
v = [a b c];
diag(v)
ans =
[ a, 0, 0]
[ 0, b, 0]
[ 0, 0, c]

Create a symbolic matrix with the second diagonal below the main diagonal specified by the vector v.

syms a b c
v = [a b c];
diag(v,-2)
ans =
[ 0, 0, 0, 0, 0]
[ 0, 0, 0, 0, 0]
[ a, 0, 0, 0, 0]
[ 0, b, 0, 0, 0]
[ 0, 0, c, 0, 0]

Extract the main diagonal from a square matrix.

syms x y z
A = magic(3).*[x, y, z];
diag(A)
ans =
 8*x
 5*y
 2*z

Extract the first diagonal above the main diagonal.

syms x y z
A = magic(3).*[x, y, z];
diag(A,1)
ans =
   y
 7*z

Input Arguments

collapse all

Diagonal elements, specified as a symbolic vector. If v is a vector with N elements, then diag(v,k) is a square matrix of order N + abs(k).

Input matrix, specified as a symbolic matrix.

Diagonal number, specified as an integer. k = 0 represents the main diagonal, k > 0 is above the main diagonal, and k < 0 is below the main diagonal.

Tips

  • The trace of a matrix is equal to sum(diag(A)).

Version History

Introduced before R2006a

See Also

|