Python Program on Read Data in Matrix
Master Python with 70+ Hands-on Projects and Get Job-ready - Learn Python
In this article, we will explore two Python programs that involve the creation of matrices using the NumPy library. Matrices play a crucial role in various scientific and computational applications, and NumPy provides efficient tools for working with them. The first program demonstrates how to create a matrix by taking runtime input for each element, while the second program creates a matrix by taking a string of elements as input.
Prerequisites
- Fundamental Python Knowledge (Variables, Data Types, Syntax)
- Basic Familiarity with the NumPy Library (Numerical Computing, Basic Array Operations)
Topic Explanation
Program 1: Create Matrix with Runtime Element Input
The first program prompts the user to enter the number of rows and columns for the matrix. It then takes runtime input for each element of the matrix and uses NumPy to reshape the array into a matrix. The program also showcases the creation of a matrix object using np.matrix() and calculates its transpose.
Code:
# Program for Creating a Matrix using Runtime input and finding its transpose
import numpy as np
import array as ar
# Get the number of rows and columns for the matrix from the user
m, n = [int(a) for a in input("Input the row and column numbers: ").split()]
# Initialize an array to store matrix elements
myar1 = ar.array('i', [])
# Determine how many elements there are in the matrix overall.
x = m * n
# Get user input for each element in the matrix
print(f"Enter {x} elements in the matrix:")
for i in range(x):
a = int(input())
myar1.append(a)
# Reshape the 1D array to create a 2D array representing the matrix
myar2 = np.reshape(myar1, (m, n))
# Create a matrix using the NumPy library
mt = np.matrix(myar2)
# Display the original matrix
print("Original Matrix:")
print(mt)
# Display the transpose of the matrix
print("Transpose is:")
print(mt.transpose())Output:
Input the row and column numbers3 3
Enter 9 elements in matrix
1
1
1
1
1
1
1
1
1
[[1 1 1]
[1 1 1]
[1 1 1]]
Transpose is :
[[1 1 1]
[1 1 1]
[1 1 1]]
Code Explanation:
Import numpy and array modules
- Take row and column input from user and convert to ints
- Create an empty integer array using array module
- Calculate total elements as row*column
- Print statement to enter the matrix elements
- Take input from user in a loop and append to array
- Reshape the array to row x column
- Convert the array to numpy matrix
- Print the matrix
- Print the transpose of the matrix using transpose() method
Program 2: Create Matrix with Runtime Element Input by String
The second program prompts the user to enter the number of rows and columns for the matrix. It then takes a string containing space-separated elements as input and uses NumPy to reshape the string into a matrix. The program demonstrates an alternative approach for creating a matrix using a string of elements.
Code:
# Program for Creating a Matrix using Runtime input by String
import numpy as np
# Ask the user how many rows and columns the matrix will have.
m, n = [int(a) for a in input("Input the row and column numbers: ").split()]
# Determine how many elements there are in the matrix overall.
x = m * n
# Get a single string containing all elements separated by spaces
input_str = input(f"Enter {x} elements separated by spaces: ")
# Create a matrix by reshaping a 1D array obtained from the input string
mt = np.reshape(np.matrix(input_str), (m, n))
# Display the created matrix
print("Matrix:")
print(mt)Output:
Input the row and column numbers: 3 3
Enter 9 elements separated by spaces: 5 5 5 5 5 5 5 5 5
Matrix:
[[5 5 5]
[5 5 5]
[5 5 5]]
Code Explanation:
- Import the numpy library to support matrix operations
- Take row and column size input from user as two integer values separated by space
- Convert the input to ints and assign to variables m and n
- Calculate total elements as m*n and store in x
- Take a string input from user containing x no. of elements separated by space
- Convert the string into a numpy matrix using np.matrix()
- Reshape the 1D matrix into 2D matrix with dimensions m x n using np.reshape()
- Print the final matrix mt
Summary
In summary, these Python programs serve as practical examples of matrix creation using runtime input with the NumPy library. Understanding these techniques is essential for tasks involving dynamic matrix generation and manipulation in Python. Proficiency in this area equips individuals with the skills needed to adapt to real-world data and computational challenges across various domains, such as scientific simulations, data-driven applications, and machine learning algorithms.
We work very hard to provide you quality material
Could you take 15 seconds and share your happy experience on Google

