Open In App

Python program to multiply two matrices

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

Given two matrix the task is that we will have to create a program to multiply two matrices in python. 

Examples: 

Input : X = [[1, 7, 3],
             [3, 5, 6],
             [6, 8, 9]]
       Y = [[1, 1, 1, 2],
           [6, 7, 3, 0],
           [4, 5, 9, 1]]
 
Output : [55, 65, 49, 5]
         [57, 68, 72, 12]
         [90, 107, 111, 21]

Using Simple Nested Loops: In this program we have to use nested for loops to iterate through each row and each column.

Implementation:

fdfxfxddx

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.

Method 2: Matrix Multiplication Using Nested List. We use zip in Python.

Implementation:

Python3




# Program to multiply two matrices using list comprehension
 
# 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.

Method 3: Matrix Multiplication (Vectorized implementation). 

Implementation:

Python3




# Program to multiply two matrices (vectorized implementation)
 
# Program to multiply two matrices (vectorized implementation)
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.

Method 4:Using recursive matrix multiplication:

Algorithm:

  1. Check if the dimensions of the two input matrices are valid for multiplication. If the number of columns in the first matrix does not equal the number of rows in the second matrix, then they cannot be multiplied. In this case, raise an error or return a None object.
  2. Check if the matrices are of size 1×1. If they are, multiply their elements and return the result.
  3. If the matrices are not of size 1×1, divide each matrix into four submatrices of equal size.
  4. Recursively multiply the submatrices using the same algorithm, until each submatrix is of size 1×1.
  5. Compute the product of the resulting submatrices using the formula:
  6. result = [A11B11 + A12B21, A11B12 + A12B22, A21B11 + A22B21, A21B12 + A22B22]
  7. Return the resulting matrix.

Python3




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)



Last Updated : 28 Jul, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads