Extract a diagonal from a matrix in Octave
In this lesson I'll explain how to extract a diagonal from a matrix in Octave.
What is the diagonal of a matrix? They are the elements that are on the main diagonal of the matrix.For example, the main diagonal of this matrix are the elements 1, 5, 9. $$ M = \begin{pmatrix} \color{red}1 & 2 & 3 \\ 4 & \color{red}5 & 6 \\ 7 & 8 & \color{red}9 \end{pmatrix} $$
I'll give you a practical example.
Create a 3x3 square matrix with three rows and three columns.
>> M=[1 2 3; 4 5 6; 7 8 9]
M =
1 2 3
4 5 6
7 8 9
To know the number of elements in the main diagonal type diag(M)
>> diag(M)
ans =
1
5
9
The elements in the main diagonal of the matrix are the numbers 1, 5 and 9
$$ M = \begin{pmatrix} \color{red}1 & 2 & 3 \\ 4 & \color{red}5 & 6 \\ 7 & 8 & \color{red}9 \end{pmatrix} $$
To know the elements on the diagonal above the main diagonal type diag(M,1)
>> diag(M,1)
ans =
2
6
This command extracts the numbers 2 and 6 that are on the diagonal above the main one.
$$ M = \begin{pmatrix} 1 & \color{red}2 & 3 \\ 4 & 5 & \color{red}6 \\ 7 & 8 & 9 \end{pmatrix} $$
Now type diag(M,2)
>> diag(M,2)
ans = 3
This way you get the elements on the diagonal even higher and so on.
$$ M = \begin{pmatrix} 1 & 2 & \color{red}3 \\ 4 & 5 & 6 \\ 7 & 8 & 9 \end{pmatrix} $$
To extract the elements of the diagonal under the main diagonal type diag(M,-1)
>> diag(M,-1)
ans =
4
8
This command extracts the elements under the main diagonal.
$$ M = \begin{pmatrix} 1 & 2 & 3 \\ \color{red}4 & 5 & 6 \\ 7 & \color{red}8 & 9 \end{pmatrix} $$
If you want to delete all other elements, except those on the main diagonal, type diag(diag(M))
>> diag(diag(M))
ans =
Diagonal Matrix
1 0 0
0 5 0
0 0 9
This way you get a diagonal matrix.
$$ M = \begin{pmatrix} 1 & 0 & 0 \\ 0 & 5 & 0 \\ 0 & 0 & 9 \end{pmatrix} $$
If you want to extract the antidiagonal or secondary diagonal, flip the matrix by fliplr() function
Type diag(fliplr(M))
>> diag(fliplr(M))
ans =
3
5
7
This command returns the elements on the antidiagonal of the matrix
$$ M = \begin{pmatrix} 1 & 2 & \color{red}3 \\ 4 & \color{red}5 & 6 \\ \color{red}7 & 8 & 9 \end{pmatrix} $$
You can also use the diag () command to extract the elements of a rectangular array.
For example, create a rectangular matrix with 3 rows and 4 columns.
>> M2=[1 1 1 1 ; 2 2 2 2 ; 3 3 3 3]
M2 =
1 1 1 1
2 2 2 2
3 3 3 3
Now type diag(M2)
>> diag(M2)
ans =
1
2
3
This command extracts the elements on the diagonal of the square matrix into the rectangular matrix.
$$ M = \begin{pmatrix} \color{red}1 & 1 & 1 & 1 \\ 2 & \color{red}2 & 2 & 2 \\ 3 & 3 & \color{red}3 & 3 \end{pmatrix} $$