In this tutorial, you will learn to write a Python Program To Add Two Matrices Taking Input From User Using Numpy.
NumPy is a Python library used for scientific computing and data analysis.
It provides support for multidimensional arrays, matrices, and high-level mathematical functions to operate on these arrays.
NumPy is a powerful library for numerical computations in Python.
It is widely used in the fields of data science, machine learning, and artificial intelligence.
NumPy arrays are similar to Python lists, but they allow for fast, element-wise operations and efficient handling of large data sets.
To understand this program you should have an understanding of the following topics:
- Numpy
Python Program To Add Two Matrices Taking Input From User Using Numpy
import numpy as np
# Take the dimensions of the matrices as input from the user
rows = int(input("Enter the number of rows: "))
cols = int(input("Enter the number of columns: "))
# Take input for the first matrix
print("Enter elements of the first matrix:")
matrix1 = np.zeros((rows, cols), dtype=int)
for i in range(rows):
for j in range(cols):
matrix1[i][j] = int(input())
# Take input for the second matrix
print("Enter elements of the second matrix:")
matrix2 = np.zeros((rows, cols), dtype=int)
for i in range(rows):
for j in range(cols):
matrix2[i][j] = int(input())
# Add the two matrices
matrix_sum = matrix1 + matrix2
# Print the result
print("Matrix 1:n", matrix1)
print("Matrix 2:n", matrix2)
print("The sum of the Matrix 1 and Matrix 2 is:")
print(matrix_sum)
Output
Enter the number of rows: 2
Enter the number of columns: 2
Enter elements of the first matrix:
4
5
6
7
9
8
7
6
Matrix 1:
[[4 5]
[6 7]]
Matrix 2:
[[9 8]
[7 6]]
The sum of the Matrix 1 and Matrix 2 is:
[[13 13]
[13 13]]
In this program, we first import the NumPy library using the import statement.
We then take the dimensions of the matrices as input from the user using the input function and convert them to integers using the int function.
Then we used nested loops to take input for the elements of the two matrices.
We initialize two NumPy arrays of zeros using the np.zeros function and the input dimensions.
We then use two nested loops to assign the user input values to the elements of these arrays.
The int function is used to convert the input values to integers.
Next, we use the + operator to add the two matrices and store the result in a new NumPy array called matrix_sum.
Finally, we print out the sum of the two matrices using the print function and pass it into the matrix_sum array.
NumPy takes care of formatting the output in matrix form.