Related Tags

matrices
python

# How to multiply matrices in Python Educative Answers Team

Matrix multiplication is only possible if the column of the second matrix is equal to rows of the first. In Python, a matrix can be represented in the form of a nested list ( a list inside a list ).

## Syntax

# sample code  for 3x2 matrix
X = [[1,2],[3,4],[5,6]] 1 of 4

## Implementation

In Python, matrix multiplication can be implemented

1. using nested loops
2. using nested list comprehension

### Using nested loops

In this, for loops are used to compute the resultant matrix. This method becomes computationally expensive if the order of matrices increases.

#### Example code

# Program to multiply two matrices using nested loops

# 3x2 matrix
X = [ [1,2],[3,4],[4,5] ]
# 2x3 matrix
Y = [ [1,2,3],[4,5,6] ]

# resultant matrix
result = [ [0,0,0],[0,0,0],[0,0,0] ]

my_list = []
# iterating rows of X matrix
for i in range( len(X) ):
# iterating columns of Y matrix
for j in range(len(Y)):
# iterating rows of Y matrix
for k in range(len(Y)):
result[i][j] += X[i][k] * Y[k][j]

for r in result:
print(r)

### Using nested list comprehension

List comprehension is very useful when creating new lists from other iterables. This method is used to iterate over each element for the given expression. #### Example code

# Program to multiply two matrices using list comprehension

# 3x2 matrix
X = [ [1,2],[3,4],[4,5] ]
# 2x3 matrix
Y = [ [1,2,3],[4,5,6] ]

# resultant matrix
resultant = [[sum(a*b for a,b in zip(X_row,Y_col)) for Y_col in zip(*Y)] for X_row in X]

# printing matrix.
for x in resultant:
print(x)

RELATED TAGS

matrices
python 