Skip to Main Content Skip to Search
Product Documentation

diag - Diagonal matrices and diagonals of matrix

Syntax

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

Description

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

X = diag(v) puts v on the main diagonal, same as above with k = 0.

v = diag(X,k) for matrix X, returns a column vector v formed from the elements of the kth diagonal of X.

v = diag(X) returns the main diagonal of X, same as above with k = 0 .

Tips

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

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

diag([]) generates an empty matrix, ([]).

diag(m-by-1,k) generates a matrix of size m+abs(k)-by-m+abs(k).

diag(1-by-n,k) generates a matrix of size n+abs(k)-by-n+abs(k).

Examples

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

blkdiag | spdiags | tril | triu

  


Free MATLAB Interactive Kit

Explore how to use MATLAB to make advancements in engineering and science.


Download free kit

Trials Available

Try the latest version of MATLAB and other MathWorks products.


Get trial software
 © 1984-2012- The MathWorks, Inc.    -   Site Help   -   Patents   -   Trademarks   -   Privacy Policy   -   Preventing Piracy   -   RSS