From e8a8b7e9dd0c27e4582e66df0ed79eb6949e0067 Mon Sep 17 00:00:00 2001 From: Talia Date: Mon, 15 Sep 2025 12:45:26 -0700 Subject: [PATCH] attempted to fix bugs and created tester class Made a new tester with the main method from matrixexample. --- MatrixExample.java | 32 ++++---------------------------- MatrixTester.java | 29 +++++++++++++++++++++++++++++ 2 files changed, 33 insertions(+), 28 deletions(-) create mode 100644 MatrixTester.java diff --git a/MatrixExample.java b/MatrixExample.java index 051e5bc..f93a0b2 100644 --- a/MatrixExample.java +++ b/MatrixExample.java @@ -1,38 +1,15 @@ import java.util.Random; public class MatrixExample { - public static void main(String[] args) { - int[][] matrix = { - { 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 numRows = 6; - int numCols = 7; - - int[][] matrix2 = generateRandomMatrix(numRows, numCols); - int[][] result = multiplyMatrices(matrix, matrix2); - - System.out.println("result length: " + result.length + " x " + result[0].length); - for (int i = 0; i < result.length; i++) { - for (int j = 0; j < result[i].length; i++) { - System.out.print(result[i][j] + " "); - } - System.out.println(); - } - - } public static int[][] multiplyMatrices(int[][] matrix1, int[][] matrix2) { int rows1 = matrix1.length; int cols1 = matrix1[0].length; int rows2 = matrix2.length; int cols2 = matrix2[0].length; + + if (cols1 != rows2) { throw new IllegalArgumentException( @@ -40,17 +17,16 @@ 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-1]; // 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]; } } } - return result; } diff --git a/MatrixTester.java b/MatrixTester.java new file mode 100644 index 0000000..39a5f91 --- /dev/null +++ b/MatrixTester.java @@ -0,0 +1,29 @@ +public class MatrixTester { + public static void main(String[] args) { + int[][] matrix = { + { 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 numRows = 7; + int numCols = 6; + + int[][] matrix2 = MatrixExample.generateRandomMatrix(numCols, numRows); + int[][] result = MatrixExample.multiplyMatrices(matrix, matrix2); + + System.out.println("result length: " + result.length + " x " + result[0].length); + for (int i = 0; i < result.length; i++) { + for (int j = 0; j < result[i].length; j++) { + System.out.print(result[i][j] + " "); + } + System.out.println(); + } + + } + +}