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 Matrix<T, S, S>::operator*=(m);
49 template<typename T, unsigned S>
50 SquareMatrix<T, S> &SquareMatrix<T, S>::invert()
52 SquareMatrix<T, S> r = identity();
53 for(unsigned i=0; i<S; ++i)
55 if(this->element(i, i)==T(0))
58 for(unsigned j=i+1; j<S; ++j)
59 if(abs(this->element(j, i))>abs(this->element(pivot, i)))
63 throw not_invertible();
65 this->exchange_rows(i, pivot);
66 r.exchange_rows(i, pivot);
69 for(unsigned j=i+1; j<S; ++j)
71 T a = -this->element(j, i)/this->element(i, i);
72 this->add_row(i, j, a);
76 T a = T(1)/this->element(i, i);
77 this->multiply_row(i, a);
81 for(unsigned i=S; i-->0; )
82 for(unsigned j=i; j-->0; )
83 r.add_row(i, j, -this->element(j, i));
88 template<typename T, unsigned S>
89 inline SquareMatrix<T, S> invert(const SquareMatrix<T, S> &m)
91 SquareMatrix<T, S> r = m;