Skip to content

diag

Creating diagonal matrix, or extracting diagonal elements

diag(A)

  • If A is a vector, it returns a matrix whose diagonal elements are given by A, and off-diagonal elements are all zeros.
  • If A is a matrix, it returns a row vector containing the diagonal elements of A.
  • If A is a scalar, it returns A.
  • If A is empty, it returns an empty array.
  • A cannot have more than 2 dimensions.

X = diag(A, k)

  • k should be an integer.
  • If k is zero, it gives the same result as diag(A).
  • When A is a vector and

    • if k > 0, it returns a matrix whose upper k-th diagonal elements are given by A. See Example 1 below.
    • if k < 0, it returns a matrix whose lower k-th diagonal elements are given by A. See Example 2 below.
  • When A is a matrix and

    • if k > 0, it returns the upper k-th diagonal. See Example 3 below.
    • if k < 0, it returns the lower k-th diagonal. See Example 4 below.
  • A cannot have more than 2 dimensions.

Example 1:

v=[10 20 30];
X=diag(v,3)
X =
0.000   0.000   0.000   10.00   0.000   0.000
0.000   0.000   0.000   0.000   20.00   0.000
0.000   0.000   0.000   0.000   0.000   30.00
0.000   0.000   0.000   0.000   0.000   0.000
0.000   0.000   0.000   0.000   0.000   0.000
0.000   0.000   0.000   0.000   0.000   0.000

Example 2:

v=[10 20 30];
X=diag(v,-3)
X =
0.000   0.000   0.000   0.000   0.000   0.000
0.000   0.000   0.000   0.000   0.000   0.000
0.000   0.000   0.000   0.000   0.000   0.000
10.00   0.000   0.000   0.000   0.000   0.000
0.000   20.00   0.000   0.000   0.000   0.000
0.000   0.000   30.00   0.000   0.000   0.000

Example 3:

A=randi(10,5,5)
diag(A, 3)
A =
6.000   5.000   4.000   5.000   7.000
1.000   1.000   6.000   1.000   8.000
7.000   9.000   5.000   2.000   10.00
5.000   9.000   8.000   1.000   10.00
5.000   5.000   5.000   5.000   3.000

ans = 
5.000   8.000

Example 4:

A=randi(10,5,5)
diag(A, -3)
A =
10.00   10.00   2.000   6.000   8.000
6.000   9.000   7.000   3.000   5.000
9.000   9.000   4.000   1.000   4.000
3.000   2.000   7.000   2.000   6.000
1.000   4.000   8.000   8.000   6.000

ans = 
3.000   4.000