DIAG Function

DIAG (matrix) ;

The DIAG function creates a diagonal matrix. The matrix argument can be either a numeric square matrix or a vector.

If matrix is a square matrix, the DIAG function creates a matrix with diagonal elements equal to the corresponding diagonal elements. All off-diagonal elements in the new matrix are zeros.

If matrix is a vector, the DIAG function creates a matrix with diagonal elements that are the values in the vector. All off-diagonal elements are zeros.

For example, the following statements produce a diagonal matrix by extracting the diagonal elements of a square matrix:

  a = {4 3,
       2 1};
  c = diag(a);
  print c;

Figure 24.102: Diagonal Matrix Obtained from a Full Matrix

c
4 0
0 1


The following statements produce a diagonal matrix by using the elements of a vector:

  b = {1 2 3};
  d = diag(b);
  print d;

Figure 24.103: Diagonal Matrix Obtained from a Vector

d
1 0 0
0 2 0
0 0 3