Python program to multiply two matrices

Matrix Multiplication is a binary operation used to get a resultant matrix by multiplying two matrices. The elements in the row of the first matrix are multiplied by the elements of the column in the second matrix.

To perform the multiplication of any two given matrices, a condition should be satisfied, that is the number of elements in the row of the first matrix should be equal to the elements of the column of the second matrix.

We can write the Python Program for multiplication of two matrices using various methods, in which we consider this method of  “Using Recursive Matrix Multiplication method.”

Using Recursive Matrix Multiplication :

  • Recursive matrix multiplication works on the Divide and Conquer algorithm, It is a function that repeats itself resulting in the formation of a sequence of terms. This results in getting a third matrix by multiplying two matrices.
  • def matrix_multiply_recursive(P, Q):
        if len(P[0]) != len(Q):
            raise ValueError("Invalid matrix dimensions")
        result = [[0 for j in range(len(Q[0]))] for i in range(len(P))]
        def multiply(P, Q, result, i, j, k):
            if i >= len(P):
                return
            if j >= len(Q[0]):
                return multiply(P, Q, result, i+1, 0, 0)
            if k >= len(Q):
                return multiply(P, Q, result, i, j+1, 0)
            result[i][j] += P[i][k] * Q[k][j]
            multiply(P, Q, result, i, j, k+1)
        multiply(P, Q, result, 0, 0, 0)
        return result
    P = [[1, 3, 5], [2, 4, 6], [1, 2, 3]]
    Q = [[1, 2, 3, 4], [4, 5, 6, 3], [2, 4, 6, 1]]
    result = matrix_multiply_recursive(P, Q)
    for row in result:
        print(row)
    OUTPUT:
    
    [23, 37, 51, 18]
    [30, 48, 66, 26]
    [15, 24, 33, 13]

    Time Complexity :  O(n^3)

    Auxiliary Space : O(n^2)

You can check: Python Program to Add Two Matrices

Leave a Reply

Your email address will not be published. Required fields are marked *