X-Git-Url: http://git.tdb.fi/?p=libs%2Fmath.git;a=blobdiff_plain;f=source%2Flinal%2Fsquarematrix.h;h=4cdc9e88f7288654d4dcbae9d2ec006517bfb734;hp=6cda86a5baa6b202ec00dba93acb0a152b03a985;hb=a3d9772a9fd483278b6248a811dc6f4ce968892b;hpb=79b2de777a3841bced5fd782a46166fc4d9d7489 diff --git a/source/linal/squarematrix.h b/source/linal/squarematrix.h index 6cda86a..4cdc9e8 100644 --- a/source/linal/squarematrix.h +++ b/source/linal/squarematrix.h @@ -1,26 +1,108 @@ #ifndef MSP_LINAL_SQUAREMATRIX_H_ #define MSP_LINAL_SQUAREMATRIX_H_ +#include #include "matrix.h" namespace Msp { namespace LinAl { +class not_invertible: public std::domain_error +{ +public: + not_invertible(): domain_error(std::string()) { } + virtual ~not_invertible() throw() { } +}; + template class SquareMatrix: public Matrix { public: - SquareMatrix(); + SquareMatrix() { } SquareMatrix(const T *); template SquareMatrix(const Matrix &); + static SquareMatrix identity(); SquareMatrix &operator*=(const SquareMatrix &); - void invert(); + SquareMatrix &invert(); }; +template +SquareMatrix::SquareMatrix(const T *d): + Matrix(d) +{ } + +template +template +SquareMatrix::SquareMatrix(const Matrix &m): + Matrix(m) +{ } + +template +inline SquareMatrix SquareMatrix::identity() +{ + SquareMatrix m; + for(unsigned i=0; i +SquareMatrix &SquareMatrix::operator*=(const SquareMatrix &m) +{ + Matrix::operator*=(m); + return *this; +} + +template +SquareMatrix &SquareMatrix::invert() +{ + SquareMatrix r = identity(); + for(unsigned i=0; ielement(i, i)==T(0)) + { + unsigned pivot = i; + for(unsigned j=i+1; jelement(j, i))>abs(this->element(pivot, i))) + pivot = j; + + if(pivot==i) + throw not_invertible(); + + this->exchange_rows(i, pivot); + r.exchange_rows(i, pivot); + } + + for(unsigned j=i+1; jelement(j, i)/this->element(i, i); + this->add_row(i, j, a); + r.add_row(i, j, a); + } + + T a = T(1)/this->element(i, i); + this->multiply_row(i, a); + r.multiply_row(i, a); + } + + for(unsigned i=S; i-->0; ) + for(unsigned j=i; j-->0; ) + r.add_row(i, j, -this->element(j, i)); + + return *this = r; +} + +template +inline SquareMatrix invert(const SquareMatrix &m) +{ + SquareMatrix r = m; + return r.invert(); +} + } // namespace LinAl } // namespace Msp