Matrix Multiplication Program in Python

Matrix Multiplication Program in Python | Here, we will discuss how to multiply two matrices in Python. 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.

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. Also See:- Matrix Addition Program in Python

We will see these below Python program examples:–

  1. Matrix Multiplication In Python Using NumPy
  2. Matrix Multiplication In Python User Input
  3. Python Matrix Multiplication Without NumPy
  4. Matrix Multiplication In Python Using Function
  5. Matrix Multiplication In Python Using For Loop
  6. Matrix Multiplication In Python Using List
  7. Dynamic Matrix Multiplication In Python

Matrix Multiplication in Python using NumPy

Now, let’s see an example to multiply two matrices using NumPy, that is NumPy matrix multiplication. As we know NumPy is a built-in library available in python which has a number of functions that simplify the python code.

The numpy.dot() function returns the dot product of two arrays or matrices. For 1-dimensional arrays, it is the inner product of the vectors. For 2-dimensional vectors, it is equivalent to the multiplication of matrices. For N-dimensional arrays, it is a sum-product over the last axis of a and the second-last axis of b.

# Python program to multiply two matrices using numpy

# import NumPy library
import numpy

# take inputs
m1 = [[1, 7],
      [4, 5]]

m2 = [[5, 3],
      [4, 2]]

res = [[0, 0],
       [0, 0]]

# multiply matrix
print("Matrix Multiplication: ")
result = numpy.dot(m1, m2)
for row in result:
   print(row)

Output:-

Matrix Multiplication:
[33 17]
[40 22]

In the above code, the length of the code has been reduced due because of the numpy.dot() function. This function directly multiplies two matrices. This is just a single-line implementation.

Matrix Multiplication in Python User Input

Here, we take user input to multiply two matrices. We will take row values and column values from the user and then proceed with the elements.

# Python program to multiply two matrices

# import NumPy library
import numpy

# take first matrix inputs
print("Enter 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 order of matrix 2:")
p, q = list(map(int, input().split()))
print("Enter row values")
m2 = []
for j in range(p):
   print("Enter row ", j, "values: ")
   row = list(map(int, input().split()))
   m2.append(row)

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

# multiply matrix
print("Matrix Multiplication: ")
result = numpy.dot(m1, m2)
for row in result:
   print(row)

Output:-

Enter the order of matrix 1:
2 2
Enter row values
Enter row 0 values:
1 3
Enter row 1 values:
5 6
Enter the order of matrix2:
2 2
Enter row values
Enter row 0 value:
7 2
Enter row 1 value:
6 9
Matrix 1: [[1, 3], [5, 6]]
Matrix 2: [[7, 2], [6, 9]]
Matrix Multiplication:
[25, 29]
[71, 64]

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 the second matrix where p, q are rows and columns respectively. Then, the matrix is multiplied using numpy.dot(), and the result is stored.

Python Matrix Multiplication Without NumPy

In the previous program, we used NumPy to multiply two matrices but in this program, we will multiply two matrices without NumPy.

# 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 order of matrix 1:
3 3
Enter row values
Enter row 0 values:
1 2 1
Enter row 1 values:
2 3 1
Enter row 2 values:
2 0 4
Enter order of matrix 2:
3 3
Enter row values
Enter row 0 values:
1 2 0
Enter row 1 values:
3 1 2
Enter row 2 values:
2 1 4
Matrix 1: [[1, 2, 1], [2, 3, 1], [2, 0, 4]]
Matrix 2: [[1, 2, 0], [3, 1, 2], [2, 1, 4]]
Matrix Multiplication:
[9 5 8]
[13 8 10]
[10 8 16]

Matrix Multiplication in Python Using Function

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 using function

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]: 6
m1[0][1]: 5
m1[1][0]: 4
m1[1][1]: 3
m1[2][0]: 2
m1[2][1]: 1
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]: 4
m2[0][1]: 3
m2[0][2]: 2
m2[1][0]: 5
m2[1][1]: 6
m2[1][2]: 9
Matrix 1:
6 5
4 3
2 1
Matrix 2:
4 3 2
5 6 9
Result:
49 48 57
31 30 35
13 12 13

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. 

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. 

Matrix Multiplication in Python Using For Loop

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 using for loop

m1 = [[1, 7, 13],
      [4, 15, 6],
      [17, 0, 9]]
m2 = [[5, 3, 1, 2],
      [8, 7, 3, 0],
      [4, 0, 0, 1]]
res = [[0, 0, 0, 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:-

[113,52,22,15]
[164,117,49,14]
[121,51,17,43]

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 Using a List

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

# Python program to multiply two matrices using a list

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

# 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:-

[72,111,39,27]
[24,30,54,6]
[76,109,89,25]

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 = [5, 12, 18, 25, 19]

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

Output:-

The minimum cost is 5705

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 *