1 #ifndef MSP_LINAL_SQUAREMATRIX_H_
2 #define MSP_LINAL_SQUAREMATRIX_H_
10 class not_invertible: public std::domain_error
13 not_invertible(): domain_error(std::string()) { }
14 virtual ~not_invertible() throw() { }
17 template<typename T, unsigned S>
18 class SquareMatrix: public Matrix<T, S, S>
22 SquareMatrix(const T *d): Matrix<T, S, S>(d) { }
24 SquareMatrix(const Matrix<U, S, S> &m): Matrix<T, S, S>(m) { }
26 static SquareMatrix identity();
28 SquareMatrix &operator*=(const SquareMatrix &);
30 SquareMatrix &invert();
33 template<typename T, unsigned S>
34 inline SquareMatrix<T, S> SquareMatrix<T, S>::identity()
37 for(unsigned i=0; i<S; ++i)
42 template<typename T, unsigned S>
43 SquareMatrix<T, S> &SquareMatrix<T, S>::operator*=(const SquareMatrix<T, S> &m)
45 return *this = *this*m;
48 template<typename T, unsigned S>
49 SquareMatrix<T, S> &SquareMatrix<T, S>::invert()
51 SquareMatrix<T, S> r = identity();
52 for(unsigned i=0; i<S; ++i)
54 if(this->element(i, i)==T(0))
57 for(unsigned j=i+1; j<S; ++j)
58 if(abs(this->element(j, i))>abs(this->element(pivot, i)))
62 throw not_invertible();
64 this->exchange_rows(i, pivot);
65 r.exchange_rows(i, pivot);
68 for(unsigned j=i+1; j<S; ++j)
70 T a = -this->element(j, i)/this->element(i, i);
71 this->add_row(i, j, a);
75 T a = T(1)/this->element(i, i);
76 this->multiply_row(i, a);
80 for(unsigned i=S; i-->0; )
81 for(unsigned j=i; j-->0; )
82 r.add_row(i, j, -this->element(j, i));
87 template<typename T, unsigned S>
88 inline SquareMatrix<T, S> invert(const SquareMatrix<T, S> &m)
90 SquareMatrix<T, S> r = m;