From 3df20257b0366ae60c6d498d8479ff9075f00cae Mon Sep 17 00:00:00 2001 From: Ziver Koc Date: Thu, 11 Jan 2018 16:35:33 +0100 Subject: [PATCH] Added multiply by element function --- src/zutil/math/MatrixMath.java | 18 ++++++++++++++++++ test/zutil/math/MatrixMathTest.java | 6 ++++++ 2 files changed, 24 insertions(+) diff --git a/src/zutil/math/MatrixMath.java b/src/zutil/math/MatrixMath.java index 5ad4e10..0c09a43 100755 --- a/src/zutil/math/MatrixMath.java +++ b/src/zutil/math/MatrixMath.java @@ -110,6 +110,24 @@ public class MatrixMath { return result; } + /** + * Element multiplication, each element in matrix1 will be + * multiplied with the corresponding element in matrix2. + * + * @return a new matrix with the result + */ + public static double[][] elemMultiply(double[][] matrix1, double[][] matrix2){ + elementalPreCheck(matrix1, matrix2); + double[][] result = new double[matrix1.length][matrix1[0].length]; + + for (int y=0; y < matrix1.length; ++y) { + for (int x=0; x < matrix1[y].length; ++x){ + result[y][x] = matrix1[y][x] * matrix2[y][x]; + } + } + return result; + } + private static void elementalPreCheck(double[][] matrix1, double[][] matrix2) { if (matrix1.length != matrix2.length || matrix1[0].length != matrix2[0].length) throw new IllegalArgumentException("Matrices need to be of same dimension: " + diff --git a/test/zutil/math/MatrixMathTest.java b/test/zutil/math/MatrixMathTest.java index 193019f..2c2285c 100755 --- a/test/zutil/math/MatrixMathTest.java +++ b/test/zutil/math/MatrixMathTest.java @@ -47,6 +47,12 @@ public class MatrixMathTest { MatrixMath.subtract(new double[][]{{2,3},{-4,9}}, new double[][]{{1,2},{3,4}})); } + @Test + public void elementalMultiply(){ + assertArrayEquals(new double[][]{{2,6},{-12,36}}, + MatrixMath.elemMultiply(new double[][]{{2,3},{-4,9}}, new double[][]{{1,2},{3,4}})); + } + @Test