Creating a diagonal matrix in Matlab
The diag() function in Matlab offers a straightforward way to create a diagonal matrix.
diag(v, k)
- The first parameter, v, is an array or vector containing the values to place along the matrix's diagonal.
- The second parameter, k, is an integer that indicates the diagonal’s position relative to the main diagonal. By default, k = 0 targets the main diagonal.
For example, let’s begin by creating an array with the elements 1, 4, and 2:
Next, I use the diag(v) function to generate a diagonal matrix, placing the elements 1, 4, and 2 along the main diagonal:
To shift the diagonal above the main one, I can set the k parameter to a positive integer (e.g., 1, 2, 3, ...):
Alternatively, using a negative value for k (such as -1, -2, -3) moves the diagonal below the main one:
For instance, k = -1 refers to the diagonal just below the main diagonal.