Python Matrix Multiplication Without NumPy

Python Matrix Multiplication without Numpy | Here, we will discuss how to multiply two matrices in Python without NumPy. Matrix multiplication is a binary operation that multiplies two matrices, as in addition and subtraction both the matrices should be of the same size, but here in multiplication matrices need not be of the same size, but to multiply two matrices the row value of the first matrix should be equal to the column value of the second matrix. Multiplying is a bit more complex than other multiplicative operations.

Matrix Multiplication in Python Without NumPy

Here, we take user input to multiply two matrices without NumPy; we intake row values and column values from the user and then proceed with the elements.

# Python program to multiply two matrices without numpy

# take first matrix inputs
print("Enter the order of matrix 1:")
m, n = list(map(int, input().split()))
print("Enter row values")
m1 = []
for i in range(m):
   print("Enter row",  i, "values:")
   row = list(map(int, input().split()))
   m1.append(row)

# take second matrix inputs
print("Enter the order of matrix2:")
p, q = list(map(int, input().split()))
print("Enter row values")
m2 = []
for j in range(p):
   print("Enter row", j, "value:")
   row = list(map(int, input().split()))
   m2.append(row)

# print both matrices
print("Matrix 1:", m1)
print("Matrix 2:", m2)

# multiply matrix
result = []
for i in range(m):
   row = []
   for j in range(q):
      row.append(0)
   result.append(row)
print("Matrix Multiplication:")
for i in range(m):
   for j in range(q):
      for k in range(n):
         result[i][j] += m1[i][k] * m2[k][j]
for row in result:
   print(row)

Output:-

Enter the order of matrix 1:
2 2
Enter row values
Enter row 0 values:
14 21
Enter row 1 values:
20 25
Enter the order of matrix2:
2 2
Enter row values
Enter row 0 value:
19 17
Enter row 1 value:
21 23
Matrix 1: [[14, 21], [20, 25]]
Matrix 2: [[19, 17], [21, 23]]
Matrix Multiplication:
[707, 721]
[905, 915]

In the above code, we are taking two inputs together that is m, n = list(map(int, input().split())) here, we have taken two inputs together as row and column for the first matrix similarly, the same thing is done for second matrix p, q are rows and columns respectively. Then in nested for loops we multiply the matrix and store it in the result.

Python Program to Multiply Two Matrices Without NumPy

In python, we can define our own functions. The main aim for this is to reuse the code hence it reduces the number of lines. To define a function we use the def keyword.

# Python program to multiply two matrices without using numpy

MAX = 100
def matrixPrint(M, row, col):
   for i in range(row):
      for j in range(col):
         print(M[i][j], end=" ")
      print()

def matrixMultiply(row1, col1, m1, row2, col2, m2):
   res = [[0 for i in range(MAX)] for j in range(MAX)]
   if(row2 != col1):
      print("Matrix multiplication not possible")
      return
   for i in range(row1):
      for j in range(col2):
         res[i][j] = 0
         for k in range(row2):
            res[i][j] += m1[i][k] * m2[k][j]
   print("Result:")
   matrixPrint(res, row1, col2)

# main
if __name__ == "__main__":
   m1 = [[0 for i in range(MAX)] for j in range(MAX)]
   m2 = [[0 for i in range(MAX)] for j in range(MAX)]
   row1 = int(input("Enter the number of rows in matrix 1: "))
   col1 = int(input("Enter the number of columns in matrix 1: "))
   print("Enter the elements of matrix 1:")
   for i in range(row1):
      for j in range(col1):
         m1[i][j] = int(input("m1[" + str(i) + "][" + str(j) + "]: "))

   row2 = int(input("Enter the number of rows in matrix 2: "))
   col2 = int(input("Enter the number of columns in matrix 2: "))

   print("Enter the elements of matrix 2: ")
   for i in range(row2):
      for j in range(col2):
         m2[i][j] = int(input("m2[" + str(i) + "][" + str(j) + "]: "))
   print("Matrix 1: ")
   matrixPrint(m1, row1, col1)
   print("Matrix 2: ")
   matrixPrint(m2, row2, col2)
   matrixMultiply(row1, col1, m1, row2, col2, m2)

Output:-

Enter the number of rows in matrix 1: 3
Enter the number of columns in matrix 1: 2
Enter the elements of matrix 1:
m1[0][0]: 12
m1[0][1]: 20
m1[1][0]: 15
m1[1][1]: 25
m1[2][0]: 14
m1[2][1]: 12
Enter the number of rows in matrix 2: 2
Enter the number of columns in matrix 2: 3
Enter the elements of matrix 2:
m2[0][0]: 23
m2[0][1]: 21
m2[0][2]: 10
m2[1][0]: 18
m2[1][1]: 16
m2[1][2]: 22
Matrix 1:
12 20
15 25
14 12
Matrix 2:
23 21 10
18 16 22
Result:
636 572 560
795 715 700
538 486 404

In the above example, we have used two functions matrixPrint() and matrixMultiply(). The first function matrixPrint() takes 3 parameters:- matrix to be printed, rows and columns, this function is used to print the matrix. Then in the second function matrixMultiply(), we have taken 6 parameters; those are rows and columns of matrix1 and matrix2 and matrix1 and matrix2 as well. 

Python Matrix Multiplication Without NumPy

To multiply a matrix we use a nested for loop. Nested for loop is a for loop inside another for loop.

# Python program to multiply two matrices without numpy

m1 = [[10, 11, 12],
      [13, 14, 15],
      [16, 17, 18]]
m2 = [[9, 8, 7],
      [6, 5, 4],
      [3, 2, 1]]
res = [[0, 0, 0],
       [0, 0, 0],
       [0, 0, 0]]

# multiply matrix
for i in range(len(m1)):
   for j in range(len(m2[0])):
      for k in range(len(m2)):
         res[i][j] += m1[i][k] * m2[k][j]
for r in res:
   print(r)

Output:-

[192, 159, 126]
[246, 204, 162]
[300, 249, 198]

For the above code, we have given our own set of values, then we have initialized the resultant matrix res to 0 and iterated in a set of for loops.

Matrix Multiplication Program in Python Without NumPy

We also multiply matrices using a list, a list is an ordered group of elements, which stores many items.

# Python program to multiply two matrices without numpy

A = [[1, 2, 3],
     [4, 5, 6],
     [7, 8, 9]]

B = [[25, 24, 23, 22],
     [21, 20, 19, 18],
     [17, 16, 15, 14]]

# multiply matrix
res = [[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 res:
   print(r)

Output:-

[118, 112, 106, 100]
[307, 292, 277, 262]
[496, 472, 448, 424]

In the code, we have used the zip function. This function helps to combine similar types of iterators, data items at that position, it also uses the shortest length of these input iterators.

Dynamic Matrix Multiplication in Python

Matrix chain multiplication (or the matrix chain ordering problem) is an optimization problem concerning the most efficient way to multiply a given sequence of matrices. The problem is not actually to perform the multiplications, but merely to decide the sequence of the matrix multiplications involved. The problem may be solved using dynamic programming.

# Python program to multiply matrices using dynamic programming

import sys
def matrixMultiply(d):
   n = len(d)
   # create the table to store solutions
   c = [[0 for x in range(n)] for x in range(n)]
 
   # length of the chain
   for length in range(2,n):
      for i in range(1,n-length+1):
         j = i+length-1
         # store a maximum integer
         c[i][j] = sys.maxsize
         
         for k in range(i,j):
            # p holds the value of multiplication cost
            p = c[i][k] + c[k+1][j] + d[i-1] * d[k] * d[j]
            #compare previous cost with p
            if p < c[i][j]:
               c[i][j] = p
   # last element of first row contains
   return c[1][n-1]

# take inputs
d = [10, 11, 12, 13, 14, 15]

# calling function and print result
print('The minimum cost is', matrixMultiply(d))

Output:-

The minimum cost is 6800

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

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