X-Git-Url: http://git.tdb.fi/?a=blobdiff_plain;f=source%2Flinal%2Fsquarematrix.h;h=1cdc56726455f9ab2b97589b1b93bacbad702eac;hb=643aa7b2317f88463f66da11e595ebe0f6c9621d;hp=6cda86a5baa6b202ec00dba93acb0a152b03a985;hpb=839a88cd2b9a2f054323627c4e76cdcefc652c63;p=libs%2Fmath.git diff --git a/source/linal/squarematrix.h b/source/linal/squarematrix.h index 6cda86a..1cdc567 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(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