我一直在尝试编码鸿沟并征服矩阵乘法算法
有问题,当我尝试将矩阵划分为四个四分之一时,它会给我一个错误ArrayOutOfIndexBound
我得到的问题是 double [] [] a21
public static double[][] divideAndConquer(double[][] a , double[][] b, int dimension){
if (a.length == 1){
double[][] result = new double[1][1];
result[0][0]= a[0][0]*b[0][0];
return result;
}
else {
int m = dimension/2;
double[][] a11 = new double[m][m];
for(int i = 0; i < m ; i++){
for (int j = 0 ; j< m ; j++)
a11[i][j]= a[i][j];
}
double[][] a21 = new double[m][m];
for(int i = m; i < dimension; i++){
for (int j = 0 ; j< m ; j++)
a21[i][j]= a[i][j];
}
double[][] a12 = new double[m][m];
for(int i = 0; i < m ; i++){
for (int j = m ; j< dimension ; j++)
a12[i][j]= a[i][j];
}
double[][] a22 = new double[m][m];
for(int i = m; i < dimension; i++){
for (int j = m; j < dimension; j++)
a21[i][j]= a[i][j];
}
double[][] b11 = new double[m][m];
for(int i = 0; i < m ; i++){
for (int j = 0 ; j< m ; j++)
b11[i][j]= b[i][j];
}
double[][] b12 = new double[m][m];
for(int i = 0; i < m ; i++){
for (int j = m ; j< dimension ; j++)
b12[i][j]= b[i][j];
}
double[][] b21 = new double[m][m];
for(int i = m; i < dimension; i++){
for (int j = 0 ; j< m ; j++)
b21[i][j]= b[i][j];
}
double[][] b22 = new double[m][m];
for(int i = m; i < dimension; i++){
for (int j = m; j < dimension; j++)
b21[i][j]= b[i][j];
}
double[][] x1 = divideAndConquer(a11,b11,m);
double[][] x2 = divideAndConquer(a12,b21,m);
double[][] x3 = divideAndConquer(a11,b12,m);
double[][] x4 = divideAndConquer(a12,b22,m);
double[][] x5 = divideAndConquer(a21,b11,m);
double[][] x6 = divideAndConquer(a22,b21,m);
double[][] x7 = divideAndConquer(a21,b12,m);
double[][] x8 = divideAndConquer(a22,b22,m);
..........................etc
答案 0 :(得分:0)
如上所述,您的问题是您需要减去数组偏移量;例如,
a12[i][j]= a[i][j];
应该是
a12[i][j-dimension]= a[i][j];
你更大的问题是你正在创建4个新的子矩阵,这将产生吨的垃圾。一旦你完成了这项工作,我会强烈想到通过操纵数组索引来“就地”这样做的方法。
例如,你的新api看起来像
public static double[][] divideAndConquer(double[][] a , double[][] b, int aMinIndex, int aMaxIndex, int bMinIndex, bMaxIndex){
并且你的分而治之将构建min&amp;的子集。最大指数。
答案 1 :(得分:0)
如何使用它进行分区?请考虑它在C中,N / 2是每个分区的块大小
for (int i = 0; i < N / 2; i++) {
for (int j = 0; j < N / 2; j++) {
ha11[i][j] = hA[i][j]; // top left
ha12[i][j] = hA[i][j + N / 2]; // top right
ha21[i][j] = hA[i + N / 2][j]; // bottom left
ha22[i][j] = hA[i + N / 2][j + N / 2]; // bottom right
hb11[i][j] = hB[i][j]; // top left
hb12[i][j] = hB[i][j + N / 2]; // top right
hb21[i][j] = hB[i + N / 2][j]; // bottom left
hb22[i][j] = hB[i + N / 2][j + N / 2]; // bottom right
}
}