Programming

Operating on Diagonal Matrices

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
```

 Sorting Row Vectors Returning a Triangular Portion of a Matrix