diag

Create or extract diagonals of symbolic matrices

Syntax

diag(A,k)
diag(A)

Description

diag(A,k) returns a square symbolic matrix of order n + abs(k), with the elements of A on the k-th diagonal. A must present a row or column vector with n components. The value k = 0 signifies the main diagonal. The value k > 0 signifies the k-th diagonal above the main diagonal. The value k < 0 signifies the k-th diagonal below the main diagonal. If A is a square symbolic matrix, diag(A, k) returns a column vector formed from the elements of the k-th diagonal of A.

diag(A), where A is a vector with n components, returns an n-by-n diagonal matrix having A as its main diagonal. If A is a square symbolic matrix, diag(A) returns the main diagonal of A.

Examples

Create a symbolic matrix with the main diagonal presented by the elements of 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 one presented by the elements of 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 a b c x y z
A = [a, b, c; 1, 2, 3; x, y, z];
diag(A)
ans =
 a
 2
 z

Extract the first diagonal above the main one:

syms a b c x y z
A = [a, b, c; 1, 2, 3; x, y, z];
diag(A, 1)
ans =
 b
 3

See Also

|

Was this topic helpful?