Python program to multiply two matrices

PythonServer Side ProgrammingProgramming

In this article, we will learn about the solution to the problem statement given below.

Problem statement − We are given two matrices, we need to multiply them and print the result.

For two matrices to be multiplied columns of the first matrix must be identical to that of the rows of the second matrix

Each time this condition is evaluated to be true computation is performed

Now let’s observe the concept in the implementation below−

Approach 1 − Brute-force method

Example

 Live Demo

A = [[1, 2, 3],
   [4, 5, 6],
   [7, 8, 9]
]
B = [[5, 3, 3],
   [6, 5, 4],
   [0, 2, 0]
]
result= [[0, 0, 0],
   [0, 0, 0],
   [0, 0, 0]
]
# iterating by row
for i in range(len(A)):
   # iterating by column
   for j in range(len(B[0])):
      # iterating by rows
      for k in range(len(B)):
         result[i][j] += A[i][k] * B[k][j]
for ele in result:
   print(ele)

Output

[17, 19, 11]
[50, 49, 32]
[83, 79, 53]

Approach 2 − Using zip function

Example

 Live Demo

A = [[1, 2, 3],
   [4, 5, 6],
   [7, 8, 9]
]
B = [[5, 3, 3],
   [6, 5, 4],
   [0, 2, 0]
]
# using built-in zip function
result = [[sum(a * b for a, b in zip(A_row, B_col))
   for B_col in zip(*B)]
   for A_row in A]
for ele in result:
   print(ele)

Output

[17, 19, 11]
[50, 49, 32]
[83, 79, 53]

Conclusion

In this article, we have learned how to multiply two matrices.

raja
Published on 24-Dec-2019 10:07:06
Advertisements