Python Matrix Multiplication (Python Program to Multiply Two Matrices)
Matrices are fundamental mathematical objects used to represent and manipulate data in various fields, including mathematics, physics, computer science, and data analysis. Multiplying matrices is a crucial operation that allows us to combine and transform data in meaningful ways.
In this tutorial, we will learn about the program for matrix multiplication in Python. We will provide a comprehensive guide, including different approaches like using NumPy, to help you understand the concept and implement the multiplication of two matrices in Python programs effectively.
Understanding how to multiply matrices in Python is essential for performing complex mathematical operations, solving systems of linear equations, transforming data representations, and working with multidimensional data structures.
Using NumPy for matrix multiplication offers several advantages, including improved performance and simplified syntax. NumPy is a powerful library in Python and provides a wide range of functionalities for working with arrays and matrices.
For beginners interested in learning this programming language, it is recommended to start with the Python Tutorial. To practice these programs online, you can use the online Python compiler. It allows you to write, run, and test code directly in your web browser, providing a convenient way to experiment with code and see the results immediately.
2x2 Matrix Multiplication in Python
Here's a Python program to multiply two 2x2 matrices:
Code
# Define the matrices
matrix1 = [[1, 2],
[3, 4]]
matrix2 = [[5, 6],
[7, 8]]
# Create an empty result matrix
result = [[0, 0],
[0, 0]]
# Perform matrix multiplication
for i in range(len(matrix1)):
for j in range(len(matrix2[0])):
for k in range(len(matrix2)):
result[i][j] += matrix1[i][k] * matrix2[k][j]
# Print the result matrix
print("Result Matrix:")
for row in result:
print(row)
Output
Result Matrix:
[19, 22]
[43, 50]
Explanation
-
The program defines two 2x2 matrices, matrix1 and matrix2, using nested lists.
-
An empty matrix called result is created to store the result of the multiplication.
-
The program uses nested loops to perform matrix multiplication. The outer loops iterate over the rows of matrix1, the innermost loop iterates over the columns of matrix2, and the middle loop iterates over the elements of matrix2 to calculate the dot product.
-
The dot product of each row and column is accumulated in the corresponding position of the result matrix using the += operator.
-
Finally, the program prints the resulting matrix by iterating over its rows and displaying them.
-
When you run this program, it will multiply the two matrices matrix1 and matrix2 and store the result in the result matrix. The resulting matrix will then be displayed.
3x3 Matrix Multiplication in Python
Here's a Python program to multiply two 3x3 matrices:
Code
# Define the matrices
matrix1 = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
matrix2 = [[10, 11, 12],
[13, 14, 15],
[16, 17, 18]]
# Create an empty result matrix
result = [[0, 0, 0],
[0, 0, 0],
[0, 0, 0]]
# Perform matrix multiplication
for i in range(len(matrix1)):
for j in range(len(matrix2[0])):
for k in range(len(matrix2)):
result[i][j] += matrix1[i][k] * matrix2[k][j]
# Print the result matrix
print("Result Matrix:")
for row in result:
print(row)
Output
Result Matrix:
[84, 90, 96]
[201, 216, 231]
[318, 342, 366]
Explanation
-
The program defines two 3x3 matrices, matrix1 and matrix2, using nested lists.
-
An empty matrix called result is created to store the result of the multiplication.
-
The program uses nested loops to perform matrix multiplication. The outer loops iterate over the rows of matrix1, the innermost loop iterates over the columns of matrix2, and the middle loop iterates over the elements of matrix2 to calculate the dot product.
-
The dot product of each row and column is accumulated in the corresponding position of the result matrix using the += operator.
-
Finally, the program prints the resulting matrix by iterating over its rows and displaying them.
-
When you run this program, it will multiply the two matrices matrix1 and matrix2 and store the result in the result matrix. The resulting matrix will then be displayed.
Matrix Multiplication in Python Using NumPy
NumPy provides a powerful and efficient way to work with arrays and matrices in Python. Its dot() function allows us to perform matrix multiplication conveniently, handling all the necessary calculations behind the scenes.
Here's a Python program to multiply matrices with NumPy:
Code
import numpy as np
# Define the matrices
matrix1 = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
matrix2 = np.array([[10, 11, 12],
[13, 14, 15],
[16, 17, 18]])
# Perform matrix multiplication
result = np.dot(matrix1, matrix2)
# Print the result matrix
print("Result Matrix:")
print(result)
Output
Result Matrix:
[[ 84 90 96]
[201 216 231]
[318 342 366]]
Explanation
-
The program imports the NumPy library using the import numpy as np statement.
-
The matrices matrix1 and matrix2 are defined as NumPy arrays using the np.array() function.
-
The np.dot() function is used to perform matrix multiplication between matrix1 and matrix2. This function calculates the dot product of the two matrices.
-
The resulting matrix is stored in the result variable.
-
Finally, the program prints the resulting matrix using the print() function.
When you run this program, it will multiply the two matrices matrix1 and matrix2 using the np.dot() function from NumPy. The resulting matrix will be displayed.
Matrix Multiplication in Python With User Input
Here's a Python program for matrix multiplication by getting input from user:
Code
# Get the dimensions of the matrices from the user
rows1 = int(input("Enter the number of rows for matrix 1: "))
cols1 = int(input("Enter the number of columns for matrix 1: "))
rows2 = int(input("Enter the number of rows for matrix 2: "))
cols2 = int(input("Enter the number of columns for matrix 2: "))
# Check if the matrices can be multiplied
if cols1 != rows2:
print("Error: The number of columns in matrix 1 must match the number of rows in matrix 2.")
exit()
# Create the matrices based on user input
matrix1 = []
matrix2 = []
print("Enter the elements of matrix 1:")
# Get input for matrix 1
for i in range(rows1):
row = []
for j in range(cols1):
element = int(input("Enter element at position ({}, {}): ".format(i, j)))
row.append(element)
matrix1.append(row)
print("Enter the elements of matrix 2:")
# Get input for matrix 2
for i in range(rows2):
row = []
for j in range(cols2):
element = int(input("Enter element at position ({}, {}): ".format(i, j)))
row.append(element)
matrix2.append(row)
# Perform matrix multiplication
result = [[0] * cols2 for _ in range(rows1)]
for i in range(rows1):
for j in range(cols2):
for k in range(cols1):
result[i][j] += matrix1[i][k] * matrix2[k][j]
# Print the result matrix
print("Result Matrix:")
for row in result:
print(row)
Output
Enter the number of rows for matrix 1: 2
Enter the number of columns for matrix 1: 2
Enter the number of rows for matrix 2: 2
Enter the number of columns for matrix 2: 2
Enter the elements of matrix 1:
Enter element at position (0, 0): 7
Enter element at position (0, 1): 6
Enter element at position (1, 0): 5
Enter element at position (1, 1): 4
Enter the elements of matrix 2:
Enter element at position (0, 0): 3
Enter element at position (0, 1): 4
Enter element at position (1, 0): 5
Enter element at position (1, 1): 7
Result Matrix:
[51, 70]
[35, 48]
Explanation
-
The program prompts the user to enter the dimensions (number of rows and columns) for both matrices.
-
It checks if the matrices can be multiplied by verifying that the number of columns in the first matrix matches the number of rows in the second matrix.
-
The program then creates two empty matrices, matrix1 and matrix2, and prompts the user to enter the elements for each matrix using nested loops and the input() function.
-
After obtaining the matrices from the user, the program performs matrix multiplication using nested loops, similar to the previous examples.
-
The resulting matrix is stored in the result variable and printed using nested loops.
When you run this program, it will prompt you to enter the dimensions and elements for the two matrices. It will then perform the matrix multiplication and display the resulting matrix.