diff --git a/MatrixExample.java b/MatrixExample.java index 051e5bc..fbf4c11 100644 --- a/MatrixExample.java +++ b/MatrixExample.java @@ -40,13 +40,13 @@ public static int[][] multiplyMatrices(int[][] matrix1, int[][] matrix2) { } // Some more issues here too - int[][] result = new int[rows1+1][cols2+1]; + int[][] result = new int[rows1][cols2]; // Lots of issues with this code, it used to be working perfectly though for (int i = 0; i < rows1; i++) { for (int j = 0; j < cols2; j++) { for (int k = 0; k < cols1; k++) { - result[j][k] += matrix1[i][j] * matrix2[k][j]; + result[i][j] += matrix1[i][k] * matrix2[k][j]; } } } diff --git a/MatrixExampleTester.java b/MatrixExampleTester.java new file mode 100644 index 0000000..fb9987f --- /dev/null +++ b/MatrixExampleTester.java @@ -0,0 +1,75 @@ +public class MatrixExampleTester { + public static void main(String[] args) { + // Testing matrix multiplication + int[][] matrix1 = { + { 1, 3, 5 }, + { 3, 5, 7 }, + { 4, 8, 12 } + }; + + int[][] matrix2 = { + { 1, 0, 0 }, + { 0, 1, 0 }, + { 0, 0, 1 } + }; + + int[][] product1 = MatrixExample.multiplyMatrices(matrix1, matrix2); + + printMatrix(product1); + + int[][] matrix3 = { + { 2, 7 }, + { 4, 1 }, + { 9, 9 }, + { 5, 1 } + }; + + int[][] matrix4 = { + { 8, 1, 3, 4, 8 }, + { 2, 4, 6, 8, 0 } + }; + + int[][] product2 = MatrixExample.multiplyMatrices(matrix3, matrix4); + + printMatrix(product2); + + int[][] matrix5 = { + { 1, 2, 3, 4, 5, 6 }, + { 4, 5, 6, 3, 7, 2 }, + { 27, 8, 9, 5, 3, 21 }, + { 73, 2, 19, 5, 1, 8 }, + { 47, 9, 9, 5, 0, 22 }, + { 78, 86, 1, 4, 1, 21 }, + { 73, 18, 2, 2, 5, 11 } + }; + + int[][] matrix6 = { + { 4, 12, 9, 1 }, + { 22, 19, 71, 2 }, + { 3, 55, 81, 47 }, + { 10, 20, 30, 40 }, + { 3, 9, 27, 81 }, + { 11, 21, 20, 7 } + }; + + int[][] product3 = MatrixExample.multiplyMatrices(matrix5, matrix6); + + printMatrix(product3); + + // Testing Random Matrices of various sizes + printMatrix(MatrixExample.generateRandomMatrix(3, 3)); + printMatrix(MatrixExample.generateRandomMatrix(2, 7)); + printMatrix(MatrixExample.generateRandomMatrix(6, 7)); + } + + static public void printMatrix(int[][] matrix) { + System.out.println("result length: " + matrix.length + " x " + matrix[0].length); + for (int i = 0; i < matrix.length; i++) { + for (int j = 0; j < matrix[i].length; j++) { + System.out.print(matrix[i][j] + " "); + } + System.out.println(); + } + System.out.println(); + } +}