根据之前的文章strassen方法求矩阵乘法,我们只需要在使用strassen方法前对矩阵进行处理,对任意行列数的矩阵mxn,在最后一行或最后一列后面添加0,使行数和列数补齐为2的幂。
修改之前的代码如下:
void MatrixMultipy(int* a, int arow, int acol, int* b, int brow, int bcol, int* c)
{
int aM = 1;
while (aM < arow)
{
aM *= 2;
}
int aN = 1;
while (aN < acol)
{
aN *= 2;
}
DATATYPE* aa = new DATATYPE[aM*aN];
memset(aa, 0, sizeof(DATATYPE)*aM*aN);
SubMat A(aa, aM, aN);
for (int i = 0; i < arow; i++)
{
for (int j = 0; j < acol; j++)
{
A.SetData(i, j, a[i*acol+j]);
}
}
int bM = 1;
while (bM < brow)
{
bM *= 2;
}
int bN = 1;
while (bN < bcol)
{
bN *= 2;
}
DATATYPE* bb = new DATATYPE[bM*bN];
memset(bb, 0, sizeof(DATATYPE)*bM*bN);
SubMat B(bb, bM, bN);
for (int i = 0; i < brow; i++)
{
for (int j = 0; j < bcol; j++)
{
B.SetData(i, j, b[i*bcol + j]);
}
}
DATATYPE* cc = new DATATYPE[aM*bN];
memset(cc, 0, sizeof(DATATYPE)*aM*bN);
SubMat C(cc, aM, bN);
MatrixMultiplyAB(A,B,C);
for (int i = 0; i < arow; i++)
{
for (int j = 0; j < bcol; j++)
{
c[i*bcol + j] = C.GetData(i, j);
}
}
}