Added multiply by element function

This commit is contained in:
Ziver Koc 2018-01-11 16:35:33 +01:00
parent acc3ccfe1f
commit 3df20257b0
2 changed files with 24 additions and 0 deletions

View file

@ -110,6 +110,24 @@ public class MatrixMath {
return result; 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) { private static void elementalPreCheck(double[][] matrix1, double[][] matrix2) {
if (matrix1.length != matrix2.length || matrix1[0].length != matrix2[0].length) if (matrix1.length != matrix2.length || matrix1[0].length != matrix2[0].length)
throw new IllegalArgumentException("Matrices need to be of same dimension: " + throw new IllegalArgumentException("Matrices need to be of same dimension: " +

View file

@ -47,6 +47,12 @@ public class MatrixMathTest {
MatrixMath.subtract(new double[][]{{2,3},{-4,9}}, new double[][]{{1,2},{3,4}})); 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 @Test