DIAG Diagonal Matrix Construction/Extraction
Section: Array Generation and Manipulations
Usage
Thediag
function is used to either construct a
diagonal matrix from a vector, or return the diagonal
elements of a matrix as a vector. The general syntax
for its use is
y = diag(x,n)
If x
is a matrix, then y
returns the n
-th
diagonal. If n
is omitted, it is assumed to be
zero. Conversely, if x
is a vector, then y
is a matrix with x
set to the n
-th diagonal.
Examples
Here is an example ofdiag
being used to extract
a diagonal from a matrix.
--> A = int32(10*rand(4,5)) A = 2 8 3 2 2 6 8 6 8 5 8 9 3 9 0 8 3 7 8 2 --> diag(A) ans = 2 8 3 8 --> diag(A,1) ans = 8 6 9 2
Here is an example of the second form of diag
, being
used to construct a diagonal matrix.
--> x = int32(10*rand(1,3)) x = 1 1 10 --> diag(x) ans = 1 0 0 0 1 0 0 0 10 --> diag(x,-1) ans = 0 0 0 0 1 0 0 0 0 1 0 0 0 0 10 0