Python Program for Lower & Upper Triangle of Matrix
Master Python with 70+ Hands-on Projects and Get Job-ready - Learn Python
In this article, we will explore a Python program that focuses on extracting the lower and upper triangles, as well as the diagonal elements, from a given matrix. Matrices are fundamental in various scientific and computational applications, and understanding these triangular and diagonal components is essential for certain computations. The program demonstrates how to create a matrix with user input and then extracts its lower and upper triangles, along with the diagonal elements.
Prerequisites
- Fundamental Python Knowledge (Variables, Data Types, Syntax)
- Basic Familiarity with the NumPy Library (Numerical Computing, Basic Array Operations)
Topic Explanation
This program initiates by soliciting user input for the number of rows and columns, allowing dynamic matrix creation. It proceeds to collect runtime input for each matrix element, employing NumPy to transform the resulting array into a matrix. The program concludes this phase by displaying the original matrix, providing a practical demonstration of user-driven matrix generation.
Subsequently, the program shifts its focus to matrix manipulation, specifically targeting the extraction and display of crucial matrix components. It showcases the extraction of both lower and upper triangles and highlights the presentation of diagonal elements within the matrix. This comprehensive exploration equips readers with essential skills for matrix manipulation in real-world scenarios, where precise data extraction and analysis are paramount.
Program
Code:
# Importing necessary libraries
import numpy as np # NumPy library for array manipulation
import array as ar # Array module for creating arrays
# Taking input for the number of rows (m) and columns (n)
m, n = [int(a) for a in input("Enter Values of Row and Column").split()]
# Calculating the total number of elements in the matrix
x = m * n
# Creating an empty array to store matrix elements
myar1 = ar.array('i', [])
# Taking input for the matrix elements
print("Enter %d elements in matrix" % x)
for i in range(x):
b = int(input())
myar1.append(b)
# Reshaping the 1D array into a 2D matrix of shape (m, n)
myar2 = np.reshape(myar1, (m, n))
# Printing the original matrix
print("Original Matrix:")
print(myar2)
# Printing the Lower Triangle of the Matrix
print("Lower Triangle of Matrix: ")
for r in range(m):
for c in range(n):
if r >= c:
print(myar2[r][c], end=" ")
print()
# Printing the Upper Triangle of the Matrix
print("Upper Triangle of Matrix: ")
for r in range(m):
for c in range(n):
if r <= c:
print(myar2[r][c], end=" ")
print()
# Printing the Diagonal of the Matrix
print("Diagonal of Matrix: ")
for r in range(m):
for c in range(n):
if r == c:
print(myar2[r][c], end=" ")
print()Output:
Enter Values of Row and Column2 2
Enter 4 elements in matrix
1
2
3
4
[[1 2]
[3 4]]
Lower Triangle of Matrix:
1
3 4
Upper Triangle of Matrix:
1 2
4
Diagonal of Matrix:
1
4
Code Explanation:
- Import numpy and array modules
- Take matrix dimension input (rows & cols) from user and convert to ints
- Calculate total elements as rows*cols and store in x
- Create an empty integer array using array module
- Take x elements as input from user
- Append each element to the array
- Convert array to numpy matrix and reshape into input dimensions
Print the full input matrix
Print lower triangle by accessing array elements where row >= col
Print upper triangle by accessing elements where row <= col
Print diagonal by accessing elements where row == col
Summary
In summary, this Python program serves as a practical example of extracting the lower and upper triangles, as well as the diagonal elements, from a matrix. Understanding these components is crucial for various matrix-related computations in scientific and computational applications. Proficiency in working with these matrix elements empowers individuals to tackle complex tasks with precision and efficiency, making it a vital skill in the toolkit of Python programmers across diverse domains.
Your 15 seconds will encourage us to work even harder
Please share your happy experience on Google

