使用python实现分治法中的矩阵乘法
时间: 2023-11-02 09:16:10 浏览: 60
用python实现矩阵乘法
以下是使用Python实现分治法中的矩阵乘法的代码:
```python
def matrix_multiply(A, B):
n = len(A)
C = [[0 for j in range(n)] for i in range(n)]
if n == 1:
C[0][0] = A[0][0] * B[0][0]
else:
# 分割矩阵
A11, A12, A21, A22 = sub_matrix(A)
B11, B12, B21, B22 = sub_matrix(B)
# 递归计算
C11 = matrix_add(matrix_multiply(A11, B11), matrix_multiply(A12, B21))
C12 = matrix_add(matrix_multiply(A11, B12), matrix_multiply(A12, B22))
C21 = matrix_add(matrix_multiply(A21, B11), matrix_multiply(A22, B21))
C22 = matrix_add(matrix_multiply(A21, B12), matrix_multiply(A22, B22))
# 合并子矩阵
merge_matrix(C, C11, C12, C21, C22)
return C
def sub_matrix(A):
n = len(A)
m = n//2
A11 = [[0 for j in range(m)] for i in range(m)]
A12 = [[0 for j in range(m)] for i in range(m)]
A21 = [[0 for j in range(m)] for i in range(m)]
A22 = [[0 for j in range(m)] for i in range(m)]
for i in range(m):
for j in range(m):
A11[i][j] = A[i][j]
A12[i][j] = A[i][j+m]
A21[i][j] = A[i+m][j]
A22[i][j] = A[i+m][j+m]
return A11, A12, A21, A22
def matrix_add(A, B):
n = len(A)
C = [[0 for j in range(n)] for i in range(n)]
for i in range(n):
for j in range(n):
C[i][j] = A[i][j] + B[i][j]
return C
def merge_matrix(C, C11, C12, C21, C22):
n = len(C)
m = n//2
for i in range(m):
for j in range(m):
C[i][j] = C11[i][j]
C[i][j+m] = C12[i][j]
C[i+m][j] = C21[i][j]
C[i+m][j+m] = C22[i][j]
```
在上面的代码中,我们定义了四个函数:`matrix_multiply`、`sub_matrix`、`matrix_add`和`merge_matrix`。
`sub_matrix`函数用于将一个矩阵分成四个子矩阵,即A11、A12、A21和A22。
`matrix_add`函数用于将两个矩阵相加。
`merge_matrix`函数用于将四个子矩阵合并成一个矩阵。
`matrix_multiply`函数是我们的主函数,它用于计算两个矩阵的乘积。如果矩阵的大小为1x1,则直接计算乘积。否则,我们将矩阵分成四个子矩阵,并递归地计算它们的乘积。最后,我们将四个子矩阵的乘积合并成一个矩阵。
下面是一个示例,演示如何使用上面的代码计算两个矩阵的乘积:
```python
A = [[1, 2], [3, 4]]
B = [[5, 6], [7, 8]]
C = matrix_multiply(A, B)
print(C)
```
输出结果为:
```
[[19, 22], [43, 50]]
```
这个结果与直接计算AB的结果相同。
阅读全文