Python Program - Multiply Two Matrices
https:.www//theitroad.com
Here's a Python program that multiplies two matrices using nested loops:
# Define two matrices A = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] B = [[10, 11, 12], [13, 14, 15], [16, 17, 18]] # Define an empty result matrix result = [[0, 0, 0], [0, 0, 0], [0, 0, 0]] # Iterate through rows of A for i in range(len(A)): # Iterate through columns of B for j in range(len(B[0])): # Iterate through rows of B for k in range(len(B)): # Update the corresponding element of the result matrix result[i][j] += A[i][k] * B[k][j] # Display the result matrix for row in result: print(row)
This program defines two matrices, A
and B
, as nested lists. It then defines an empty matrix result
that will store the result of multiplying A
and B
. The program uses nested loops to iterate through the rows of A
, the columns of B
, and the rows of B
. For each combination of indices (i, j, k)
, the program multiplies the corresponding elements of A
and B
and adds the result to the corresponding element of result
. Finally, the program displays the result matrix.