# Python | Upper Triangle of a Matrix

Upper Triangle of a Matrix in Python: Here, we are going to learn about the Upper Triangle of a Matrix and how to find it using Python code?
Submitted by Anuj Singh, on July 17, 2020

A matrix can be seen in different ways and one of them is the upper triangular matrix part. Some problems in linear algebra are concerned with the upper triangular part of the matrix.

For this purpose, we have a predefined function numpy.triu(a) in the NumPy library package which automatically stores the upper triangular elements in a separate matrix. In this article, we are going to print the upper triangular elements of a matrix using inbuilt function numpy.triu(a).

## Python code to find upper triangle of a matrix

```# Linear Algebra Learning Sequence
# Upper Triangle of matrix

import numpy as np

print('Upper Triangle of an 3x3 identity matrix : ', np.triu(np.eye(3)))

a = np.arange(9).reshape((3,3))

print('\n\nMatrix a :\n', a)
print('Upper Triangle of Matrix a :\n', np.triu(a))

b = np.triu(np.array([[1,2,3],[4,5,6],[7,8,9],[10,11,12]]))
print('\n\nMatrix b :\n', np.array([[1,2,3],[4,5,6],[7,8,9],[10,11,12]]))
print('Upper Triangle of Matrix b : ', b)
```

Output:

```Upper Triangle of an 3x3 identity matrix :  [[1. 0. 0.]
[0. 1. 0.]
[0. 0. 1.]]

Matrix a :
[[0 1 2]
[3 4 5]
[6 7 8]]
Upper Triangle of Matrix a :
[[0 1 2]
[0 4 5]
[0 0 8]]

Matrix b :
[[ 1  2  3]
[ 4  5  6]
[ 7  8  9]
[10 11 12]]
Upper Triangle of Matrix b :  [[1 2 3]
[0 5 6]
[0 0 9]
[0 0 0]]
```

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates