user10605347
user10605347

Reputation:

Multiply 2 matrices 4x1 and 1x4

The program should multiply 2 matrices 4x1 and 1x4 and output the result to the console (matrix 4X4). But nothing displays. What's the problem?

public class Matrix {
    public static void main(String[] args) {
        int[][] matrixA = new int[4][1];
        int[][] matrixB = new int[1][4];
        int[][] matrixC = new int[4][4];

        matrixA[0][0] = 1;
        matrixA[1][0] = 2;
        matrixA[2][0] = 3;
        matrixA[3][0] = 4;

        matrixB[0][0] = 4;
        matrixB[0][1] = 3;
        matrixB[0][2] = 2;
        matrixB[0][3] = 1;

        for (int i = 0; i < 4; i++) { // A rows
            for (int j = 0; j < 4; j++) { // B columns
                for (int k = 0; k < 1; k++) { // A columns
                    matrixC[i][j] += matrixA[i][k] * matrixB[k][j];
                    System.out.print(matrixC[i][j] + "   ");
                }
            }
        }
        int j = 0;
        for (int i = 0; i < 4; i++) {
            for (int k = 0; k < 1; k++)
                System.out.print(matrixC[i][j] + "   ");
            System.out.println();
        }
    } //end main
} //end class

Upvotes: 0

Views: 1568

Answers (2)

user14940971
user14940971

Reputation:

Hope this helps:

public class Matrix {
    public static void main(String[] args) {
        int[][] matrixA = {{1}, {2}, {3}, {4}};
        int[][] matrixB = {{4, 3, 2, 1}};

        int[][] matrixC = new int[4][4];

        for (int i = 0; i < 4; i++) { // A rows
            for (int j = 0; j < 4; j++) { // B columns
                for (int k = 0; k < 1; k++) { // A columns
                    matrixC[i][j] += matrixA[i][k] * matrixB[k][j];
                    System.out.print(matrixC[i][j] + "   ");
                }
            }
            System.out.println();
        }
    }
}

Output:

4   3   2   1   
8   6   4   2   
12   9   6   3   
16   12   8   4   

Upvotes: 0

Elliott Frisch
Elliott Frisch

Reputation: 201429

You introduced a variable j before your second set of for loops. Also, even if they're optional, I would highly recommend always including braces. And k < 4. Like,

for (int i = 0; i < 4; i++) {
    for (int k = 0; k < 4; k++) {
        System.out.print(matrixC[i][k] + "   "); // not [i][j]
    }
    System.out.println();
}

or just use Arrays.deepToString(Object[]) like

System.out.println(Arrays.deepToString(matrixC));

Upvotes: 1

Related Questions