Language Reference


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 25.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 25.103: Diagonal Matrix Obtained from a Vector

d
1 0 0
0 2 0
0 0 3



The DIAG function is useful, but is not always necessary. Most multiplication operations with diagonal matrices can be accomplished by using the elementwise multiplication operator . To add or subtract from the diagonal of a matrix, you can directly reference the matrix elements, as shown in the following example:

A = j(5,5,1);
v = T(1:5);
D = diag(v);

/* overwrite A with A + diag(v) */
/* method 1: less efficient */
A = j(5,5,1);
A = A + diag(v);         /* explicitly form 5x5 diagonal matrix */

/* method 2: more efficient */
A = j(5,5,1);
j = do(1, ncol(A)*nrow(A), ncol(A)+1);      /* {1 7 13 19 25} */
A[j] = vecdiag(A) + v;   /* access diagonal elements directly */