OKPEDIA MATLAB EN MATRICE

How to extract diagonals from a matrix in Matlab and Octave

To extract the diagonals of a matrix in Matlab and Octave use the function diag()

diag(M, k)

The first argument (M) is the matrix.

The second argument (k) is optional. It is an integer that indicates the diagonal to be extracted. By default it is k = 0 and the function extracts the main diagonal of the matrix.

Note. If the first argument of the diag () function is a vector, the function creates a diagonal matrix in which the main diagonal is made up of the elements of the vector.

Examples

Example 1

Define a square matrix

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

It is a 3x3 square matrix

$$ \begin{pmatrix} 1 & 2 & 3 \\ 4 & 5 & 6 \\ 7 & 8 & 9 \end{pmatrix} $$

Extract the main diagonal using the diag function (M)

diag(M)

The function extracts the main diagonal of the matrix

1
5
9

Example 2

To extract the diagonal above the main diagonal, specify the parameter k = 1 in the function diag()

diag(M,1)

The output result is

2
6

Example 3

To extract the diagonal below the main diagonal, use the diag() function with the parameter k =-1

diag(M,-1)

The output result is

4
8

Example 4

To extract the secondary diagonal, mirror the matrix horizontally with the fliplr() function and extract the diagonal with the function diag().

diag(fliplr(M))

The output result is the second diagonal

3
5
7

Example 5

To extract all the diagonals of the matrix with a single command type

>> spdiags(M)

The function outputs all diagonals as array.

Each column vector is a diagonal of the matrix.

7 4 1 0 0
0 8 5 2 0
0 0 9 6 3

The central column vector 1 5 9 is the main diagonal of the matrix.

$$ \begin{pmatrix} \color{red}1 & 2 & 3 \\ 4 & \color{red}5 & 6 \\ 7 & 8 & \color{red}9 \end{pmatrix} $$

The column vector 4 8 0 is the diagonal below the main diagonal.

$$ \begin{pmatrix} 1 &2 & 3 \\ \color{red}4 & 5 & 6 \\ 7 & \color{red}8 & 9 \end{pmatrix} $$

The column vector 0 2 6 is the diagonal above the main diagonal.

$$ \begin{pmatrix} 1 & \color{red}2 & 3 \\ 4 & 5 & \color{red}6 \\ 7 & 8 & 9 \end{pmatrix} $$

https://how.okpedia.org/en/matlab/how-to-extract-diagonals-from-a-matrix-in-matlab-and-octave


Report an error or share a suggestion to enhance this page


Matrix in Matlab/Octave


FacebookTwitterLinkedinLinkedin