English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this example, we will learn to multiply matrices using two different methods: nested loops and nested list comprehension
To understand this example, you should understand the followingPython programmingTopic:
In Python, we can implement a matrix as a nested list (a list within a list).
We can treat each element as a row of the matrix.
For example, X = [[1, 2], [4, 5], [3, 6]] will represent a3x2Matrix.
The first row can be chosen as X[0]. And, the element in the first row and first column can be selected as X[0][0].
Only when the number of columns of X is equal to the number of rows of Y, the multiplication of the two matrices X and Y is defined.
If X is an n x m matrix and Y is an m x l matrix, then XY is defined, with dimensions n x l (but YX is not defined). Here are several methods to implement matrix multiplication in Python.
# Program to multiply two matrices using nested loops # 3x3 matrix X = [[12,7,3], [4 ,5,6], [7 ,8,9] # 3x4 matrix Y = [[5,8,1,2], [6,7,3,0], [4,5,9,1] # The result is 3x4 result = [[0,0,0,0], [0,0,0,0], [0,0,0,0]] # Traverse X rows for i in range(len(X)): # Traverse Y columns for j in range(len(Y[0])): # Traverse Y rows for k in range(len(Y)): result[i][j] += X[i][k] * Y[k][j] for r in result: print(r)
Output result
[114, 160, 60, 27] [74, 97, 73, 14] [119, 157, 112, 23]
In this program, we use nested for loops to traverse each row and column. We accumulate the sum of the products in the result.
This technique is simple, but as we increase the order of the matrix, the amount of computation is very large.
For larger matrix operations, we recommend using optimized software packages, such asNumPyIt is several times faster than the above code (about1000 times).
# Program to multiply two matrices using list comprehension # 3x3 matrix X = [[12,7,3], [4 ,5,6], [7 ,8,9] # 3x4 matrix Y = [[5,8,1,2], [6,7,3,0], [4,5,9,1] # The 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)
The output of this program is the same as the one above. To understand the code above, we must first understand the built-in function zip() and use*Operator unpacks the parameter list.
We use nested lists to traverse each element in the matrix immediately. The code looks complex and unreadable at first glance. But once you master the list comprehension technique, you may not want to use nested loops anymore.