lettura simple

The triangular matrices in Octave

In this lesson I'll explain how to make a triangular matrix in Octave.

What is a triangular matrix? It is a square matrix where only the main diagonal and the elements above (upper triangular) or below (lower triangular) the main diagonal are different from zero. For example, this is a lower triangular matrix $$ T = \begin{pmatrix} 1 & 0 & 0 \\ 2 & 3 & 0 \\ 4 & 5 & 6 \end{pmatrix} $$ This, on the other hand, is a upper triangular matrix.$$ T = \begin{pmatrix} 1 & 2 & 3 \\ 0 & 4 & 5 \\ 0 & 0 & 6 \end{pmatrix} $$

I'll give you a practical example.

Create a square matrix of any size.

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

Now transform the M matrix into a upper triangolar matrix

Type the command triu(M)

The function returns an array in which only the elements on the main diagonal and above the diagonal are nonzero

>> triu(M)
ans =
1 2 3
0 5 6
0 0 9

If you want to create a lower triangular matrix instead, use the command tril(M)

The function returns an array in which only the elements on the main diagonal and below the diagonal are nonzero.

>> tril(M)
ans =
1 0 0
4 5 0
7 8 9

This way you can create triangular matrices of any order.

You can use the triu() and tril() functions on rectangular arrays as well.

For example, create a rectangular matrix

>> 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

Then type triu(M2) and enter

The output function is another rectangular function with elements equal to zero below the diagonal of the largest square matrix that is inside the rectangular matrix

>> triu(M2)
ans =
1 1 1 1
0 2 2 2
0 0 3 3

If you type tril(M2) the result is similar.

In this case the elements equal to zero are above the main diagonal.

>> tril(M2)
ans =
1 0 0 0
2 2 0 0
3 3 3 0




Report a mistake or post a question




FacebookTwitterLinkedinLinkedin