X-Git-Url: http://git.tdb.fi/?a=blobdiff_plain;f=source%2Flinal%2Fsquarematrix.h;h=5117bb3fa189ee4339d0ce52cdbb4d2ff141b83b;hb=e4b75401bd773201deb00eff672ee34794479671;hp=6cda86a5baa6b202ec00dba93acb0a152b03a985;hpb=839a88cd2b9a2f054323627c4e76cdcefc652c63;p=libs%2Fmath.git diff --git a/source/linal/squarematrix.h b/source/linal/squarematrix.h index 6cda86a..5117bb3 100644 --- a/source/linal/squarematrix.h +++ b/source/linal/squarematrix.h @@ -1,26 +1,103 @@ #ifndef MSP_LINAL_SQUAREMATRIX_H_ #define MSP_LINAL_SQUAREMATRIX_H_ +#include +#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() { } +}; + +/** +A mathematical matrix with S rows and columns. Some operations are provided +here that are only possible for square matrices. +*/ template class SquareMatrix: public Matrix { public: - SquareMatrix(); - SquareMatrix(const T *); + SquareMatrix() { } + SquareMatrix(const T *d): Matrix(d) { } template - SquareMatrix(const Matrix &); + SquareMatrix(const Matrix &m): Matrix(m) { } + static SquareMatrix identity(); SquareMatrix &operator*=(const SquareMatrix &); - void invert(); + SquareMatrix &invert(); }; +template +inline SquareMatrix SquareMatrix::identity() +{ + SquareMatrix m; + for(unsigned i=0; i +SquareMatrix &SquareMatrix::operator*=(const SquareMatrix &m) +{ + return *this = *this*m; +} + +template +SquareMatrix &SquareMatrix::invert() +{ + using std::abs; + + SquareMatrix r = identity(); + for(unsigned i=0; ielement(j, i))>abs(this->element(pivot, i))) + pivot = j; + + if(this->element(pivot, i)==T(0)) + throw not_invertible(); + + if(pivot!=i) + { + 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