diag

Purpose

Diagonal matrices and diagonals of a matrix.

Synopsis

X = diag(v,k)
X = diag(v)
v = diag(X,k)
v = diag(X)

Description

X = diag(v,k), where v is a vector with n components, returns s a square matrix X of order n+abs(k) with the elements of v on the k-th diagonal. k = 0 is the main diagonal, k > 0 is above the main diagonal, and k < 0 is below the main diagonal.

diag(v) simply puts v on the main diagonal.

v = diag(X,k), where X is a matrix, returns a column vector v formed from the elements of the k-th diagonal of X.

diag(X) is the main diagonal of X.

Examples

diag(diag(X)) is a diagonal matrix.

sum(diag(X)) is the trace of X.

The statement

diag(-m:m)+diag(ones(2*m,1),1)+diag(ones(2*m,1),-1)
produces a tridiagonal matrix of order 2*m+1.

See Also

tril, triu

(c) Copyright 1994 by The MathWorks, Inc.