Accelerating the pace of engineering and science

Documentation Center

• Trials

Operating on Diagonal Matrices

Diagonal Matrix Functions

There are several MATLAB® functions that work specifically on diagonal matrices.

Function

Description

blkdiag

Construct a block diagonal matrix from input arguments.

diag

Return a diagonal matrix or the diagonals of a matrix.

trace

Compute the sum of the elements on the main diagonal.

tril

Return the lower triangular part of a matrix.

triu

Return the upper triangular part of a matrix.

Constructing a Matrix from a Diagonal Vector

The diag function has two operations that it can perform. You can use it to generate a diagonal matrix:

```A = diag([12:4:32])
A =
12     0     0     0     0     0
0    16     0     0     0     0
0     0    20     0     0     0
0     0     0    24     0     0
0     0     0     0    28     0
0     0     0     0     0    32
```

You can also use the diag function to scan an existing matrix and return the values found along one of the diagonals:

```A = magic(5)
A =
17    24     1     8    15
23     5     7    14    16
4     6    13    20    22
10    12    19    21     3
11    18    25     2     9

diag(A, 2)       % Return contents of second diagonal of A
ans =
1
14
22
```

Returning a Triangular Portion of a Matrix

The tril and triu functions return a triangular portion of a matrix, the former returning the piece from the lower left and the latter from the upper right. By default, the main diagonal of the matrix divides these two segments. You can use an alternate diagonal by specifying an offset from the main diagonal as a second input argument:

```A = magic(6);

B = tril(A, -1)
B =
0     0     0     0     0     0
3     0     0     0     0     0
31     9     0     0     0     0
8    28    33     0     0     0
30     5    34    12     0     0
4    36    29    13    18     0
```

Concatenating Matrices Diagonally

You can diagonally concatenate matrices to form a composite matrix using the blkdiag function. See Creating a Block Diagonal Matrix for more information on how this works.