I need this for a project of mine. I have a basic understanding of the algorithm, I copied the code from the internet but it seems to not work if the dimensions of a matrix are uneven (3 5 7, etc). The code is a part of the Matrix Class.
private static double[][] multiply(double[][] matrixA, double[][] matrixB) //recursive multiplication function { int n = matrixA.length;
double[][] MatrixRes = new double[n][n];
if (n == 1) {
MatrixRes[0][0] = matrixA[0][0] * matrixB[0][0];
return MatrixRes;
}
double[][] A11 = new double[n / 2][n / 2];
double[][] A12 = new double[n / 2][n / 2];
double[][] A21 = new double[n / 2][n / 2];
double[][] A22 = new double[n / 2][n / 2];
double[][] B11 = new double[n / 2][n / 2];
double[][] B12 = new double[n / 2][n / 2];
double[][] B21 = new double[n / 2][n / 2];
double[][] B22 = new double[n / 2][n / 2];
split(matrixA, A11, 0, 0);
split(matrixA, A12, 0, n / 2);
split(matrixA, A21, n / 2, 0);
split(matrixA, A22, n / 2, n / 2);
split(matrixB, B11, 0, 0);
split(matrixB, B12, 0, n / 2);
split(matrixB, B21, n / 2, 0);
split(matrixB, B22, n / 2, n / 2);
double[][] M1 = multiply(add(A11, A22), add(B11, B22));
double[][] M2 = multiply(add(A21, A22), B11);
double[][] M3 = multiply(A11, sub(B12, B22));
double[][] M4 = multiply(A22, sub(B21, B11));
double[][] M5 = multiply(add(A11, A12), B22);
double[][] M6 = multiply(sub(A21, A11), add(B11, B12));
double[][] M7 = multiply(sub(A12, A22), add(B21, B22));
double[][] C11 = add(sub(add(M1, M4), M5), M7);
double[][] C12 = add(M3, M5);
double[][] C21 = add(M2, M4);
double[][] C22 = add(sub(add(M1, M3), M2), M6);
join(C11, MatrixRes, 0, 0);
join(C12, MatrixRes, 0, n / 2);
join(C21, MatrixRes, n / 2, 0);
join(C22, MatrixRes, n / 2, n / 2);
return MatrixRes;
}
private static double[][] add(double[][] matrix1, double[][] matrix2) // add 2 array matrixes
{
int n = matrix2.length;
double[][] sum = new double[n][n];
for (int i = 0; i < n; i++){
for (int j = 0; j < n; j++)
sum[i][j] = matrix1[i][j] + matrix2[i][j];
}
return sum;
}
private static double[][] sub(double[][] matrix1, double[][] matrix2) // sub 2 array matrixes
{
int n = matrix2.length;
double[][] sub = new double[n][n];
for (int i = 0; i < n; i++){
for (int j = 0; j < n; j++)
sub[i][j] = matrix1[i][j] - matrix2[i][j];
}
return sub;
}
private static void split(double[][] P, double[][] C, int iB, int jB) // split (used for multiplication)
{
for (int i1 = 0, i2 = iB; i1 < C.length; i1++, i2++)
for (int j1 = 0, j2 = jB; j1 < C.length;
j1++, j2++)
C[i1][j1] = P[i2][j2];
}
private static void join(double[][] C, double[][] P, int iB, int jB) // join (used for multiplication)
{
for (int i1 = 0, i2 = iB; i1 < C.length; i1++, i2++)
for (int j1 = 0, j2 = jB; j1 < C.length;
j1++, j2++)
P[i2][j2] = C[i1][j1];
}
Check the matrix multiplication algorithm below. I added time complexity analysis, naive approach and a main function to test the code as well. It covers the cases if
n
is not a power of two (or uneven of course).