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() { }
18 A mathematical matrix with S rows and columns. Some operations are provided
19 here that are only possible for square matrices.
21 template<typename T, unsigned S>
22 class SquareMatrix: public Matrix<T, S, S>
26 SquareMatrix(const T *d): Matrix<T, S, S>(d) { }
28 SquareMatrix(const Matrix<U, S, S> &m): Matrix<T, S, S>(m) { }
30 static SquareMatrix identity();
32 SquareMatrix &operator*=(const SquareMatrix &);
34 SquareMatrix &invert();
37 template<typename T, unsigned S>
38 inline SquareMatrix<T, S> SquareMatrix<T, S>::identity()
41 for(unsigned i=0; i<S; ++i)
46 template<typename T, unsigned S>
47 SquareMatrix<T, S> &SquareMatrix<T, S>::operator*=(const SquareMatrix<T, S> &m)
49 return *this = *this*m;
52 template<typename T, unsigned S>
53 SquareMatrix<T, S> &SquareMatrix<T, S>::invert()
55 SquareMatrix<T, S> r = identity();
56 for(unsigned i=0; i<S; ++i)
58 if(this->element(i, i)==T(0))
61 for(unsigned j=i+1; j<S; ++j)
62 if(abs(this->element(j, i))>abs(this->element(pivot, i)))
66 throw not_invertible();
68 this->exchange_rows(i, pivot);
69 r.exchange_rows(i, pivot);
72 for(unsigned j=i+1; j<S; ++j)
74 T a = -this->element(j, i)/this->element(i, i);
75 this->add_row(i, j, a);
79 T a = T(1)/this->element(i, i);
80 this->multiply_row(i, a);
84 for(unsigned i=S; i-->0; )
85 for(unsigned j=i; j-->0; )
86 r.add_row(i, j, -this->element(j, i));
91 template<typename T, unsigned S>
92 inline SquareMatrix<T, S> invert(const SquareMatrix<T, S> &m)
94 SquareMatrix<T, S> r = m;