How to Multiply Two Matrices using Python?


Multiplication of two matrices is possible only when number of columns in first matrix equals number of rows in second matrix.

Multiplication can be done using nested loops. Following program has two matrices x and y each with 3 rows and 3 columns. The resultant z matrix will also have 3X3 structure. Element of each row of first matrix is multiplied by corresponding element in column of second matrix.

Example

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]]  
 
# iterate through rows of X  
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

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

Updated on: 02-Mar-2020

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements