How to create a diagonal matrix in Matlab and Octave
To create a diagonal matrix in Matlab or Octave, use the function diag()
diag(V,k)
The first parameter (V) is the vector with the elements of the diagonal.
The second parameter (k) is an integer indicating the position of the diagonal. By default it is k = 0.
What is a diagonal matrix? A diagonal matrix is a square matrix with non-zero elements on the main diagonal and zero in the other positions. An example of a 4x4 diagonal matrix $$ M= \begin{pmatrix} 3 & 0 & 0 & 0 \\ 0 & 2 & 0 & 0 \\ 0 & 0 & 5 & 0 \\ 0 & 0 & 0 & 1 \end{pmatrix} $$
Examples
Example 1
Define a diagonal matrix with the elements 1 2 3 in the main diagonal
diag([1,2,3])
The output result is a 3x3 square matrix
$$ \begin{pmatrix} 1 & 0 & 0 \\ 0 & 2 & 0 \\ 0 & 0 & 3 \end{pmatrix} $$
Example 2
To create a diagonal matrix with the elements 1 2 3 above the main diagonal, use the diag () function with the second parameter k = 1.
diag([1,2,3], 1)
The output result is a 4x4 square matrix
$$ \begin{pmatrix} 0 & 1 & 0 & 0 \\ 0 & 0 & 2 & 0 \\ 0 & 0 & 0 & 3 \\ 0 & 0 & 0 & 0 \end{pmatrix} $$
Example 3
To create a diagonal matrix with the elements 1 2 3 under the main diagonal, use the diag () function with the second parameter k = -1.
diag([1,2,3], -1)
The output result is a 4x4 square matrix
$$ \begin{pmatrix} 0 & 0 & 0 & 0 \\ 1 & 0 & 0 & 0 \\ 0 & 2 & 0 & 0 \\ 0 & 0 & 3 & 0 \end{pmatrix} $$