有人可以用我的Matrix Multiply解释我做错了什么

时间:2016-01-28 04:17:26

标签: java matrix printing

我正在创建一个带有两个矩阵的程序,并将它们的值设置为-2到2.然后将它们加在一起并输出。我一直试图让我的乘法方法起作用,但我无法做到。它只是打印错误的值。有人可以解释我为什么遇到这个问题。

我的代码:

public class TwoDStuff {

public static void main(String[] args) {
    int[][] D = new int[10][10];
    int[][] E = new int[10][10];
    int[][] F = new int[10][10];

    loadMatrix(D);
    loadMatrix(E);

    System.out.println("Matrix One:");
    printMatrix(D, 3);
    System.out.println("Matrix two:");
    printMatrix(E, 3);

    System.out.println("Matrix one and two added together value:");
    addMatrix(D, E, F, 3);
    printMatrix(F, 3);

    System.out.println("Matrix one and two multiplied together value:");
    multMatrix(D, E, F, 3);
    printMatrix(F, 3);
}

public static void loadMatrix(int[][] A) {
    for (int Row = 0; Row < A.length; Row++) {
        for (int Col = 0; Col < A.length; Col++) {
            A[Row][Col] = (int) ((Math.random() * 6 - 3));
        }
    }
}

public static void printMatrix(int[][] A, int n) {
    System.out.println();
    for (int Row = 1; Row <= n; Row++) {
        for (int Col = 1; Col <= n; Col++) {
            System.out.print(Format.rightAlign(6, A[Row][Col]));
        }
        System.out.println();
    }
    System.out.println();
}

public static int addMatrix(int[][] A, int[][] B, int[][] C, int n) {
    System.out.println();
    for (int Row = 0; Row <= n; Row++) {
        for (int Col = 0; Col <= n; Col++) {
            C[Row][Col] = A[Row][Col] + B[Row][Col];

        }

    }
    return n;
}

public static int multMatrix(int[][] A, int[][] B, int[][] C, int n) {

    for (int Row = 0; Row <= n; Row++) {
        for (int Col = 0; Col <= n; Col++) {
            for (int i = 1; i <= n; i++) {
                C[Row][Col] = C[Row][Col] + A[Row][i] * B[i][Col];
            }
        }

    }
    return n;
}
}

以下是我得到的输出示例:

Matrix One:

 2    -1    -1
 0    -1     0
-1    -1    -1

Matrix II:

 1     0     1
 0     0    -1
-1     0    -1

矩阵一和二加在一起的值:

 3    -1     0
 0    -1    -1
-2    -1    -2

矩阵一和二乘以值:

 6    -1     4
 0    -1     0
-2    -1    -1

乘法答案应为:

3     0      4
0     0      1
0     0      1

1 个答案:

答案 0 :(得分:0)

印刷的矩阵和矩阵的乘法是不同的。使用forprintMatrix两种方法检查multMatrix循环初始化。另请注意,数组索引从0开始。将值更改为10,您将看到异常。