Multiply 2 matrices 4x1 and 1x4

481 views java
8

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

answered question

It outputs something on my console, as it clearly should considering the print statements.

note that the second nested loop thingy uses the wrong index j and only iterates one time in the inner loop.

1 Answer

5

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

posted this

Have an answer?

JD

Please login first before posting an answer.