【问题标题】:Method to multiply 2 two-dimensional array2个二维数组相乘的方法
【发布时间】:2015-09-09 18:44:01
【问题描述】:

我正在尝试创建一个将 2 个二维数组作为参数并打印它们的乘法数组的方法(就像方法中的矩阵乘法一样)。似乎它在运行时被卡在无限循环中的某个地方。有修改吗?

public static void multiplicationOfArray(int[][] matrix1, int[][] matrix2) {
    int row1 = matrix1.length;
    int column1 = matrix1[0].length;
    int row2 = matrix2.length;
    int column2 = matrix2[0].length;
    int[][] resultmatrix = new int[row1][column2];

    if (column1 == row2) {
        for (int i = 0; i < row1; row1++) {
            for(int j = 0; j < column2; j++) {
                for (int k = 0; k < column1; k++) {
                    resultmatrix[i][j] += matrix1[i][k] * matrix2[k][j];
                }
            }
        }

        for (int row = 0; row < row1; row++) {
            for (int column = 0; column < column2; column++) {
                System.out.println(resultmatrix[row][column] + " ");
            }
            System.out.println();
        }
    }
}

【问题讨论】:

  • for (int i = 0; i &lt; row1; row1++) { 看起来应该是 for (int i = 0; i &lt; row1; i++) {

标签: java arrays algorithm loops matrix-multiplication


【解决方案1】:

如果尺寸不正确/有效,那么您可能会抛出异常。 你也可以试试这个方法——

public static double[][] multiply(double[][] A, double[][] B) {
        int mA = A.length;
        int nA = A[0].length;
        int mB = B.length;
        int nB = B[0].length;
        if (nA != mB) throw new RuntimeException("Illegal matrix dimensions.");
        double[][] C = new double[mA][nB];
        for (int i = 0; i < mA; i++)
            for (int j = 0; j < nB; j++)
                for (int k = 0; k < nA; k++)
                    C[i][j] += A[i][k] * B[k][j];
        return C;
    }  

完整的代码可以在here找到。

【讨论】:

  • 谢谢哥们,非常有用的链接! :)
  • O(n^3) 解决方案。您可以尝试对此进行优化。阅读Strassen algo,它试图在 O(n^2.8) 中解决它
【解决方案2】:

您的 for 循环条件有点混乱。例如这个循环:

for (int i = 0; i < row1; row1++) {

只会在i 大于row1 时终止,但是,在剩余的代码或循环中,您不会增加i 的值或减少row1 的值,因此条件@987654326 @永远不会遇到。

试试这个:

public static void multiplicationOfArray(int[][] matrix1, int[][] matrix2) {
    int row1 = matrix1.length;
    int coloumn1 = matrix1[0].length;
    int row2 = matrix2.length;
    int coloumn2 = matrix2[0].length;
    int[][] resultmatrix = new int[row1][coloumn2];

    if (coloumn1 == row2) {
        for (int i = 0; i < row1; i++) {
            for(int j = 0; j < coloumn2; j++) {
                for (int k = 0; k < coloumn1; k++) {
                    resultmatrix[i][j] += matrix1[i][k] * matrix2[k][j];
                    }
                }
            }
        for (int row = 0; row < row1; row++) {
            for (int coloumn = 0; coloumn < coloumn2; coloumn++) {
                System.out.println(resultmatrix[row][coloumn] + " ");
            }
            System.out.println();
        }
    }
}

【讨论】:

    猜你喜欢
    • 2013-09-21
    • 2018-07-16
    • 1970-01-01
    • 2014-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-18
    • 1970-01-01
    相关资源
    最近更新 更多