lettura simple

How to extract all diagonals from a matrix in Octave

In this lesson I'll explain how to extract all matrix diagonals in Octave with a practical example.

 

What are the diagonals of a matrix? These are the elements found on the diagonals that start at the top right and end at the bottom left and vice versa. For example, the main diagonal of this matrix consists of 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} $$ La diagonale secondaria è composta dagli elementi 3, 5, 7 $$ M = \begin{pmatrix} 1 & 2 & \color{red}3 \\ 4 & \color{red}5 & 6 \\ \color{red}7 & 8 & 9 \end{pmatrix} $$

I'll give you a practical example.

Make a 3x3 matrix

>> M=[1 2 3 ; 4 5 6 ; 7 8 9]
M =
1 2 3
4 5 6
7 8 9

To extract all the diagonals, type spdiags()

>> spdiags(M)
ans =
7 4 1 0 0
0 8 5 2 0
0 0 9 6 3

Each column of the output matrix is a diagonal of the matrix M

The central red column is the main diagonal which consists of the numbers 1, 5, 9.

all diagonals of matrix

If you want to extract only the main diagonal type spdiags(M,0)

>> spdiags(M,0)
ans =
1
5
9

To extract the diagonal above the main diagonal type spdiags(M,1)

>> spdiags(M,1)
ans =
0
2
6

To extract the diagonal under the main diagonal, type spdiags(M,-1)

>> spdiags(M,-1)
ans =
4
8
0

If you want to extract all the secondary diagonals of the matrix M, use spdiags() and fliplr()

The fliplr function flips the matrix M from left to right.

Type spdiags(fliplr(M))

>> spdiags(fliplr(M))
ans =
9 6 3 0 0
0 8 5 2 0
0 0 7 4 1

Each column of the matrix is a diagonal of the matrix from left to right.

The red central column is the secondary diagonal of the matrix which is made up of the numbers 3, 5, 7.

all secondary diagonals of matrix

This way you can extract any diagonal from the matrix.




Report a mistake or post a question




FacebookTwitterLinkedinLinkedin