strassen矩阵乘法c++
时间: 2023-05-26 13:06:04 浏览: 127
以下是使用C语言实现的Strassen标准矩阵乘法算法的代码:
```
#include <stdio.h>
#define N 4 // 矩阵大小
#define THRESHOLD 2 // 阈值
// 矩阵加法
void add_matrix(int a[][N], int b[][N], int c[][N])
{
int i, j;
for (i = 0; i < N; i++) {
for (j = 0; j < N; j++) {
c[i][j] = a[i][j] + b[i][j];
}
}
}
// 矩阵减法
void sub_matrix(int a[][N], int b[][N], int c[][N])
{
int i, j;
for (i = 0; i < N; i++) {
for (j = 0; j < N; j++) {
c[i][j] = a[i][j] - b[i][j];
}
}
}
// Strassen矩阵乘法
void strassen_mul(int a[][N], int b[][N], int c[][N])
{
// 达到阈值,使用标准矩阵乘法
if (N <= THRESHOLD) {
int i, j, k;
for (i = 0; i < N; i++) {
for (j = 0; j < N; j++) {
c[i][j] = 0;
for (k = 0; k < N; k++) {
c[i][j] += a[i][k] * b[k][j];
}
}
}
return;
}
// 处理矩阵的大小并向上取整
int size = N / 2;
if (N % 2 != 0) {
size += 1;
}
int A[size][size], B[size][size], C[size][size], D[size][size];
int E[size][size], F[size][size], G[size][size], H[size][size];
int P1[size][size], P2[size][size], P3[size][size], P4[size][size], P5[size][size], P6[size][size], P7[size][size];
int tmp1[size][size], tmp2[size][size];
// 拆分矩阵
int i, j;
for (i = 0; i < size; i++) {
for (j = 0; j < size; j++) {
A[i][j] = a[i][j];
B[i][j] = a[i][j + size];
C[i][j] = a[i + size][j];
D[i][j] = a[i + size][j + size];
E[i][j] = b[i][j];
F[i][j] = b[i][j + size];
G[i][j] = b[i + size][j];
H[i][j] = b[i + size][j + size];
}
}
// 计算P1到P7
sub_matrix(F, H, tmp1);
strassen_mul(A, tmp1, P1);
add_matrix(A, B, tmp1);
strassen_mul(tmp1, H, P2);
add_matrix(C, D, tmp1);
strassen_mul(tmp1, E, P3);
sub_matrix(G, E, tmp1);
strassen_mul(D, tmp1, P4);
add_matrix(A, D, tmp1);
add_matrix(E, H, tmp2);
strassen_mul(tmp1, tmp2, P5);
sub_matrix(B, D, tmp1);
add_matrix(G, H, tmp2);
strassen_mul(tmp1, tmp2, P6);
sub_matrix(A, C, tmp1);
add_matrix(E, F, tmp2);
strassen_mul(tmp1, tmp2, P7);
// 计算结果矩阵
add_matrix(P5, P4, tmp1);
sub_matrix(tmp1, P2, tmp2);
add_matrix(tmp2, P6, c[0]);
add_matrix(P1, P2, c[1]);
add_matrix(P3, P4, c[2]);
add_matrix(P5, P1, tmp1);
sub_matrix(tmp1, P3, tmp2);
sub_matrix(tmp2, P7, c[3]);
}
int main()
{
int a[N][N] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}};
int b[N][N] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}};
int c[N][N];
int i, j;
strassen_mul(a, b, c);
printf("Result:\n");
for (i = 0; i < N; i++) {
for (j = 0; j < N; j++) {
printf("%d ", c[i][j]);
}
printf("\n");
}
return 0;
}
```
本代码中定义了THRESHOLD变量,当矩阵大小小于等于阈值时,使用标准矩阵乘法算法计算。简单起见,本代码中矩阵大小固定为4 * 4,可以根据需要修改。
阅读全文