用C语言写出Strassen矩阵乘法
时间: 2023-06-04 08:02:14 浏览: 111
01_比较矩阵相乘的常规法和Strassen方法.zip_01矩阵算法_C++_VS2012
好的,可以,下面是C语言实现的Strassen矩阵乘法代码:
```c
void strassen(int **A, int **B, int **C, int n) {
int i, j;
if (n == 1) {
C[0][0] = A[0][0] * B[0][0];
return;
}
int **A11 = allocate(n/2), **A12 = allocate(n/2), **A21 = allocate(n/2), **A22 = allocate(n/2);
int **B11 = allocate(n/2), **B12 = allocate(n/2), **B21 = allocate(n/2), **B22 = allocate(n/2);
int **C11 = allocate(n/2), **C12 = allocate(n/2), **C21 = allocate(n/2), **C22 = allocate(n/2);
int **M1 = allocate(n/2), **M2 = allocate(n/2), **M3 = allocate(n/2), **M4 = allocate(n/2), **M5 = allocate(n/2), **M6 = allocate(n/2), **M7 = allocate(n/2);
int **temp1 = allocate(n/2), **temp2 = allocate(n/2), **temp3 = allocate(n/2), **temp4 = allocate(n/2), **temp5 = allocate(n/2), **temp6 = allocate(n/2), **temp7 = allocate(n/2);
split_matrix(A, A11, A12, A21, A22, n);
split_matrix(B, B11, B12, B21, B22, n);
sub_matrix(B12, B22, temp1, n/2);
strassen(A11, temp1, M1, n/2);
add_matrix(A11, A12, temp2, n/2);
strassen(temp2, B22, M2, n/2);
add_matrix(A21, A22, temp3, n/2);
strassen(temp3, B11, M3, n/2);
sub_matrix(B21, B11, temp4, n/2);
strassen(A22, temp4, M4, n/2);
add_matrix(A11, A22, temp5, n/2);
add_matrix(B11, B22, temp6, n/2);
strassen(temp5, temp6, M5, n/2);
sub_matrix(A12, A22, temp7, n/2);
add_matrix(B21, B22, temp6, n/2);
strassen(temp7, temp6, M6, n/2);
sub_matrix(A11, A21, temp7, n/2);
add_matrix(B11, B12, temp6, n/2);
strassen(temp7, temp6, M7, n/2);
add_matrix(M5, M4, temp1, n/2);
sub_matrix(temp1, M2, temp2, n/2);
add_matrix(temp2, M6, C11, n/2);
add_matrix(M1, M2, C12, n/2);
add_matrix(M3, M4, C21, n/2);
add_matrix(M5, M1, temp3, n/2);
sub_matrix(temp3, M3, temp4, n/2);
sub_matrix(temp4, M7, C22, n/2);
merge_matrix(C, C11, C12, C21, C22, n);
deallocate(A11, n/2); deallocate(A12, n/2); deallocate(A21, n/2); deallocate(A22, n/2);
deallocate(B11, n/2); deallocate(B12, n/2); deallocate(B21, n/2); deallocate(B22, n/2);
deallocate(C11, n/2); deallocate(C12, n/2); deallocate(C21, n/2); deallocate(C22, n/2);
deallocate(M1, n/2); deallocate(M2, n/2); deallocate(M3, n/2); deallocate(M4, n/2);
deallocate(M5, n/2); deallocate(M6, n/2); deallocate(M7, n/2);
deallocate(temp1, n/2); deallocate(temp2, n/2); deallocate(temp3, n/2);
deallocate(temp4, n/2); deallocate(temp5, n/2); deallocate(temp6, n/2); deallocate(temp7, n/2);
}
```
希望能够帮助到你!
阅读全文