Problem: Write a Python program to multiply two matrices.
Description: Multiplying two matrices is easy but confusing for beginners. Here is an image that illustrates the concept to multiply two matrices.
Python Program: Multiply Two Matrices
matrix1 = [ [1, 2, 3], [4, 5, 6] ] # Uncomment to take Input #matrix1 = [list(map(int,input("Enter the row value separated by space: ").split(" "))) for i in range(int(input("Enter Number of rows: ")))] matrix2 = [ [2, 3, 4], [5, 6, 7], [5, 7, 8] ] #matrix1 = [list(map(int,input("Enter the row value separated by space: ").split(" "))) for i in range(int(input("Enter Number of rows: ")))] result = [ [0, 0, 0], [0, 0, 0] ] # Rows of matrix 1 for i in range(len(matrix1)): # Columns of matrix 2 for j in range(len(matrix2)): #Rows of matrix 2 for k in range(len(matrix2)): result[i][j] += matrix1[i][k]*matrix2[k][j] print(result)
[[27, 36, 42], [63, 84, 99]]
I remember the days when I used to memorize this program for my tests :). The reason is that the matrix multiplication is often confusing for beginners.
Before reading this program I will suggest you go through the above illustration and understand the logic of matrix multiplication.
for loop traverse through rows of matrix 1.
The second nested loop goes through each column of matrix 2 (for every iteration of matrix1 rows).
The thirst loop
k simple means traverse through each row and pickup individual elements to multiply.
An finally we print the matrix. Python print function can directly output list or other objects.
If you have any confusion then feel free to ask in comments.
Related Python Examples: