Matrix Multiplication in Python using For Loop

Matrix Multiplication in Python using For Loop | Here, we will discuss how to multiply two matrices in Python using the for loop. 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.

Python Program to Multiply Two Matrices 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

# take first matrix
m1 = [[1, 2, 3],
      [4, 5, 6],
      [7, 8, 9]]

# take second matrix
m2 = [[9, 8, 7],
      [1, 1, 1],
      [1, 1, 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:-

[14, 13, 12]
[47, 43, 39]
[80, 73, 66]

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 in Python Using For Loop

In this program, we use another input example (3×4 matrix) for matrix multiplication.

# Python program to multiply two matrices using for loop

# take first matrix
m1 = [[20, 21, 22],
      [23, 24, 25],
      [26, 27, 28]]

# take second matrix
m2 = [[29, 28, 27, 26],
      [18, 17, 16, 15],
      [14, 13, 12, 11]]

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

[1266, 1203, 1140, 1077]
[1449, 1377, 1305, 1233]
[1632, 1551, 1470, 1389]

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 *