Method Example of Multiplication Operation of Matrix by Pure python
- 2021-07-22 09:58:05
- OfStack
This paper introduces the pure python matrix multiplication method example, to share with you, as follows:
def matrixMultiply(A, B):
# Get A Number of rows and columns of
A_row, A_col = shape(A)
# Get B Number of rows and columns of
B_row, B_col = shape(B)
# Judgment of inability to calculate
if(A_col != B_row):
raise ValueError
# Final matrix
result = []
# zip After unpacking, it is a transposed tuple, which is strongly transformed into list, Deposit result Medium
BT = [list(row) for row in zip(*B)]
# Start doing product operation
for A_index in range(A_row):
# Used to record each row element of the new matrix
rowItem = []
for B_index in range(len(BT)):
# num Used for accumulation
num = 0
for Br in range(len(BT[B_index])):
num += A[A_index][Br] * BT[B_index][Br]
# After the accumulation is completed, store the data in the rows of the new matrix
rowItem.append(num)
result.append(rowItem)
return result
A Matrix and B Matrix multiplication, finally get a new matrix X, ideas
First, determine whether multiplication is possible: the premise is that the columns of A are the same as the rows of B We can draw a picture to understand: If A is 3 rows and 5 columns, B is 5 rows and 2 columns, the multiplication result is 3 rows and 2 columns When B is transposed, it is 2 rows and 5 columns, which we call BT, so that A and BT are both 5 columns Then the i-th element in each row of A * the i-th element in each row of BT are added to form a new row of the new matrix X, and the A row is circulated for a total of 3 rows, then the new row is gradually added to the new matrix X, and the new matrix X is obtained after the circulation is completed