From 41a70d45b8b103242c9ca3068c6379b1d06fabbb Mon Sep 17 00:00:00 2001 From: Ziver Koc Date: Sun, 3 Dec 2017 18:14:19 +0100 Subject: [PATCH] Added identity matrix --- src/zutil/math/MatrixMath.java | 16 ++++++++++++++++ test/zutil/math/MatrixMathTest.java | 11 +++++++++++ 2 files changed, 27 insertions(+) diff --git a/src/zutil/math/MatrixMath.java b/src/zutil/math/MatrixMath.java index ce39dbf..a409c71 100755 --- a/src/zutil/math/MatrixMath.java +++ b/src/zutil/math/MatrixMath.java @@ -196,4 +196,20 @@ public class MatrixMath { "matrix1 " + matrix1.length + "x" + matrix1[0].length + ", " + "matrix2 " + matrix2.length + "x" + matrix2[0].length + ", "); } + + /*********************************************************************** + * Util Methods + **********************************************************************/ + + /** + * @return a identity matrix (n x n) where the diagonal elements have the value 1 + */ + public static double[][] identity(int n){ + double[][] result = new double[n][n]; + + for (int i=0; i < n; ++i) { + result[i][i] = 1; + } + return result; + } } diff --git a/test/zutil/math/MatrixMathTest.java b/test/zutil/math/MatrixMathTest.java index 921535e..cf14ab2 100755 --- a/test/zutil/math/MatrixMathTest.java +++ b/test/zutil/math/MatrixMathTest.java @@ -80,4 +80,15 @@ public class MatrixMathTest { } + + @Test + public void identity(){ + assertArrayEquals( + new double[][]{{1}}, + MatrixMath.identity(1)); + + assertArrayEquals( + new double[][]{{1,0,0,0},{0,1,0,0},{0,0,1,0},{0,0,0,1}}, + MatrixMath.identity(4)); + } } \ No newline at end of file