Anonymous avatar Anonymous committed 1c42e27

Finally we're able to calculate the inverse and adjugate matrix.

Comments (0)

Files changed (2)

neglect/cpplib/include/neglect/matrix.hpp

         );
     }
 
+    /* return the adjugate matrix */
+
+    template <typename T, size_t N>
+    matrix<T, N, N> adjugate(const matrix<T, N, N> &mat)
+    {
+        matrix<T, N, N> rv;
+        for (size_t i = 0; i < N; i++)
+            for (size_t j = 0; j < N; j++)
+                rv[j][i] = math::pow(static_cast<T>(-1), static_cast<T>(i + j))
+                    * determinant(exclude(mat, i, j));
+        return rv;
+    }
+
+    template <typename T>
+    matrix<T, 2, 2> adjugate(const matrix<T, 2, 2> &mat)
+    {
+        matrix<T, 2, 2> rv;
+        rv[0][0] =  mat[1][1];
+        rv[0][1] = -mat[0][1];
+        rv[1][0] = -mat[1][0];
+        rv[1][1] =  mat[0][0];
+        return rv;
+    }
+
+    /* invert a matrix */
+
+    template <typename T, size_t N>
+    matrix<T, N, N> inverse(const matrix<T, N, N> &mat)
+    {
+        matrix<T, N, N> amat = adjugate(mat);
+        T l = T();
+        for (size_t i = 0; i < N; i++)
+            l += mat[0][i] * amat[i][0];
+
+        for (size_t i = 0; i < N; i++)
+            for (size_t j = 0; j < N; j++)
+                amat[i][j] /= l;
+
+        return amat;
+    }
+
     /* creates a scale matrix */
     template <typename T>
     matrix<T, 4, 4> scale_matrix(T sx, T sy, T sz)

neglect/tests/src/test_matrix.cpp

         m4[3] = vec4(4, 2, 3, 1);
         NUT_CHECK_EQUAL(determinant(m4), 60.0f);
     }
+
+    NUT_TESTCASE(matrix_inverse)
+    {
+        mat2 m1;
+        m1[0] = vec2(1, 1);
+        m1[1] = vec2(1, 0);
+        mat2 m1expected;
+        m1expected[0] = vec2(0, 1);
+        m1expected[1] = vec2(1, -1);
+        NUT_CHECK_EQUAL(inverse(m1), m1expected);
+
+        mat3 m2;
+        m2[0] = vec3(1, 1, 1);
+        m2[1] = vec3(1, 1, 0);
+        m2[2] = vec3(1, 0, 0);
+        mat3 m2expected;
+        m2expected[0] = vec3(0, 0, 1);
+        m2expected[1] = vec3(0, 1, -1);
+        m2expected[2] = vec3(1, -1, 0);
+        NUT_CHECK_EQUAL(inverse(m2), m2expected);
+    }
 }
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.