
Diagonal matrix in Octave
In this lesson I'll explain how to create a diagonal matrix in Octave.
What is the diagonal matrix? It is a square matrix where the elements on the main diagonal are different from zero. All other elements of the matrix are null. This is an example of a diagonal matrix $$ M = \begin{pmatrix} 1 & 0 & 0 & 0 \\ 0 & 2 & 0 & 0 \\ 0 & 0 & 3 & 0 \\ 0 & 0 & 0 & 4 \end{pmatrix} $$
I'll give you a practical example.
Create a number vector with 4 elements.
>> v=[1 2 3 4]
v =
1 2 3 4
Now type the command diag(v)
The output result is a 4x4 diagonal matrix with four rows and four columns.
>> diag(v)
ans =
Diagonal Matrix
1 0 0 0
0 2 0 0
0 0 3 0
0 0 0 4
The elements on the main diagonal of the matrix are the numbers 1, 2, 3, 4 that you indicated in the vector
All other elements of the matrix are null.
$$ M = \begin{pmatrix} \color{red}1 & 0 & 0 & 0 \\ 0 & \color{red}2 & 0 & 0 \\ 0 & 0 & \color{red}3 & 0 \\ 0 & 0 & 0 & \color{red}4 \end{pmatrix} $$
You can also get the same result by typing diag([1 2 3 4]) without defining a vector.
>> diag([1 2 3 4])
ans =
Diagonal Matrix
1 0 0 0
0 2 0 0
0 0 3 0
0 0 0 4
To create a 3x3 diagonal matrix type diag([3 4 1])
>> diag([3 4 1])
ans =
Diagonal Matrix
3 0 0
0 4 0
0 0 1
This way you can define any diagonal matrix.