# Matrix Multiplication in Python

21 Dec 2018 7:44 am || 0

## Multiply Matrices in Python

Python allows you to multiply matrices if the matrices you want to find the product of satisfies the condition of multiplication. This means if there are two matrices A and B, and you want to find out the product of A*B, the number of columns in matrix A and the number of rows in matrix B must be the same. Also, multiplication of matrices is not commutable, i.e. A*B is not the same as B*A. This means B*A will not work if the number of columns in matrix B is not equal to the number of rows in matrix A.

The number of rows of the resultant matrix will be equal to the number of rows in the first matrix. Similarly, the number of columns in the resultant matrix will be the same as the number of columns in the second matrix.

To multiply matrices you can use either nested loops i.e. loops within a loop, or nested list i.e. lists within a list.

To perform multiplication of matrices using nested loops, you can follow the following example with nested for loops.

Input

### Program to multiply two matrices using nested loops

``````# 3x3 matrix
A = [[9,7,3],
[4,2,6],
[7,8,15]]
# 3x4 matrix
B = [[5,7,1,3],
[6,0,3,0],
[4,9,3,1]]
# result is 3x4
result =  [[0,0,0,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)):
# iterate through rows of B
for k in range(len(B)):
result[i][j] += A[i][k] * B[k][j]
for r in result:
print(r)
``````

Output

[99, 90, 39, 30]
[56, 82, 28, 18]
[143, 184, 76, 36]

You can perform the same multiplication using nested lists instead of loops. The following example demonstrates it.

Input

### Program to find the product of two matrices using nested lists

``````# 3x3 matrix
X =  [9,7,3],
[4,2,6],
[7,8,15]
# 3x4 matrix
Y = [5,7,1,3],
[6,0,3,0],
[4,9,3,1]
# result is 3x4
result = [[sum(a*b for a,b in zip(X_row,Y_col)) for Y_col in zip(*Y)] for X_row in X]
for r in result:
print(r)
``````

Output

[45, 63, 9, 27]

Recommended Posts: