In this tutorial, we will learn how to multiply two matrices in Python. We will cover the basic concept of matrix multiplication and implement a function to perform the operation.
Matrix multiplication is the process of multiplying two matrices by taking the dot product of rows and columns. The number of columns in the first matrix must be equal to the number of rows in the second matrix.
The syntax to multiply two matrices in Python is:
def multiply_matrices(matrix1, matrix2):
result = [[0 for _ in range(len(matrix2[0]))] for _ in range(len(matrix1))]
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]
return result
We can create a function to multiply two matrices by taking the dot product of rows and columns.
For example,
multiply_matrices
that takes two parameters matrix1
and matrix2
.matrix1
and the same number of columns as matrix2
.for
loop to iterate through the rows of matrix1
and the columns of matrix2
.def multiply_matrices(matrix1, matrix2):
result = [[0 for _ in range(len(matrix2[0]))] for _ in range(len(matrix1))]
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]
return result
# Sample matrices
matrix1 = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
matrix2 = [[9, 8, 7],
[6, 5, 4],
[3, 2, 1]]
# Multiply the matrices
result = multiply_matrices(matrix1, matrix2)
# Print the result
print('Product of the matrices is:')
for row in result:
print(row)
Product of the matrices is: [30, 24, 18] [84, 69, 54] [138, 114, 90]