Python Program to Multiply Two Matrices
Given two matrices, we will have to create a program to multiply two matrices in Python.
Example: Python Matrix Multiplication of Two-Dimension
matrix_a = [[1, 2], [3, 4]]
matrix_b = [[5, 6], [7, 8]]
result = [[0, 0], [0, 0]]
for i in range(2):
for j in range(2):
result[i][j] = (matrix_a[i][0] * matrix_b[0][j] +
matrix_a[i][1] * matrix_b[1][j])
for row in result:
print(row)
Output
[19, 22] [43, 50]
Table of Content
Multiply Two Matrices Using Nested Loops
This Python program multiplies two matrices using nested loops. It initializes two matrices A and B, along with a result matrix filled with zeros. The program then iterates through each element of matrix A and matrix B to compute the product, storing the result in the result matrix. Finally, it prints the result matrix.
# take a 3x3 matrix
A = [[12, 7, 3],
[4, 5, 6],
[7, 8, 9]]
# take a 3x4 matrix
B = [[5, 8, 1, 2],
[6, 7, 3, 0],
[4, 5, 9, 1]]
result = [[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]]
# iterating by row of A
for i in range(len(A)):
# iterating by column by B
for j in range(len(B[0])):
# iterating by rows of B
for k in range(len(B)):
result[i][j] += A[i][k] * B[k][j]
for r in result:
print(r)
Output
[114, 160, 60, 27] [74, 97, 73, 14] [119, 157, 112, 23]
Time Complexity: O(M*M*N), as we are using nested loop traversing, M*M*N.
Auxiliary Space: O(M*N), as we are using a result matrix which is extra space.
Matrix Multiplication in Python Using List Comprehension
This Python program multiplies two matrices A
and B
using list comprehension. It calculates the dot product of rows from matrix A
and columns from matrix B
using zip()
to pair elements. The sum()
function computes the element-wise product and adds the results. The final 3×4 result is printed row by row.
# take a 3x3 matrix
A = [[12, 7, 3],
[4, 5, 6],
[7, 8, 9]]
# take a 3x4 matrix
B = [[5, 8, 1, 2],
[6, 7, 3, 0],
[4, 5, 9, 1]]
# result will be 3x4
result = [[sum(a * b for a, b in zip(A_row, B_col))
for B_col in zip(*B)]
for A_row in A]
for r in result:
print(r)
Output
[114, 160, 60, 27] [74, 97, 73, 14] [119, 157, 112, 23]
Time Complexity: O(M*M*N), as we are using nested loop traversing, M*M*N.
Auxiliary Space: O(M*N), as we are using a result matrix which is extra space.
Efficient Matrix Multiplication in Python using NumPy (Vectorized Implementation)
This code multiplies two matrices using NumPy’s np.dot()
function for matrix multiplication. The first matrix A
is a 3×3 matrix, and the second matrix B
is a 3×4 matrix. The result is a 3×4 matrix, and the code prints each row of the resulting matrix after multiplication.
import numpy as np
# take a 3x3 matrix
A = [[12, 7, 3],
[4, 5, 6],
[7, 8, 9]]
# take a 3x4 matrix
B = [[5, 8, 1, 2],
[6, 7, 3, 0],
[4, 5, 9, 1]]
# result will be 3x4
result= [[0,0,0,0],
[0,0,0,0],
[0,0,0,0]]
result = np.dot(A,B)
for r in result:
print(r)
Output
[114 160 60 27] [74 97 73 14] [119 157 112 23]
Time Complexity: O(M*M*N), as we are using nested loop traversing, M*M*N.
Auxiliary Space: O(M*N), as we are using a result matrix which is extra space.
Recursive Matrix Multiplication in Python
To multiply two matrices, first check if their dimensions are valid by ensuring the number of columns in the first matrix equals the number of rows in the second matrix. If not, raise an error or return None
. If both matrices are 1×1 in size, simply multiply their elements and return the result. Otherwise, divide each matrix into four equal-sized submatrices. Recursively multiply these submatrices until each is 1×1 in size. Then, compute the result using the formula:result = [A11B11 + A12B21, A11B12 + A12B22, A21B11 + A22B21, A21B12 + A22B22]
. Finally, return the resulting matrix.
def matrix_multiply_recursive(A, B):
# check if matrices can be multiplied
if len(A[0]) != len(B):
raise ValueError("Invalid matrix dimensions")
# initialize result matrix with zeros
result = [[0 for j in range(len(B[0]))] for i in range(len(A))]
# recursive multiplication of matrices
def multiply(A, B, result, i, j, k):
if i >= len(A):
return
if j >= len(B[0]):
return multiply(A, B, result, i+1, 0, 0)
if k >= len(B):
return multiply(A, B, result, i, j+1, 0)
result[i][j] += A[i][k] * B[k][j]
multiply(A, B, result, i, j, k+1)
# perform matrix multiplication
multiply(A, B, result, 0, 0, 0)
return result
# example usage
A = [[12, 7, 3], [4, 5, 6], [7, 8, 9]]
B = [[5, 8, 1, 2], [6, 7, 3, 0], [4, 5, 9, 1]]
result = matrix_multiply_recursive(A, B)
for row in result:
print(row)
Output
[114, 160, 60, 27] [74, 97, 73, 14] [119, 157, 112, 23]
Time complexity: O(n^3)
Auxiliary Space : O(n^2)