简体   繁体   中英

Can someone explain what I am doing wrong with my Matrix Multiply

I am making a program that takes two matrices and sets their value from -2 to 2. It then adds both of them together and outputs that. I have been trying to get my multiply method to work and I have not been able to. It just prints the wrong values. Can someone please explain why I am having this issue.

My code:

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;
}
}

Here is an example of the output I get:

Matrix One:

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

Matrix two:

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

Matrix one and two added together value:

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

Matrix one and two multiplied together value:

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

The multiplication answer should be:

3     0      4
0     0      1
0     0      1

The matrices printed and the matrices multiplies are different. Check for loop initialization in two methods, printMatrix and multMatrix . Also note that Array indexes start at 0. Change value to 10, you will see exception.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM