Matrix Multiplication in Python
This program multiplies two matrices. Matrix multiplication involves multiplying the rows of the first matrix by the columns of the second matrix.
Python Code
# Function to multiply two matrices
def multiply_matrices(matrix1, matrix2):
"""
Multiplies two matrices and returns the result.
:param matrix1: List of lists where each sublist is a row in the first matrix
:param matrix2: List of lists where each sublist is a row in the second matrix
:return: Resultant matrix as a list of lists
"""
# Number of rows in the first matrix
rows_matrix1 = len(matrix1)
# Number of columns in the first matrix (and rows in the second matrix)
cols_matrix1 = len(matrix1[0])
# Number of columns in the second matrix
cols_matrix2 = len(matrix2[0])
# Initializing the result matrix with zeros
result = [[0 for _ in range(cols_matrix2)] for _ in range(rows_matrix1)]
# Iterating through rows of matrix1
for i in range(rows_matrix1):
# Iterating through columns of matrix2
for j in range(cols_matrix2):
# Iterating through rows of matrix2
for k in range(cols_matrix1):
result[i][j] += matrix1[i][k] * matrix2[k][j]
return result
# Example usage
matrix1 = [
[1, 2, 3],
[4, 5, 6]
]
matrix2 = [
[7, 8],
[9, 10],
[11, 12]
]
# Print the matrices
print("Matrix 1:")
for row in matrix1:
print(row)
print("\nMatrix 2:")
for row in matrix2:
print(row)
# Multiply the matrices
result = multiply_matrices(matrix1, matrix2)
# Print the result
print("\nResultant Matrix:")
for row in result:
print(row)
Explanation
The program includes a function multiply_matrices
that takes two matrices as input and returns their product.
- Defining the function: The function is defined to accept two parameters:
matrix1
andmatrix2
. - Determining the dimensions: The number of rows and columns in each matrix is determined using the
len()
function. - Initializing the result matrix: The result matrix is initialized with zeros. It has dimensions equal to the number of rows of the first matrix and the number of columns of the second matrix.
- Matrix multiplication logic: Nested loops are used to iterate through the rows of the first matrix and the columns of the second matrix. The innermost loop performs the multiplication and addition to compute each element of the resultant matrix.
- Example usage: Two matrices are defined and printed. The function is called with these matrices, and the resultant matrix is printed.