Python Matrix Addition: Program to Add Two Matrices in Python
Matrices are a fundamental concept in linear algebra and play a crucial role in various fields, including mathematics, computer science, and data analysis. Adding two matrices is a common operation that allows us to combine their corresponding elements and obtain a new matrix.
In this tutorial, we will explore a Python program to add two matrices. You will get a step-by-step guide, complete with examples and code explanations, to help you understand the concept and implement it in your Python programs effectively.
The addition of two matrices in Python involves adding their corresponding elements together to create a new matrix with the same dimensions. This operation is valuable in many areas, such as image processing, scientific computing, and solving systems of linear equations.
Understanding matrix addition in Python provides a powerful tool for performing calculations and manipulating data structures. It enhances your ability to work with multidimensional data and opens doors to more advanced topics in linear algebra and numerical computing.
For beginners interested in learning this programming language, it is recommended to start with the Python Tutorial. To practice online, you can use the Python online compiler. It helps you to write, run, and test Python code directly in your web browser, providing a convenient way to experiment with Python code and see the results immediately.
Python Program to Add Two Matrices
To add two matrices in Python, you can use nested loops to iterate over the elements of the matrices and perform the addition operation. Here's an example program without numpy:
Code
# Function to add two matrices
def add_matrices(matrix1, matrix2):
rows = len(matrix1)
columns = len(matrix1[0])
# Create a result matrix filled with zeros
result = [[0 for _ in range(columns)] for _ in range(rows)]
# Iterate over the elements and perform addition
for i in range(rows):
for j in range(columns):
result[i][j] = matrix1[i][j] + matrix2[i][j]
return result
# Example matrices
matrix1 = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
matrix2 = [[9, 8, 7],
[6, 5, 4],
[3, 2, 1]]
# Call the function to add the matrices
result_matrix = add_matrices(matrix1, matrix2)
# Print the result matrix
for row in result_matrix:
print(row)
Output
[10, 10, 10]
[10, 10, 10]
[10, 10, 10]
Explanation
In this program, we define the function add_matrices() to perform the addition of two matrices. It takes two matrices as input (matrix1 and matrix2) and returns the result matrix.
Inside the function, we determine the dimensions of the matrices (rows and columns). We create a new matrix called result filled with zeros, having the same dimensions as the input matrices.
Then, we use nested loops to iterate over each element of the matrices. We add the corresponding elements from matrix1 and matrix2 and store the result in the corresponding position of the result matrix.
Finally, we call the add_matrices() function with the example matrices, and print the resulting matrix element by element.
Matrix Addition in Python Using Numpy
To add two matrices in Python using the NumPy library, you can use the numpy.add() function. NumPy provides a convenient way to perform element-wise addition of two matrices.
Code
import numpy as np
# Example matrices
matrix1 = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
matrix2 = np.array([[9, 8, 7],
[6, 5, 4],
[3, 2, 1]])
# Add the matrices using numpy.add()
result_matrix = np.add(matrix1, matrix2)
# Print the result matrix
print(result_matrix)
Output
[[10 10 10]
[10 10 10]
[10 10 10]]
Explanation
In this program, we import the NumPy library with the line import numpy as np. Then, we define the example matrices matrix1 and matrix2 as NumPy arrays.
Using the numpy.add() function, we add the matrices matrix1 and matrix2 together, and store the result in the result_matrix variable.
Finally, we print the result_matrix, which displays the element-wise sum of the two matrices.
Matrix Addition in Python With User Input
Here's an example program that adds two matrices with user input using the NumPy library:
Code
import numpy as np
# Function to add two matrices
def add_matrices(matrix1, matrix2):
result_matrix = np.add(matrix1, matrix2)
return result_matrix
# Input matrix dimensions
rows = int(input("Enter the number of rows: "))
columns = int(input("Enter the number of columns: "))
# Input elements for matrix1
print("Enter elements for matrix1:")
matrix1 = []
for i in range(rows):
row = []
for j in range(columns):
element = int(input(f"Enter element at position ({i+1}, {j+1}): "))
row.append(element)
matrix1.append(row)
# Input elements for matrix2
print("Enter elements for matrix2:")
matrix2 = []
for i in range(rows):
row = []
for j in range(columns):
element = int(input(f"Enter element at position ({i+1}, {j+1}): "))
row.append(element)
matrix2.append(row)
# Call the function to add the matrices
result_matrix = add_matrices(np.array(matrix1), np.array(matrix2))
# Print the result matrix
print("Result Matrix:")
print(result_matrix)
Output
Enter the number of rows: 2
Enter the number of columns: 3
Enter elements for matrix1:
Enter element at position (1, 1): 1
Enter element at position (1, 2): 2
Enter element at position (1, 3): 3
Enter element at position (2, 1): 4
Enter element at position (2, 2): 5
Enter element at position (2, 3): 6
Enter elements for matrix2:
Enter element at position (1, 1): 9
Enter element at position (1, 2): 8
Enter element at position (1, 3): 7
Enter element at position (2, 1): 6
Enter element at position (2, 2): 5
Enter element at position (2, 3): 4
Result Matrix:
[[10 10 10]
[10 10 10]]
Explanation
In this program, the user is prompted to enter the dimensions (number of rows and columns) for the matrices.
Then, the program asks the user to input the elements for matrix1 and matrix2 using nested loops. The user enters the elements for each position in the matrices.
The function add_matrices() is defined to add the two matrices using numpy.add(). It takes the matrices as arguments, converts them to NumPy arrays, performs the addition, and returns the resulting matrix.
Finally, the program calls the add_matrices() function with the user-input matrices, and prints the resulting matrix.