×

Python Tutorial

Python Basics

Python I/O

Python Operators

Python Conditions & Controls

Python Functions

Python Strings

Python Modules

Python Lists

Python OOPs

Python Arrays

Python Dictionary

Python Sets

Python Tuples

Python Exception Handling

Python NumPy

Python Pandas

Python File Handling

Python WebSocket

Python GUI Programming

Python Image Processing

Python Miscellaneous

Python Practice

Python Programs

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


Comments and Discussions!

Load comments ↻


Advertisement
Advertisement
Advertisement

Copyright © 2025 www.includehelp.com. All rights reserved.