Write a program to Multiply Two Matrices in Python
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | # Program to multiply two matrices using nested loops # 3x3 matrix X = [[12,7,3], [4 ,5,6], [7 ,8,9]] # 3x4 matrix Y = [[5,8,1,2], [6,7,3,0], [4,5,9,1]] # result is 3x4 result = [[0,0,0,0], [0,0,0,0], [0,0,0,0]] # iterate through rows of X for i in range(len(X)): # iterate through columns of Y for j in range(len(Y[0])): # iterate through rows of Y for k in range(len(Y)): result[i][j] += X[i][k] * Y[k][j] for r in result: print(r) |
This program uses nested loops to multiply two matrices, X and Y, together. The result is stored in a 3×4 matrix called “result.”
The outermost loop iterates through the rows of matrix X. For each row, the next loop iterates through the columns of matrix Y. For each column, the innermost loop iterates through the rows of matrix Y.
At each iteration, the element of the “result” matrix at the current row and column is updated by adding the product of the corresponding element of the current row of matrix X and the corresponding element of the current column of matrix Y.
After the loops have finished executing, the final output will be the resulting matrix.
It should be noted that the matrices being multiplied must have the number of columns of the first matrix match the number of rows of the second matrix, in this case 3×3 and 3×4 , otherwise the operation cannot be performed.