Python Program for Matrix Multiplication

Matrix Multiplication

Python program to multiply two matrices has been shown here. Matrix $[A]_{m \times n}$ can be multiplied with matrix $[B]_{p \times q}$, iff $n = p$ i.e. the number of columns of the first matrix should to be equal to the number of rows in the second matrix. The order of the resultant matrix $C$ would be $m \times q$.

Algorithm, pseudocode and time complexity of the program have also been shown below.






1. Algorithm for matrix multiplication


1. Take two matrice $A_{m\times n}$ and $B_{p\times q}$ as input.

2. Declare another matrix $C_{m\times q}$ and initailize it with 0.

3. Check if $n = p$

4. If step [3] is false then display "Matrices can not be multiplied!" and go to step [8]

5. If step [3] is true, then

6. Repeat for each $i \in [0, m - 1]$

6.1. Repeat for each $j \in [0, q - 1]$

6.1.1. Repeat for each $k \in [0, p - 1]$

6.1.1.1. Perform $C[i][j] = C[i][j] + A[i][k] * B[k][j]$

7. Display $C_{m\times q}$ as the resultant matrix.

8. Exit program.




2. Pseudocode for matrix multiplication


Input: Two matrices $A_{m\times n}$ and $B_{p\times q}$

Output: $A * B$

1. Procedure matrixMultiplication($A_{m\times n}$, $B_{p\times q}$):

2. Initialize $C_{m\times q} = 0$

3. If $n == p$:

4. Repeat for each $i \in [0, m-1]$

5. Repeat for each $i \in [0, q-1]$

6. Repeat for each $k \in [0, p-1]$

7. $C_{ij}\leftarrow C_{ij} + A_{ik} * B_{kj}$

8. Return $C_{m\times q}$

9. Else:

10. Return Matrices can not be multiplied!

11. End Procedure





3. Time Complexity for matrix multiplication


Time Complexity: O($n^3$)

Where $n$ is the row and column size of two matrices.




4. Python Program for matrix multiplication

Code has been copied
# ******************************************
#           alphabetacoder.com
# Python Program for Matrix Multiplication
# ******************************************

# declare a function which takes
# two matrices as inputs and returns
# the resultant matrix after multiplication
def matrixMultiplication(A, B):
    # get the size of resultant matrix
    x = len(A)
    y = len(B[0])
    # declare and initialize resultant matrix
    C = [[0 for j in range(y)] for i in range(x)]
    # do matrix multiplication
    for i in range(0, x):
        for j in range(0, y):
            for k in range(0, len(B)):  # Use len(B) to get the number of rows in B
                C[i][j] += A[i][k] * B[k][j]
    return C


def main():
    # take input of the order of first matrix
    m = int(input("Enter the number of rows of the first matrix: "))
    n = int(input("Enter the number of columns of the first matrix: "))

    # take input of the order of second matrix
    p = int(input("Enter the number of rows of the second matrix: "))
    q = int(input("Enter the number of columns of the second matrix: "))

    # check if number of columns in the first matrix
    # is the same as the number of rows in the second matrix.
    # If not, then matrices cannot be multiplied
    if n != p:
        print("Matrices cannot be multiplied!")
    else:
        # declare and initialize the matrices
        A = [[0 for j in range(n)] for i in range(m)]
        B = [[0 for j in range(q)] for i in range(p)]

        # take input of the first matrix
        print("Enter the first matrix of order", m, "x", n, ":")
        for i in range(m):
            for j in range(n):
                A[i][j] = int(
                    input(f"Enter element at row {i + 1} and column {j + 1}: ")
                )

        # take input of the second matrix
        print("Enter the second matrix of order", p, "x", q, ":")
        for i in range(p):
            for j in range(q):
                B[i][j] = int(
                    input(f"Enter element at row {i + 1} and column {j + 1}: ")
                )

        # call the function to get the resultant matrix
        # after matrix A is multiplied by matrix B
        C = matrixMultiplication(A, B)

        # display matrix C
        print("The resultant matrix after multiplication: ")
        # display the result
        for i in range(m):
            for j in range(q):
                print(C[i][j], end=" ")
            # new line
            print("")


# drive code
main()

Output


Enter the number of rows of the first matrix: 3

Enter the number of columns of the first matrix: 3

Enter the number of rows of the second matrix: 3

Enter the number of columns of the second matrix: 3

Enter the first matrix of order 3 x 3 :

Enter element at row 1 and column 1: 5

Enter element at row 1 and column 2: 6

Enter element at row 1 and column 3: 1

Enter element at row 2 and column 1: 0

Enter element at row 2 and column 2: 2

Enter element at row 2 and column 3: 0

Enter element at row 3 and column 1: 3

Enter element at row 3 and column 2: 4

Enter element at row 3 and column 3: 6

Enter the second matrix of order 3 x 3 :

Enter element at row 1 and column 1: 0

Enter element at row 1 and column 2: 1

Enter element at row 1 and column 3: 2

Enter element at row 2 and column 1: 5

Enter element at row 2 and column 2: 3

Enter element at row 2 and column 3: 4

Enter element at row 3 and column 1: 5

Enter element at row 3 and column 2: 0

Enter element at row 3 and column 3: 6

The resultant matrix after multiplication:

35 23 40

10 6 8

50 15 58