Matrix Multiplication in Python
Matrix Multiplication in Python
Matrix multiplication is a fundamental operation in linear algebra where two matrices are multiplied to produce a third matrix. Unlike element-wise multiplication, the row elements of the first matrix are multiplied by the column elements of the second matrix and summed up.
To multiply matrix A by matrix B, the number of columns in matrix A must equal the number of rows in matrix B. If matrix A has dimensions rows by columns (represented as R1 x C1) and matrix B has dimensions R2 x C2, the multiplication is only possible if C1 equals R2. The resulting matrix will have the dimensions R1 x C2.
This program accomplishes matrix multiplication using nested loops without relying on external libraries like NumPy. This approach is excellent for understanding the underlying mathematics and logic of the operation.
The Python Program
# This program performs matrix multiplication of two 2D lists without using any external libraries.
# Define the first matrix (Matrix A) with dimensions 3x3
matrix_a = [
[12, 7, 3],
[4, 5, 6],
[7, 8, 9]
]
# Define the second matrix (Matrix B) with dimensions 3x4
matrix_b = [
[5, 8, 1, 2],
[6, 7, 3, 0],
[4, 5, 9, 1]
]
# Initialize the result matrix with zeros, matching the rows of A (3) and columns of B (4)
result = [
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]
]
# Iterate through the rows of Matrix A
for i in range(len(matrix_a)):
# Iterate through the columns of Matrix B
for j in range(len(matrix_b[0])):
# Iterate through the rows of Matrix B to calculate the dot product
for k in range(len(matrix_b)):
# Multiply corresponding elements and accumulate the sum into the result matrix
result[i][j] += matrix_a[i][k] * matrix_b[k][j]
# Display the final resulting matrix row by row
print("Resultant Matrix:")
for row in result:
print(row)
Sample Inputs and Output
[12, 7, 3] [4, 5, 6] [7, 8, 9]
[5, 8, 1, 2] [6, 7, 3, 0] [4, 5, 9, 1]
[114, 160, 60, 27] [74, 97, 73, 14] [119, 157, 112, 23]
Comments
Post a Comment