Python Program to multiply two matrices


April 14, 2022, Learn eTutorial
1092

In this simple python program, we need to multiply two matrices. It's a matrix python program.

To understand this example, you should have knowledge of the following Python programming topics:

What is the Matrix?

A matrix is a set of elements that are of the same data type, which is arranged in rows and columns. Each element in a matrix is denoted by a[i][j], where,

  • 'a' is the name of Matrix.
  • The subscript 'i' is the Row name.
  • The subscript 'j' is the Column name.

How we multiply two matrices in python?

Now in this simple python program, we have to multiply two matrices and get a result matrix. Matrix multiplication is a binary operation where the sum of elements in each row of matrix A is multiplied with elements in each column of matrix B to get the resultant matrix C.

For matrix multiplication, we have to satisfy one condition as the number of columns in the first matrix will be equal to the number of rows in the second matrix. For example, let us take two matrices A and B and to get the result matrix C, [a11 a12][a31 a32] * [b12 b13] [b22 b23] c12 = a11b12 + a12b22 c33 = a31b13 + a32b23. In this python program, we accept two matrices from the user, and we initialize the third matrix as zero.

Then we use three for loop nested to calculate the result as the sum of the element in the first column of the first matrix A multiplied with the first element in the first row of second matrix B and continue that using the for loop in python. Then print the result.

ALGORITHM

STEP 1: Initialize the two matrices X and Y.

STEP 2: Initialize a matrix result as zero.

STEP 3: Use 3 for loop nested for traversing each element in the first matrix row of matrix A and each element in the column of matrix B.

STEP 4: Apply the result[i][j] += X[i][k] * Y[k][j] to get the result matrix elements and print the result using the print statement in python programming language.

Python Source Code

                                          X = [[1,2,3],  
    [4,5,6],  
    [7,8,9]]  
  
Y = [[10,11,12],  
    [13,14,15],  
    [16,17,18]]  
  
Result = [[0,0,0],  
         [0,0,0],  
         [0,0,0]]  
for i in range(len(X)):
 
   for j in range(len(Y[0])):

       for k in range(len(Y)):
         Result[i][j] += X[i][k] * Y[k][j]

for r in Result:
   print(r)

                                      

OUTPUT

[[84, 90, 96]
[201, 216, 231]
[318, 342, 366]]