# Commits

committed 1c42e27

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

• Participants
• Parent commits c279d45
• Branches default

# File 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)

# File 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);
+    }
}