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 matrix X = [[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 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[0])): # 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)
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 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
View all Courses