]> git.tdb.fi Git - libs/math.git/blobdiff - source/linal/matrix.h
Remove SquareMatrix and instead use static_assert to check squareness
[libs/math.git] / source / linal / matrix.h
index bf21184092046c71bc1973ae1575deff51406fb7..2ad03447a9b10454f73ab982cf49f26dd25f983f 100644 (file)
@@ -3,6 +3,7 @@
 
 #include <algorithm>
 #include <ostream>
+#include "matrixops.h"
 #include "vector.h"
 
 namespace Msp {
@@ -26,6 +27,7 @@ public:
        template<typename U>
        Matrix(const Matrix<U, M, N> &);
 
+       static Matrix identity();
        static Matrix from_columns(const Vector<T, M> *);
        static Matrix from_rows(const Vector<T, N> *);
 
@@ -47,10 +49,13 @@ public:
        Matrix<T, P, Q> block(unsigned, unsigned) const;
 
        Matrix &operator*=(T);
+       Matrix &operator*=(const Matrix &);
        Matrix &operator/=(T);
        Matrix &operator+=(const Matrix &);
        Matrix &operator-=(const Matrix &);
 
+       Matrix &invert();
+
        Matrix &exchange_columns(unsigned, unsigned);
        Matrix &multiply_column(unsigned, T);
        Matrix &add_column(unsigned, unsigned, T);
@@ -77,6 +82,16 @@ inline Matrix<T, M, N>::Matrix(const Matrix<U, M, N> &other)
                        element(i, j) = other(i, j);
 }
 
+template<typename T, unsigned M, unsigned N>
+inline Matrix<T, M, N> Matrix<T, M, N>::identity()
+{
+       static_assert(M==N, "An identity matrix must be square");
+       Matrix<T, M, N> m;
+       for(unsigned i=0; i<M; ++i)
+               m(i, i) = T(1);
+       return m;
+}
+
 template<typename T, unsigned M, unsigned N>
 inline Matrix<T, M, N> Matrix<T, M, N>::from_columns(const Vector<T, M> *v)
 {
@@ -127,6 +142,13 @@ inline Matrix<T, M, N> &Matrix<T, M, N>::operator*=(T s)
        return *this;
 }
 
+template<typename T, unsigned M, unsigned N>
+inline Matrix<T, M, N> &Matrix<T, M, N>::operator*=(const Matrix<T, M, N> &m)
+{
+       static_assert(M==N, "Multiplication-assignment is only possible on square matrices");
+       return *this = *this*m;
+}
+
 template<typename T, unsigned M, unsigned N>
 inline Matrix<T, M, N> operator*(const Matrix<T, M, N> &m, T s)
 {
@@ -216,6 +238,23 @@ inline Matrix<T, M, N> operator-(const Matrix<T, M, N> &m1, const Matrix<T, M, N
        return r -= m2;
 }
 
+template<typename T, unsigned M, unsigned N>
+inline Matrix<T, M, N>& Matrix<T, M, N>::invert()
+{
+       static_assert(M==N, "Inversion is only possible on square matrices");
+       Matrix<T, M, N> r = identity();
+       gauss_jordan(*this, r);
+       return *this = r;
+}
+
+template<typename T, unsigned S>
+inline Matrix<T, S, S> invert(const Matrix<T, S, S> &m)
+{
+       Matrix<T, S, S> temp = m;
+       Matrix<T, S, S> r = Matrix<T, S, S>::identity();
+       return gauss_jordan(temp, r);
+}
+
 template<typename T, unsigned M, unsigned N>
 inline bool operator==(const Matrix<T, M, N> &a, const Matrix<T, M, N> &b)
 {