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 ).
# sample code for 3x2 matrixX = [[1,2],[3,4],[5,6]]
In Python, matrix multiplication can be implemented
In this, for
loops are used to compute the resultant matrix. This method becomes computationally expensive if the order of matrices increases.
# Program to multiply two matrices using nested loops# 3x2 matrixX = [ [1,2],[3,4],[4,5] ]# 2x3 matrixY = [ [1,2,3],[4,5,6] ]# resultant matrixresult = [ [0,0,0],[0,0,0],[0,0,0] ]my_list = []# iterating rows of X matrixfor i in range( len(X) ):# iterating columns of Y matrixfor j in range(len(Y[0])):# iterating rows of Y matrixfor k in range(len(Y)):result[i][j] += X[i][k] * Y[k][j]for r in result:print(r)
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.
# Program to multiply two matrices using list comprehension# 3x2 matrixX = [ [1,2],[3,4],[4,5] ]# 2x3 matrixY = [ [1,2,3],[4,5,6] ]# resultant matrixresultant = [[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)
Free Resources