lettura simple

Triangular Matrices in Matlab

In this lesson, I will explain how to create triangular matrices using Matlab.

What are triangular matrices? A square matrix is called a triangular matrix if it has non-zero elements only on the main diagonal and above (upper triangular) or below (lower triangular) the main diagonal. The other elements of the matrix are zero. For example, this matrix is a lower triangular matrix. $$ T = \begin{pmatrix} 1 & 0 & 0 \\ 2 & 3 & 0 \\ 4 & 5 & 6 \end{pmatrix} $$ And this matrix is an upper triangular matrix. $$ T = \begin{pmatrix} 1 & 2 & 3 \\ 0 & 4 & 5 \\ 0 & 0 & 6 \end{pmatrix} $$

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

Type triu(M) to transform the square matrix M into an upper triangular matrix.

The triu() function sets all the elements of matrix M below the main diagonal to zero.

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

Type tril(M) if you want to transform the matrix M into a lower triangular matrix.

The tril() function sets all the elements of matrix M above the main diagonal to zero.

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

This way, you can create upper and lower triangular matrices from a square matrix of any order.

Matlab allows you to use the triu() and tril() functions on a rectangular matrix as well.

For example, create a 3x4 rectangular matrix with three rows and four 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

Then type triu(M2) and press enter.

The function generates another rectangular matrix by setting the elements below the diagonal, starting from the top left element, to zero.

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

If you type tril(M2), you will get the opposite result.

In this case, the function sets the elements of the matrix above the diagonal to zero.

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




Report a mistake or post a question




FacebookTwitterLinkedinLinkedin