added and fixed documentation for PIMath #101

Merged
peri4 merged 3 commits from math-doc into master 2022-08-03 08:49:08 +03:00
3 changed files with 910 additions and 630 deletions

View File

@@ -42,120 +42,142 @@ public:
PIPoint<Type> p0; PIPoint<Type> p0;
PIPoint<Type> p1; PIPoint<Type> p1;
//! //! \~russian
//! Пустой конструктор.
//! \details
//! При выполнении пустого конструктора координаты не изменяются.
//! Начало и конец совпадают.
PILine() {} PILine() {}
//! //! \~russian
//! Создает линию по двум принятым точкам \a PIPoint начала и конца.
PILine(const PIPoint<Type> & p0_, const PIPoint<Type> & p1_) { PILine(const PIPoint<Type> & p0_, const PIPoint<Type> & p1_) {
p0 = p0_; p0 = p0_;
p1 = p1_; p1 = p1_;
} }
//! //! \~russian
//! Создает линию по принятым координатам начала и конца.
PILine(Type x0, Type y0, Type x1, Type y1) { PILine(Type x0, Type y0, Type x1, Type y1) {
p0.set(x0, y0); p0.set(x0, y0);
p1.set(x1, y1); p1.set(x1, y1);
} }
//! //! \~russian
//! Задать новые координаты начала и конца по двум принятым точкам \a PIPoint.
PILine<Type> & set(const PIPoint<Type> & p0_, const PIPoint<Type> & p1_) { PILine<Type> & set(const PIPoint<Type> & p0_, const PIPoint<Type> & p1_) {
p0 = p0_; p0 = p0_;
p1 = p1_; p1 = p1_;
return *this; return *this;
} }
//! //! \~russian
//! Задать новые координаты начала и конца.
PILine<Type> & set(Type x0, Type y0, Type x1, Type y1) { PILine<Type> & set(Type x0, Type y0, Type x1, Type y1) {
p0.set(x0, y0); p0.set(x0, y0);
p1.set(x1, y1); p1.set(x1, y1);
return *this; return *this;
} }
//! //! \~russian
//! Проверить на совпадение координат начала и конца.
bool isEmpty() const { bool isEmpty() const {
return (p0 == p1); return (p0 == p1);
} }
//! //! \~russian
//! Вычислить ширину прямоугольника, диагональю которого является данный отрезок.
Type width() const {return piAbs<Type>(p1.x - p0.x);} Type width() const {return piAbs<Type>(p1.x - p0.x);}
//! //! \~russian
//! Вычислить высоту прямоугольника, диагональю которого является данный отрезок.
Type height() const {return piAbs<Type>(p1.y - p0.y);} Type height() const {return piAbs<Type>(p1.y - p0.y);}
//! //! \~russian
//! Сдвинуть линию на \a x, \a y.
PILine<Type> & translate(Type x, Type y) { PILine<Type> & translate(Type x, Type y) {
p0.translate(x, y); p0.translate(x, y);
p1.translate(x, y); p1.translate(x, y);
return *this; return *this;
} }
//! //! \~russian
//! Сдвинуть линию на значение координат точки \a PIPoint.
PILine<Type> & translate(const PIPoint<Type> & p) { PILine<Type> & translate(const PIPoint<Type> & p) {
p0.translate(p); p0.translate(p);
p1.translate(p); p1.translate(p);
return *this; return *this;
} }
//! //! Создать копию отрезка и сдвинуть её на `x` и `y`.
PILine<Type> translated(Type x, Type y) const { PILine<Type> translated(Type x, Type y) const {
PILine<Type> l(*this); PILine<Type> l(*this);
l.translate(x, y); l.translate(x, y);
return l; return l;
} }
//! //! \~russian
//! Создать копию отрезка и сдвинуть её на значение координат точки \a PIPoint.
PILine<Type> translated(const PIPoint<Type> & p) const { PILine<Type> translated(const PIPoint<Type> & p) const {
PILine<Type> l(*this); PILine<Type> l(*this);
l.translate(p); l.translate(p);
return l; return l;
} }
//! //! \~russian
//! Сдвинуть линию на \a x, \a y.
//! \details Является копией метода \a translate().
PILine<Type> & move(Type x, Type y) {return translate(x, y);} PILine<Type> & move(Type x, Type y) {return translate(x, y);}
//! //! \~russian
//! Сдвинуть линию на значение координат точки \a PIPoint.
//! \details Является копией метода \a translate().
PILine<Type> & move(const PIPoint<Type> & p) {return translate(p);} PILine<Type> & move(const PIPoint<Type> & p) {return translate(p);}
//! //! \~russian
//! Создать копию отрезка и сдвинуть её на \a x, \a y.
//! \details Является копией метода \a translated().
PILine<Type> moved(Type x, Type y) const { PILine<Type> moved(Type x, Type y) const {
PILine<Type> l(*this); PILine<Type> l(*this);
l.translate(x, y); l.translate(x, y);
return l; return l;
} }
//! //! \~russian
//! Создать копию отрезка и сдвинуть её на значение координат точки \a PIPoint.
//! \details Является копией метода \a translated().
PILine<Type> moved(const PIPoint<Type> & p) const { PILine<Type> moved(const PIPoint<Type> & p) const {
PILine<Type> l(*this); PILine<Type> l(*this);
l.translate(p); l.translate(p);
return l; return l;
} }
//! //! \~russian Сдвинуть линию по двум координатам на значение \a x.
void operator +=(Type x) {translate(x, x);} void operator +=(Type x) {translate(x, x);}
//! //! \~russian Сдвинуть линию по двум координатам на величину координат точки \a PIPoint.
void operator +=(const PIPoint<Type> & p) {translate(p);} void operator +=(const PIPoint<Type> & p) {translate(p);}
//! //! \~russian Сдвинуть линию по двум координатам на значение \a x.
void operator -=(Type x) {translate(-x, -x);} void operator -=(Type x) {translate(-x, -x);}
//! //! \~russian Сдвинуть линию по двум координатам на величину координат точки \a PIPoint.
void operator -=(const PIPoint<Type> & p) {translate(-p);} void operator -=(const PIPoint<Type> & p) {translate(-p);}
//! //! \~russian Сдвинуть линию по двум координатам на величину координат точки \a PIPoint.
PILine<Type> operator +(const PIPoint<Type> & p) {return translated(p);} PILine<Type> operator +(const PIPoint<Type> & p) {return translated(p);}
//! //! \~russian Сдвинуть линию по двум координатам на величину координат точки \a PIPoint.
PILine<Type> operator -(const PIPoint<Type> & p) {return translated(-p);} PILine<Type> operator -(const PIPoint<Type> & p) {return translated(-p);}
//! //! \~russian Проверить равенство координат двух отрезков.
bool operator ==(const PILine<Type> & r) const {return (p0 == r.p0 && p1 == r.p1);} bool operator ==(const PILine<Type> & r) const {return (p0 == r.p0 && p1 == r.p1);}
//! //! \~russian Проверить неравенство координат двух отрезков.
bool operator !=(const PILine<Type> & r) const {return (p1 != r.p1 || p1 != r.p1);} bool operator !=(const PILine<Type> & r) const {return (p1 != r.p1 || p1 != r.p1);}
}; };
//! \~russian Перегруженный оператор для вывода координат в \a PICout.
template<typename Type> template<typename Type>
PICout operator <<(PICout & s, const PILine<Type> & v) { PICout operator <<(PICout & s, const PILine<Type> & v) {
s.setControl(0, true); s.setControl(0, true);

View File

@@ -1,9 +1,9 @@
/*! \file pimathmatrix.h //! \file pimathmatrix.h
* \ingroup Math //! \ingroup Math
* \~\brief //! \~\brief
* \~english Math matrix //! \~english Math matrix
* \~russian Математическая матрица //! \~russian Математическая матрица
*/
/* /*
PIP - Platform Independent Primitives PIP - Platform Independent Primitives
PIMathMatrix PIMathMatrix
@@ -38,11 +38,18 @@
#pragma pack(push, 1) #pragma pack(push, 1)
//! \brief A class that works with square matrix operations, the input data of which are columns, rows and the data type of the matrix //! \~english
//! @tparam Rows rows number of matrix //! \brief A class that works with square matrix operations, the input data of which are columns, rows and the data type of the matrix.
//! @tparam Сols columns number of matrix //! \tparam `Rows` rows number of matrix.
//! @tparam Type is the data type of the matrix. There are can be basic C++ language data and different classes where the arithmetic operators(=, +=, -=, *=, /=, ==, !=, +, -, *, /) //! \tparam `Сols` columns number of matrix.
//! \tparam `Type` is the data type of the matrix. There are can be basic C++ language data and different classes where the arithmetic operators(=, +=, -=, *=, /=, ==, !=, +, -, *, /)
//! of the C++ language are implemented //! of the C++ language are implemented
//! \~russian
//! \brief Класс, работающий с операциями над квадратными матрицами, входными данными которого являются столбцы, строки и матричный типа данных.
//! \tparam `Rows` количество строк матрицы.
//! \tparam `Сols` количество столбцов матрицы.
//! \tparam `Type`типа данных матрицы. Здесь можеть быть базовый тип данных C++ или различные классы,
//! где реализованы арифметические операторы(=, +=, -=, *=, /=, ==, !=, +, -, *, /) языка C++.
template<uint Rows, uint Cols = Rows, typename Type = double> template<uint Rows, uint Cols = Rows, typename Type = double>
class PIP_EXPORT PIMathMatrixT { class PIP_EXPORT PIMathMatrixT {
typedef PIMathMatrixT<Rows, Cols, Type> _CMatrix; typedef PIMathMatrixT<Rows, Cols, Type> _CMatrix;
@@ -53,337 +60,410 @@ class PIP_EXPORT PIMathMatrixT {
static_assert(Rows > 0, "Row count must be > 0"); static_assert(Rows > 0, "Row count must be > 0");
static_assert(Cols > 0, "Column count must be > 0"); static_assert(Cols > 0, "Column count must be > 0");
public: public:
/** //! \~english
* \brief Constructs PIMathMatrixT that is filled by \a new_value //! \brief Constructs \a PIMathMatrixT that is filled by \a new_value.
*/ //! \~russian
//! \brief Создает \a PIMathMatrixT и заполняет её из \a new_value.
PIMathMatrixT(const Type &new_value = Type()) {PIMM_FOR m[r][c] = new_value;} PIMathMatrixT(const Type &new_value = Type()) {PIMM_FOR m[r][c] = new_value;}
/** //! \~english
* \brief Contructs PIMathMatrixT from PIVector //! \brief Contructs \a PIMathMatrixT from \a PIVector.
*/ //! \~russian
//! \brief Создает \a PIMathMatrixT и заполняет её из \a PIVector.
PIMathMatrixT(const PIVector<Type> &val) { PIMathMatrixT(const PIVector<Type> &val) {
assert(Rows*Cols == val.size()); assert(Rows*Cols == val.size());
int i = 0; int i = 0;
PIMM_FOR m[r][c] = val[i++]; PIMM_FOR m[r][c] = val[i++];
} }
/** //! \~english
* \brief Contructs PIMathMatrixT from C++11 initializer list //! \brief Contructs \a PIMathMatrixT from [C++11 initializer list](https://en.cppreference.com/w/cpp/utility/initializer_list).
*/ //! \~russian
//! \brief Создает \a PIMathMatrixT и заполняет её из [списка инициализации C++11](https://ru.cppreference.com/w/cpp/utility/initializer_list).
PIMathMatrixT(std::initializer_list<Type> init_list) { PIMathMatrixT(std::initializer_list<Type> init_list) {
assert(Rows*Cols == init_list.size()); assert(Rows*Cols == init_list.size());
int i = 0; int i = 0;
PIMM_FOR m[r][c] = init_list.begin()[i++]; PIMM_FOR m[r][c] = init_list.begin()[i++];
} }
/** //! \~english
* \brief Сreates a matrix whose main diagonal is filled with ones and the remaining elements are zeros //! \brief Сreates a matrix whose main diagonal is filled with ones and the remaining elements are zeros.
* //! \return identity matrix of type \a PIMathMatrixT.
* @return identity matrix of type PIMathMatrixT //! \~russian
*/ //! \brief Создает матрицу, главная диагональ которой заполнена единицами, а остальные элементы — нулями.
static _CMatrix identity() { //! \return единичная матрица типа \a PIMathMatrixT.
_CMatrix tm = _CMatrix(); static PIMathMatrixT<Rows, Cols, Type> identity() {
PIMathMatrixT<Rows, Cols, Type> tm = PIMathMatrixT<Rows, Cols, Type>();
PIMM_FOR tm.m[r][c] = (c == r ? Type(1) : Type(0)); PIMM_FOR tm.m[r][c] = (c == r ? Type(1) : Type(0));
return tm; return tm;
} }
/** //! \~english
* \brief Method which returns number of columns in matrix //! \brief Method which returns number of columns in matrix.
* //! \return type \a uint shows number of columns.
* @return type uint shows number of columns //! \~russian
*/ //! \brief Метод возвращающий количество столбцов в матрице.
//! \return \a uint количество столбцов.
constexpr uint cols() const {return Cols;} constexpr uint cols() const {return Cols;}
/** //! \~english
* \brief Method which returns number of rows in matrix //! \brief Method which returns number of rows in matrix.
* //! \return type uint shows number of rows.
* @return type uint shows number of rows //! \~russian
*/ //! \brief Метод возвращающий количество строк в матрице.
//! \return \a uint количество строк.
constexpr uint rows() const {return Rows;} constexpr uint rows() const {return Rows;}
/** //! \~english
* \brief Method which returns the selected column in PIMathVectorT format. //! \brief Method which returns the selected column in PIMathVectorT format.
* If you enter an index out of the border of the matrix there will be "undefined behavior" //! \details If you enter an index out of the border of the matrix there will be "undefined behavior".
* //! \param index is the number of the selected column.
* @param index is the number of the selected column //! \return column in PIMathVectorT format.
* @return column in PIMathVectorT format //! \~russian
*/ //! \brief Метод возвращающий выбранную строку в формате \a PIMathVectorT.
_CMCol col(uint index) { //! \details Если вы введете индекс вне границ матрицы, то поведение не определено ("undefined behavior").
_CMCol tv; //! \param index номер выбранного столбца.
//! \return столбец в формате \a PIMathVectorT.
PIMathVectorT<Rows, Type> col(uint index) {
PIMathVectorT<Rows, Type> tv;
PIMM_FOR_R tv[i] = m[i][index]; PIMM_FOR_R tv[i] = m[i][index];
return tv; return tv;
} }
/** //! \brief Method which returns the selected row in PIMathVectorT format.
* \brief Method which returns the selected row in PIMathVectorT format //! \details If you enter an index out of the border of the matrix there will be "undefined behavior".
* If you enter an index out of the border of the matrix there will be "undefined behavior" //! \param index is the number of the selected row.
* //! \return row in PIMathVectorT format.
* @param index is the number of the selected row //! \~russian
* @return row in PIMathVectorT format //! \brief Метод возвращающий выбранный столбец в формате \a PIMathVectorT.
*/ //! \details Если вы введете индекс вне границ матрицы, то поведение не определено ("undefined behavior").
_CMRow row(uint index) { //! \param index номер выбранной строки.
_CMRow tv; //! \return строка в формате \a PIMathVectorT.
PIMathVectorT<Cols, Type> row(uint index) {
PIMathVectorT<Cols, Type> tv;
PIMM_FOR_C tv[i] = m[index][i]; PIMM_FOR_C tv[i] = m[index][i];
return tv; return tv;
} }
/** //! \~english
* \brief Set the selected column in matrix. //! \brief Set the selected column in matrix.
* If you enter an index out of the border of the matrix there will be "undefined behavior" //! \details If you enter an index out of the border of the matrix there will be "undefined behavior".
* //! \param index is the number of the selected column.
* @param index is the number of the selected column //! \param v is a vector of the type \a PIMathVectorT<Rows, Type> that needs to fill the column.
* @param v is a vector of the type _CMCol that needs to fill the column //! \return matrix type \a PIMathMatrixT<Rows, Cols, Type>.
* @return matrix type _CMatrix //! \~russian
*/ //! \brief Определить выбранный столбец матрицы.
_CMatrix &setCol(uint index, const _CMCol &v) { //! \details Если вы введете индекс вне границ матрицы, то поведение не определено ("undefined behavior").
//! \param index номер выбранного столбца.
//! \param v вектор типа \a PIMathVectorT<Rows, Type>, которым необходимо заполнить столбец.
//! \return матрица типа \a PIMathMatrixT<Rows, Cols, Type>.
PIMathMatrixT<Rows, Cols, Type> &setCol(uint index, const PIMathVectorT<Rows, Type> &v) {
PIMM_FOR_R m[i][index] = v[i]; PIMM_FOR_R m[i][index] = v[i];
return *this; return *this;
} }
/** //! \~english
* \brief Set the selected row in matrix //! \brief Set the selected row in matrix.
* If you enter an index out of the border of the matrix there will be "undefined behavior" //! \details If you enter an index out of the border of the matrix there will be "undefined behavior".
* //! \param index is the number of the selected row.
* @param index is the number of the selected row //! \param v is a vector of the type PIMathVectorT<Cols, Type> that needs to fill the row.
* @param v is a vector of the type _CMCol that needs to fill the row //! \return matrix type PIMathMatrixT<Rows, Cols, Type>
* @return matrix type _CMatrix //! \~russian
*/ //! \brief Определить выбранную строку матрицы.
_CMatrix &setRow(uint index, const _CMRow &v) { //! \details Если вы введете индекс вне границ матрицы, то поведение не определено ("undefined behavior").
//! \param index номер выбранной строки.
//! \param v вектор типа \a PIMathVectorT<Cols, Type>, которым необходимо заполнить строку.
//! \return матрица типа \a PIMathMatrixT<Rows, Cols, Type>.
PIMathMatrixT<Rows, Cols, Type> &setRow(uint index, const PIMathVectorT<Cols, Type> &v) {
PIMM_FOR_C m[index][i] = v[i]; PIMM_FOR_C m[index][i] = v[i];
return *this; return *this;
} }
/** //! \~english
* \brief Method which changes selected rows in a matrix. //! \brief Method which swaps the selected rows in a matrix.
* If you enter an index out of the border of the matrix there will be "undefined behavior" //! \details If you enter an index out of the border of the matrix there will be "undefined behavior"
* //! \param rf is the number of the first selected row
* @param rf is the number of the first selected row //! \param rs is the number of the second selected row
* @param rs is the number of the second selected row //! \return matrix type \a PIMathMatrixT<Rows, Cols, Type>
* @return matrix type _CMatrix //! \~russian
*/ //! \brief Метод, меняющий местами выбранные строки в матрице.
_CMatrix &swapRows(uint rf, uint rs) { //! \details Если вы введете индекс вне границ матрицы, то поведение не определено ("undefined behavior").
//! \param rf номер первой выбранной строки.
//! \param rs номер второй выбранной строки.
//! \return матрица типа \a PIMathMatrixT<Rows, Cols, Type>.
PIMathMatrixT<Rows, Cols, Type> &swapRows(uint rf, uint rs) {
PIMM_FOR_C piSwap<Type>(m[rf][i], m[rs][i]); PIMM_FOR_C piSwap<Type>(m[rf][i], m[rs][i]);
return *this; return *this;
} }
/** //! \~english
* \brief Method which changes selected columns in a matrix. //! \brief Method which swaps the selected columns in a matrix.
* If you enter an index out of the border of the matrix there will be "undefined behavior" //! \details If you enter an index out of the border of the matrix there will be "undefined behavior"
* //! \param cf is the number of the first selected column
* @param cf is the number of the first selected column //! \param cs is the number of the second selected column
* @param cs is the number of the second selected column //! \return matrix type \a PIMathMatrixT<Rows, Cols, Type>
* @return matrix type _CMatrix //! \~russian
*/ //! \brief Метод, меняющий местами выбранные столбцы в матрице.
_CMatrix &swapCols(uint cf, uint cs) { //! \details Если вы введете индекс вне границ матрицы, то поведение не определено ("undefined behavior").
//! \param rf номер первого выбранного столбца.
//! \param rs номер второго выбранного столбца.
//! \return матрица типа \a PIMathMatrixT<Rows, Cols, Type>.
PIMathMatrixT<Rows, Cols, Type> &swapCols(uint cf, uint cs) {
PIMM_FOR_R piSwap<Type>(m[i][cf], m[i][cs]); PIMM_FOR_R piSwap<Type>(m[i][cf], m[i][cs]);
return *this; return *this;
} }
/** //! \~english
* \brief Method which fills the matrix with selected value //! \brief Method which fills the matrix with selected value.
* //! \param v is a parameter the type and value of which is selected and later filled into the matrix.
* @param v is a parameter the type and value of which is selected and later filled into the matrix //! \return filled matrix type \a PIMathMatrixT<Rows, Cols, Type>.
* @return filled matrix type _CMatrix //! \~russian
*/ //! \brief Метод, заполняющий матрицу выбранным значением.
_CMatrix &fill(const Type &v) { //! \param v параметр тип и значения, которого выбираются и заносятся в матрицу.
//! \return заполненная матрица типа \a PIMathMatrixT<Rows, Cols, Type>.
PIMathMatrixT<Rows, Cols, Type> &fill(const Type &v) {
PIMM_FOR m[r][c] = v; PIMM_FOR m[r][c] = v;
return *this; return *this;
} }
/** //! \~english
* \brief Method which checks if matrix is square //! \brief Method which checks if matrix is square.
* //! \return true if matrix is square, else false.
* @return true if matrix is square, else false //! \~russian
*/ //! \brief Метод, проверяющий является ли матрицей квадратной.
//! \return true если матрица квадратная, иначе false.
constexpr bool isSquare() const { return Rows == Cols; } constexpr bool isSquare() const { return Rows == Cols; }
/** //! \~english
* \brief Method which checks if main diagonal of matrix consists of ones and another elements are zeros //! \brief Method which checks if main diagonal of matrix consists of ones and another elements are zeros.
* //! \return true if matrix is identitied, else false.
* @return true if matrix is identitied, else false //! \~russian
*/ //! \brief Метод, проверяющий содержит ли главная диагональ единицы и все остальные поля нули.
//! \return true если матрица единичная, иначе false.
bool isIdentity() const { bool isIdentity() const {
PIMM_FOR if ((c == r) ? m[r][c] != Type(1) : m[r][c] != Type(0)) return false; PIMM_FOR if ((c == r) ? m[r][c] != Type(1) : m[r][c] != Type(0)) return false;
return true; return true;
} }
/** //! \~english
* \brief Method which checks if every elements of matrix are zeros //! \brief Method which checks if every elements of matrix are zeros.
* //! \return true if matrix is null, else false.
* @return true if matrix is null, else false //! \~russian
*/ //! \brief Метод, являются ли все элементы матрицы нулями.
//! \return true если матрица нулевая, иначе false.
bool isNull() const { bool isNull() const {
PIMM_FOR if (m[r][c] != Type(0)) return false; PIMM_FOR if (m[r][c] != Type(0)) return false;
return true; return true;
} }
/** //! \~english
* \brief Read-only access to element by \a row and \a col. //! \brief Read-only access to element by `row` number and `col` number.
* If you enter an index out of the border of the matrix there will be "undefined behavior" //! \details If you enter an index out of the border of the matrix there will be "undefined behavior".
* //! \param row matrix row number.
* @param row of matrix //! \param col matrix column number.
* @param col of matrix //! \return copy of element of matrix.
* @return copy of element of matrix //! \~russian
*/ //! \brief Доступ только для чтения к элементу по номеру \a строки `row` и номеру \a столбца `col`.
//! \details Если вы введете индекс вне границ матрицы, то поведение не определено ("undefined behavior").
//! \param row номер строки матрицы.
//! \param col номер столбца матрицы.
//! \return копия элемента матрицы.
Type at(uint row, uint col) const { return m[row][col]; } Type at(uint row, uint col) const { return m[row][col]; }
/** //! \~english
* \brief Full access to element by \a row and \a col. //! \brief Full access to element by `row` number and `col` number.
* If you enter an index out of the border of the matrix there will be "undefined behavior" //! \details If you enter an index out of the border of the matrix there will be "undefined behavior"
* //! \param row matrix row number.
* @param row of matrix //! \param col matrix column number.
* @param col of matrix //! \return element of matrix
* @return element of matrix //! \~russian
*/ //! \brief Полный доступ к элементу по номеру \a строки `row` и номеру \a столбца `col`.
//! \details Если вы введете индекс вне границ матрицы, то поведение не определено ("undefined behavior").
//! \param row номер строки матрицы.
//! \param col номер столбца матрицы.
//! \return элемент матрицы.
inline Type & element(uint row, uint col) {return m[row][col];} inline Type & element(uint row, uint col) {return m[row][col];}
/** //! \~english
* \brief Read-only access to element by \a row and \a col. //! \brief Read-only access to element by `row` number and `col` number.
* If you enter an index out of the border of the matrix there will be "undefined behavior" //! \details If you enter an index out of the border of the matrix there will be "undefined behavior".
* //! \param row matrix row number.
* @param row of matrix //! \param col matrix column number.
* @param col of matrix //! \return copy of element of matrix.
* @return element of matrix //! \~russian
*/ //! \brief Доступ только для чтения к элементу по номеру \a строки `row` и номеру \a столбца `col`.
//! \details Если вы введете индекс вне границ матрицы, то поведение не определено ("undefined behavior").
//! \param row номер строки матрицы.
//! \param col номер столбца матрицы.
//! \return копия элемента матрицы.
inline const Type & element(uint row, uint col) const {return m[row][col];} inline const Type & element(uint row, uint col) const {return m[row][col];}
/** //! \~english
* \brief Full access to the matrix row pointer. If you enter an index out of the border of the matrix there will be "undefined behavior" //! \brief Full access to the matrix row pointer.
* //! \details If you enter an index out of the border of the matrix there will be "undefined behavior".
* @param row of matrix //! \param row matrix row number.
* @return matrix row pointer //! \return matrix row pointer
*/ //! \~russian
//! \brief Полный доступ к указателю на строку матрицы.
//! \details Если вы введете индекс вне границ матрицы, то поведение не определено ("undefined behavior").
//! \param row номер строки матрицы.
//! \return указатель на строку матрицы.
Type *operator[](uint row) { return m[row]; } Type *operator[](uint row) { return m[row]; }
/** //! \~english
* \brief Read-only access to the matrix row pointer. If you enter an index out of the border of the matrix there will be "undefined behavior" //! \brief Read-only access to the matrix row pointer.
* //! \details If you enter an index out of the border of the matrix there will be "undefined behavior".
* @param row of matrix //! \param row matrix row number.
* @return matrix row pointer //! \return matrix row pointer
*/ //! \~russian
//! \brief Доступ только для чтения к указателю на строку матрицы.
//! \details Если вы введете индекс вне границ матрицы, то поведение не определено ("undefined behavior").
//! \param row номер строки матрицы.
//! \return указатель на строку матрицы.
const Type *operator[](uint row) const {return m[row];} const Type *operator[](uint row) const {return m[row];}
/** //! \~english
* \brief Matrix compare //! \brief Matrix compare.
* //! \param sm matrix for compare.
* @param sm matrix for compare //! \return if matrices are equal true, else false.
* @return if matrices are equal true, else false //! \~russian
*/ //! \brief Сравнение матриц.
bool operator==(const _CMatrix &sm) const { //! \param sm матрица для сравнения.
//! \return если матрицы равны true, иначе false.
bool operator==(const PIMathMatrixT<Rows, Cols, Type> &sm) const {
PIMM_FOR if (m[r][c] != sm.m[r][c]) return false; PIMM_FOR if (m[r][c] != sm.m[r][c]) return false;
return true; return true;
} }
/** //! \~english
* \brief Matrix negative compare //! \brief Matrix negative compare.
* //! \param sm matrix for compare.
* @param sm matrix for compare //! \return if matrices are not equal true, else false.
* @return if matrices are not equal true, else false //! \~russian
*/ //! \brief Отрицательное сравнение матриц.
bool operator!=(const _CMatrix &sm) const { return !(*this == sm); } //! \param sm матрица для сравнения.
//! \return если матрицы не равны true, иначе false.
bool operator!=(const PIMathMatrixT<Rows, Cols, Type> &sm) const { return !(*this == sm); }
/** //! \~english
* \brief Addition assignment with matrix "sm" //! \brief Addition assignment with matrix `sm`.
* //! \param sm matrix for the addition assigment.
* @param sm matrix for the addition assigment //! \~russian
*/ //! \brief Сложение с присваиванием с матрицей `sm`.
void operator+=(const _CMatrix &sm) {PIMM_FOR m[r][c] += sm.m[r][c];} //! \param sm матрица для сложения с присваиванием.
void operator+=(const PIMathMatrixT<Rows, Cols, Type> &sm) {PIMM_FOR m[r][c] += sm.m[r][c];}
/** //! \~english
* \brief Subtraction assignment with matrix "sm" //! \brief Subtraction assignment with matrix `sm`.
* //! \param sm matrix for the subtraction assigment.
* @param sm matrix for the subtraction assigment //! \~russian
*/ //! \brief Вычитание с присваиванием с матрицей `sm`.
void operator-=(const _CMatrix &sm) {PIMM_FOR m[r][c] -= sm.m[r][c];} //! \param sm матрица для вычитания с присваиванием.
void operator-=(const PIMathMatrixT<Rows, Cols, Type> &sm) {PIMM_FOR m[r][c] -= sm.m[r][c];}
/** //! \~english
* \brief Multiplication assignment with value "v" //! \brief Multiplication assignment with value `v`.
* //! \param v value for the multiplication assigment.
* @param v value for the multiplication assigment //! \~russian
*/ //! \brief Умножение с присваиванием с матрицей `v`.
//! \param sm матрица для умножения с присваиванием.
void operator*=(const Type &v) { void operator*=(const Type &v) {
PIMM_FOR m[r][c] *= v; PIMM_FOR m[r][c] *= v;
} }
/** //! \~english
* \brief Division assignment with value "v" //! \brief Division assignment with value `v`.
* //! \param v value for the division assigment.
* @param v value for the division assigment //! \~russian
*/ //! \brief Деление с присваиванием с матрицей `v`.
//! \param sm матрица для деления с присваиванием.
void operator/=(const Type &v) { void operator/=(const Type &v) {
assert(piAbs<Type>(v) > PIMATHVECTOR_ZERO_CMP); assert(piAbs<Type>(v) > PIMATHVECTOR_ZERO_CMP);
PIMM_FOR m[r][c] /= v; PIMM_FOR m[r][c] /= v;
} }
/** //! \~english
* \brief Matrix substraction //! \brief Negation operation
* //! \return copy of the negative matrix
* @return the result of matrix substraction //! \~russian
*/ //! \brief Операция отрицания
_CMatrix operator-() const { //! \return копия отрицательной матрицы
_CMatrix tm; PIMathMatrixT<Rows, Cols, Type> operator-() const {
PIMathMatrixT<Rows, Cols, Type> tm;
PIMM_FOR tm.m[r][c] = -m[r][c]; PIMM_FOR tm.m[r][c] = -m[r][c];
return tm; return tm;
} }
/** //! \~english
* \brief Matrix addition //! \brief Matrix addition.
* //! \param sm is matrix term.
* @param sm is matrix term //! \return the result of matrix addition.
* @return the result of matrix addition //! \~russian
*/ //! \brief Матричное сложение.
_CMatrix operator+(const _CMatrix &sm) const { //! \param sm матричное слагаемое.
_CMatrix tm = _CMatrix(*this); //! \return результат матричного сложения.
PIMathMatrixT<Rows, Cols, Type> operator+(const PIMathMatrixT<Rows, Cols, Type> &sm) const {
PIMathMatrixT<Rows, Cols, Type> tm = PIMathMatrixT<Rows, Cols, Type>(*this);
PIMM_FOR tm.m[r][c] += sm.m[r][c]; PIMM_FOR tm.m[r][c] += sm.m[r][c];
return tm; return tm;
} }
/** //! \~english
* \brief Matrix substraction //! \brief Matrix substraction.
* //! \param sm is matrix subtrahend.
* @param sm is matrix subtractor //! \return the result of matrix substraction.
* @return the result of matrix substraction //! \~russian
*/ //! \brief Матричная разность.
_CMatrix operator-(const _CMatrix &sm) const { //! \param sm матричное вычитаемое.
_CMatrix tm = _CMatrix(*this); //! \return результат матричной разности.
PIMathMatrixT<Rows, Cols, Type> operator-(const PIMathMatrixT<Rows, Cols, Type> &sm) const {
PIMathMatrixT<Rows, Cols, Type> tm = PIMathMatrixT<Rows, Cols, Type>(*this);
PIMM_FOR tm.m[r][c] -= sm.m[r][c]; PIMM_FOR tm.m[r][c] -= sm.m[r][c];
return tm; return tm;
} }
/** //! \~english
* \brief Matrix multiplication //! \brief Matrix multiplication by a constant.
* //! \param v is value factor.
* @param v is value factor //! \return the result of matrix multiplication.
* @return the result of matrix multiplication //! \~russian
*/ //! \brief Умножение матрицы на константу.
_CMatrix operator*(const Type &v) const { //! \param v множитель.
_CMatrix tm = _CMatrix(*this); //! \return результат произведения.
PIMathMatrixT<Rows, Cols, Type> operator*(const Type &v) const {
PIMathMatrixT<Rows, Cols, Type> tm = PIMathMatrixT<Rows, Cols, Type>(*this);
PIMM_FOR tm.m[r][c] *= v; PIMM_FOR tm.m[r][c] *= v;
return tm; return tm;
} }
/** //! \~english
* \brief Matrix division //! \brief Division a matrix by a constant.
* //! \param v is value divider.
* @param v is value divider //! \return the result of matrix division.
* @return the result of matrix division //! \~russian
*/ //! \brief Деление матрицы на константу.
_CMatrix operator/(const Type &v) const { //! \param v делитель.
//! \return результат деления.
PIMathMatrixT<Rows, Cols, Type> operator/(const Type &v) const {
assert(piAbs<Type>(v) > PIMATHVECTOR_ZERO_CMP); assert(piAbs<Type>(v) > PIMATHVECTOR_ZERO_CMP);
_CMatrix tm = _CMatrix(*this); PIMathMatrixT<Rows, Cols, Type> tm = PIMathMatrixT<Rows, Cols, Type>(*this);
PIMM_FOR tm.m[r][c] /= v; PIMM_FOR tm.m[r][c] /= v;
return tm; return tm;
} }
/** //! \~english
* \brief Determinant of the matrix is calculated. Works only with square matrix, nonzero matrices and invertible matrix //! \brief Calculate Determinant of the matrix.
* //! \details Works only with square matrix, nonzero matrices and invertible matrix.
* @param ok is a parameter with which we can find out if the method worked correctly //! \param ok is a parameter with which we can find out if the method worked correctly.
* @return matrix determinant //! \return matrix determinant.
*/ //! \~russian
//! \brief Вычислить определитель матрицы.
//! \details Работает только с квадратными, ненулевыми и обратимыми матрицами.
//! \param ok это параметр, с помощью которого мы можем узнать, правильно ли сработал метод.
//! \return опеределитель матрицы.
Type determinant(bool *ok = 0) const { Type determinant(bool *ok = 0) const {
_CMatrix m(*this); PIMathMatrixT<Rows, Cols, Type> m(*this);
bool k; bool k;
Type ret = Type(0); Type ret = Type(0);
m.toUpperTriangular(&k); m.toUpperTriangular(&k);
@@ -394,11 +474,14 @@ public:
return ret; return ret;
} }
/** //! \~english
* \brief Trace of the matrix is calculated. Works only with square matrix, nonzero matrices and invertible matrix //! \brief Calculate the trace of a matrix.
* //! \details Works only with square matrix.
* @return matrix trace //! \return matrix trace.
*/ //! \~russian
//! \brief Вычислить след матрицы.
//! \details Работает только с квадратными матрицами.
//! \return след матрицы.
Type trace() const { Type trace() const {
static_assert(Rows == Cols, "Works only with square matrix"); static_assert(Rows == Cols, "Works only with square matrix");
Type ret = Type(0); Type ret = Type(0);
@@ -408,15 +491,19 @@ public:
return ret; return ret;
} }
/** //! \~english
* \brief Transforming matrix to upper triangular. Works only with square matrix, nonzero matrices and invertible matrix //! \brief Transforming matrix to upper triangular.
* //! \details Works only with square matrix, nonzero matrices and invertible matrix.
* @param ok is a parameter with which we can find out if the method worked correctly //! \param ok is a parameter with which we can find out if the method worked correctly.
* @return copy of transformed upper triangular matrix //! \return a transformed upper triangular matrix.
*/ //! \~russian
_CMatrix &toUpperTriangular(bool *ok = 0) { //! \brief Преобразование матрицы в верхнетреугольную.
//! \details Работает только с квадратными, ненулевыми и обратимыми матрицами.
//! \param ok это параметр, с помощью которого мы можем узнать, правильно ли сработал метод.
//! \return преобразованная верхнетреугольная матрицы.
PIMathMatrixT<Rows, Cols, Type> &toUpperTriangular(bool *ok = 0) {
static_assert(Rows == Cols, "Works only with square matrix"); static_assert(Rows == Cols, "Works only with square matrix");
_CMatrix smat(*this); PIMathMatrixT<Rows, Cols, Type> smat(*this);
bool ndet; bool ndet;
uint crow; uint crow;
Type mul; Type mul;
@@ -448,15 +535,19 @@ public:
return *this; return *this;
} }
/** //! \~english
* \brief Matrix inversion operation. Works only with square matrix, nonzero matrices and invertible matrix //! \brief Matrix inversion operation.
* //! \details Works only with square matrix, nonzero matrices and invertible matrix.
* @param ok is a parameter with which we can find out if the method worked correctly //! \param ok is a parameter with which we can find out if the method worked correctly.
* @return copy of inverted matrix //! \return inverted matrix.
*/ //! \~russian
_CMatrix &invert(bool *ok = 0) { //! \brief Операция обращения матрицы.
//! \details Работает только с квадратными, ненулевыми и обратимыми матрицами.
//! \param ok это параметр, с помощью которого мы можем узнать, правильно ли сработал метод.
//! \return обратная матрица.
PIMathMatrixT<Rows, Cols, Type> &invert(bool *ok = 0) {
static_assert(Rows == Cols, "Works only with square matrix"); static_assert(Rows == Cols, "Works only with square matrix");
_CMatrix mtmp = _CMatrix::identity(), smat(*this); PIMathMatrixT<Rows, Cols, Type> mtmp = PIMathMatrixT<Rows, Cols, Type>::identity(), smat(*this);
bool ndet; bool ndet;
uint crow; uint crow;
Type mul, iddiv; Type mul, iddiv;
@@ -502,35 +593,45 @@ public:
return *this; return *this;
} }
/** //! \~english
* \brief Matrix inversion operation. Works only with square matrix, nonzero matrices and invertible matrix //! \brief Matrix inversion operation.
* //! \details Works only with square matrix, nonzero matrices and invertible matrix.
* @param ok is a parameter with which we can find out if the method worked correctly //! \param ok is a parameter with which we can find out if the method worked correctly.
* @return inverted matrix //! \return copy of inverted matrix.
*/ //! \~russian
_CMatrix inverted(bool *ok = 0) const { //! \brief Операция обращения матрицы.
_CMatrix tm(*this); //! \details Работает только с квадратными, ненулевыми и обратимыми матрицами.
//! \param ok это параметр, с помощью которого мы можем узнать, правильно ли сработал метод.
//! \return копия обратной матрицы.
PIMathMatrixT<Rows, Cols, Type> inverted(bool *ok = 0) const {
PIMathMatrixT<Rows, Cols, Type> tm(*this);
tm.invert(ok); tm.invert(ok);
return tm; return tm;
} }
/** //! \~english
* \brief Matrix transposition operation. Works only with square matrix, nonzero matrices and invertible matrix //! \brief Matrix transposition operation.
* //! \details Works only with square matrix.
* @return transposed matrix //! \return copy of transposed matrix
*/ //! \~russian
_CMatrixI transposed() const { //! \brief Транспонирование матрицы.
_CMatrixI tm; //! \details Работает только с квадратными матрицами.
//! \return копия транспонированной матрицы.
PIMathMatrixT<Cols, Rows, Type> transposed() const {
PIMathMatrixT<Cols, Rows, Type> tm;
PIMM_FOR tm[c][r] = m[r][c]; PIMM_FOR tm[c][r] = m[r][c];
return tm; return tm;
} }
/** //! \~english
* \brief Matrix rotation operation. Works only with 2x2 matrix //! \brief Matrix rotation operation.
* //! \details Works only with 2x2 matrix.
* @return rotated matrix //! \return rotated matrix.
*/ //! \~russian
_CMatrix rotate(Type angle) { //! \brief Операция поворота матрицы.
//! \details Работает только с матрицами 2x2.
//! \return повернутая матрица.
Review

эта функция должна возвращать _CMatrix &
И хорошо бы сделать функцию rotated которая вернет копию

эта функция должна возвращать _CMatrix & И хорошо бы сделать функцию rotated которая вернет копию
PIMathMatrixT<Rows, Cols, Type> rotate(Type angle) {
static_assert(Rows == 2 && Cols == 2, "Works only with 2x2 matrix"); static_assert(Rows == 2 && Cols == 2, "Works only with 2x2 matrix");
Type c = std::cos(angle); Type c = std::cos(angle);
Type s = std::sin(angle); Type s = std::sin(angle);
@@ -542,6 +643,27 @@ public:
return *this; return *this;
} }
//! \~english
//! \brief Matrix rotation operation.
//! \details Works only with 2x2 matrix.
//! \return copy of rotated matrix.
//! \~russian
//! \brief Операция поворота матрицы.
//! \details Работает только с матрицами 2x2.
//! \return копия повернутой матрицы.
PIMathMatrixT<Rows, Cols, Type>& rotated(Type angle) {
static_assert(Rows == 2 && Cols == 2, "Works only with 2x2 matrix");
PIMathMatrixT<Cols, Rows, Type> outm;
Type c = std::cos(angle);
Type s = std::sin(angle);
PIMathMatrixT<2u, 2u> tm;
tm[0][0] = tm[1][1] = c;
tm[0][1] = -s;
tm[1][0] = s;
outm = outm * tm;
return outm;
}
private: private:
Type m[Rows][Cols]; Type m[Rows][Cols];
}; };
@@ -565,13 +687,16 @@ inline std::ostream & operator <<(std::ostream & s, const PIMathMatrixT<Rows, Co
} }
#endif #endif
/** //! \~english
* \brief Add matrix "m" at the end of matrix and return reference to matrix //! \brief Inline operator for outputting the matrix to the console.
* //! \param s \a PICout type.
* @param s PICout type //! \param the matrix type \a PIMathMatrix that we print to the console.
* @param m PIMathMatrixT type //! \return \a PIMathMatrix printed to the console.
* @return bitwise left PICout //! \~russian
*/ //! \brief Inline-оператор для вывода матрицы в консоль.
//! \param s типа \a PICout.
//! \param m типа \a PIMathMatrixT.
//! \return непечатанная в консоль \a PICout.
template<uint Rows, uint Cols, typename Type> template<uint Rows, uint Cols, typename Type>
inline PICout operator<<(PICout s, const PIMathMatrixT<Rows, Cols, Type> &m) { inline PICout operator<<(PICout s, const PIMathMatrixT<Rows, Cols, Type> &m) {
s << "{"; s << "{";
@@ -586,13 +711,16 @@ inline PICout operator<<(PICout s, const PIMathMatrixT<Rows, Cols, Type> &m) {
return s; return s;
} }
/** //! \~english
* \brief Multiplying matrices by each other. If you enter an index out of the border of the matrix there will be "undefined behavior" //! \brief Multiplying matrices by each other.
* //! \param fm first matrix multiplier.
* @param fm first matrix multiplier //! \param sm second matrix multiplier.
* @param sm second matrix multiplier //! \return matrix that is the result of multiplication.
* @return matrix that is the result of multiplication //! \~russian
*/ //! \brief Умножение матриц друг на друга.
//! \param fm первый множитель-матрица.
//! \param sm второй множитель-матрица.
//! \return матрица, являющаяся результатом умножения.
template<uint CR, uint Rows0, uint Cols1, typename Type> template<uint CR, uint Rows0, uint Cols1, typename Type>
inline PIMathMatrixT<Rows0, Cols1, Type> operator*(const PIMathMatrixT<Rows0, CR, Type> &fm, inline PIMathMatrixT<Rows0, Cols1, Type> operator*(const PIMathMatrixT<Rows0, CR, Type> &fm,
const PIMathMatrixT<CR, Cols1, Type> &sm) { const PIMathMatrixT<CR, Cols1, Type> &sm) {
@@ -609,13 +737,16 @@ inline PIMathMatrixT<Rows0, Cols1, Type> operator*(const PIMathMatrixT<Rows0, CR
return tm; return tm;
} }
/** //! \~english
* \brief Multiplying matrix and vector. If you enter an index out of the border of the matrix there will be "undefined behavior" //! \brief Multiplying a matrix by a vector.
* //! \param fm first matrix multiplier
* @param fm first matrix multiplier //! \param sv second vector multiplier
* @param sv second vector multiplier //! \return vector that is the result of multiplication
* @return vector that is the result of multiplication //! \~russian
*/ //! \brief Умножения матрицы на вектор.
//! \param fm первый множитель-матрица.
//! \param sv второй множитель-вектор.
//! \return вектор, являющийся результатом умножения.
template<uint Cols, uint Rows, typename Type> template<uint Cols, uint Rows, typename Type>
inline PIMathVectorT<Rows, Type> operator*(const PIMathMatrixT<Rows, Cols, Type> &fm, inline PIMathVectorT<Rows, Type> operator*(const PIMathMatrixT<Rows, Cols, Type> &fm,
const PIMathVectorT<Cols, Type> &sv) { const PIMathVectorT<Cols, Type> &sv) {
@@ -630,13 +761,16 @@ inline PIMathVectorT<Rows, Type> operator*(const PIMathMatrixT<Rows, Cols, Type>
return tv; return tv;
} }
/** //! \~english
* \brief Multiplying vector and matrix. If you enter an index out of the border of the matrix there will be "undefined behavior" //! \brief Multiplying a vector by a matrix.
* //! \param sv first vector multiplier
* @param sv first vector multiplier //! \param fm second matrix multiplier
* @param fm second matrix multiplier //! \return vector that is the result of multiplication
* @return vector that is the result of multiplication //! \~russian
*/ //! \brief Умножения вектора на матрицу.
//! \param sv второй множитель-вектор.
//! \param fm первый множитель-матрица.
//! \return вектор, являющийся результатом умножения.
template<uint Cols, uint Rows, typename Type> template<uint Cols, uint Rows, typename Type>
inline PIMathVectorT<Cols, Type> operator*(const PIMathVectorT<Rows, Type> &sv, inline PIMathVectorT<Cols, Type> operator*(const PIMathVectorT<Rows, Type> &sv,
const PIMathMatrixT<Rows, Cols, Type> &fm) { const PIMathMatrixT<Rows, Cols, Type> &fm) {
@@ -651,13 +785,16 @@ inline PIMathVectorT<Cols, Type> operator*(const PIMathVectorT<Rows, Type> &sv,
return tv; return tv;
} }
/** //! \~english
* \brief Multiplying value of type Type and matrix //! \brief Multiplying a value of type `Type` by a matrix.
* //! \param x first multiplier of type `Type`.
* @param x first multiplier of type Type //! \param v second matrix multiplier.
* @param fm second matrix multiplier //! \return matrix that is the result of multiplication.
* @return matrix that is the result of multiplication //! \~russian
*/ //! \brief Умножение значения тип `Type` на матрицу.
//! \param x первый множитель типа `Type`.
//! \param v вторая множитель-матрица.
//! \return матрица, являющаяся результатом умножения.
template<uint Cols, uint Rows, typename Type> template<uint Cols, uint Rows, typename Type>
inline PIMathMatrixT<Rows, Cols, Type> operator*(const Type &x, const PIMathMatrixT<Rows, Cols, Type> &v) { inline PIMathMatrixT<Rows, Cols, Type> operator*(const Type &x, const PIMathMatrixT<Rows, Cols, Type> &v) {
return v * x; return v * x;
@@ -690,41 +827,53 @@ class PIMathMatrix;
#define PIMM_FOR_C for (uint i = 0; i < _V2D::cols_; ++i) #define PIMM_FOR_C for (uint i = 0; i < _V2D::cols_; ++i)
#define PIMM_FOR_R for (uint i = 0; i < _V2D::rows_; ++i) #define PIMM_FOR_R for (uint i = 0; i < _V2D::rows_; ++i)
//! \brief A class that works with matrix operations, the input data of which is the data type of the matrix //! \~english
//! @tparam There are can be basic C++ language data and different classes where the arithmetic operators(=, +=, -=, *=, /=, ==, !=, +, -, *, /) //! \brief A class that works with matrix operations, the input data of which is the data type of the matrix.
//! of the C++ language are implemented //! @tparam `Type` There are can be basic C++ language data and different classes where the arithmetic operators(=, +=, -=, *=, /=, ==, !=, +, -, *, /)
//! of the C++ language are implemented.
//! \~russian
//! \brief Класс, работающий с матричными операциями, входными данными которого является тип данных матрицы.
//! @tparam `Type` Здесь можеть быть базовый тип данных C++ или различные классы,
//! где реализованы арифметические операторы(=, +=, -=, *=, /=, ==, !=, +, -, *, /) языка C++.
template<typename Type> template<typename Type>
class PIP_EXPORT PIMathMatrix : public PIVector2D<Type> { class PIP_EXPORT PIMathMatrix : public PIVector2D<Type> {
typedef PIVector2D<Type> _V2D; typedef PIVector2D<Type> _V2D;
typedef PIMathMatrix<Type> _CMatrix; typedef PIMathMatrix<Type> _CMatrix;
public: public:
/** //! \~english
* \brief Constructor of class PIMathMatrix, which creates a matrix //! \brief Constructor of class \a PIMathMatrix, which creates a matrix.
* //! \param cols is number of matrix column \a uint type.
* @param cols is number of matrix column uint type //! \param rows is number of matrix row \a uint type.
* @param rows is number of matrix row uint type //! \param f is type of matrix elements.
* @param f is type of matrix elements //! \~russian
*/ //! \brief Конструктор класса \a PIMathMatrix, который создает матрицу.
//! \param cols количество столбов матрицы типа \a uint.
//! \param rows количество строк матрицы типа \a uint.
//! \param f тип элементов матрицы.
PIMathMatrix(const uint cols = 0, const uint rows = 0, const Type &f = Type()) { _V2D::resize(rows, cols, f); } PIMathMatrix(const uint cols = 0, const uint rows = 0, const Type &f = Type()) { _V2D::resize(rows, cols, f); }
/** //! \~english
* \brief Constructor of class PIMathMatrix, which creates a matrix //! \brief Constructor of class \a PIMathMatrix, which creates a matrix
* //! \param cols is number of matrix column \a uint type
* @param cols is number of matrix column uint type //! \param rows is number of matrix row \a uint type
* @param rows is number of matrix row uint type //! \param val is \a PIVector<Type> of matrix elements
* @param val is PIVector<Type> of matrix elements //! \~russian
*/ //! \brief Конструктор класса \a PIMathMatrix, который создает матрицу.
//! \param cols количество столбов матрицы типа \a uint.
//! \param rows количество строк матрицы типа \a uint.
//! \param val тип \a PIVector<Type> элементов матрицы.
PIMathMatrix(const uint cols, const uint rows, const PIVector<Type> &val) { PIMathMatrix(const uint cols, const uint rows, const PIVector<Type> &val) {
_V2D::resize(rows, cols); _V2D::resize(rows, cols);
int i = 0; int i = 0;
PIMM_FOR _V2D::element(r, c) = val[i++]; PIMM_FOR _V2D::element(r, c) = val[i++];
} }
/** //! \~english
* \brief Constructor of class PIMathMatrix, which creates a matrix //! \brief Constructor of class \a PIMathMatrix, which creates a matrix.
* //! \param val is PIVector<Type> of PIVector, which creates matrix.
* @param val is PIVector<Type> of PIVector, which creates matrix //! \~russian
*/ //! \brief Конструктор класса \a PIMathMatrix, который создает матрицу.
//! \param val тип \a PIVector<Type>, который создает матрицу.
PIMathMatrix(const PIVector<PIVector<Type> > &val) { PIMathMatrix(const PIVector<PIVector<Type> > &val) {
if (!val.isEmpty()) { if (!val.isEmpty()) {
_V2D::resize(val.size(), val[0].size()); _V2D::resize(val.size(), val[0].size());
@@ -736,11 +885,12 @@ public:
} }
} }
/** //! \~english
* \brief Constructor of class PIMathMatrix, which creates a matrix //! \brief Constructor of class \a PIMathMatrix, which creates a matrix.
* //! \param val is \a PIVector2D<Type>, which creates matrix.
* @param val is PIVector2D<Type>, which creates matrix //! \~russian
*/ //! \brief Конструктор класса \a PIMathMatrix, который создает матрицу.
//! \param val тип \a PIVector2D<Type>, который создает матрицу.
PIMathMatrix(const PIVector2D<Type> &val) { PIMathMatrix(const PIVector2D<Type> &val) {
if (!val.isEmpty()) { if (!val.isEmpty()) {
_V2D::resize(val.rows(), val.cols()); _V2D::resize(val.rows(), val.cols());
@@ -748,246 +898,301 @@ public:
} }
} }
/** //! \~english
* \brief Creates a matrix whose main diagonal is filled with ones and the remaining elements are zeros //! \brief Creates a matrix whose main diagonal is filled with ones and the remaining elements are zeros
* //! \param cols is number of matrix column uint type
* @param cols is number of matrix column uint type //! \param rows is number of matrix row uint type
* @param rows is number of matrix row uint type //! \return identity matrix(cols, rows)
* @return identity matrix(cols,rows) //! \~russian
*/ //! \brief Создает матрицу, главная диагональ которой заполнена, а оставшиеся элементы - нулями.
static _CMatrix identity(const uint cols, const uint rows) { //! \param cols количество столбов матрицы типа \a uint.
_CMatrix tm(cols, rows); //! \param rows количество строк матрицы типа \a uint.
//! \return единичная матрица matrix(`cols`, `rows`)
static PIMathMatrix<Type> identity(const uint cols, const uint rows) {
PIMathMatrix<Type> tm(cols, rows);
for (uint r = 0; r < rows; ++r) for (uint c = 0; c < cols; ++c) tm.element(r, c) = (c == r ? Type(1) : Type(0)); for (uint r = 0; r < rows; ++r) for (uint c = 0; c < cols; ++c) tm.element(r, c) = (c == r ? Type(1) : Type(0));
return tm; return tm;
} }
/** //! \~english
* \brief Creates a row matrix of every element that is equal to every element of the vector //! \brief Creates a row matrix of every element that is equal to every element of the vector
* //! \param val is the vector type \a PIMathVector
* @param val is the vector type PIMathVector //! \return row matrix of every element that is equal to every element of the vector
* @return row matrix of every element that is equal to every element of the vector //! \~russian
*/ //! \brief Создает матрицу-строку, каждый элемент которой равен каждому элементу вектора
static _CMatrix matrixRow(const PIMathVector<Type> &val) {return _CMatrix(val.size(), 1, val.toVector());} //! \param val вектор типа \a PIMathVector
//! \return матрица-строка, каждый элемент которой равен каждому элементу вектора
static PIMathMatrix<Type> matrixRow(const PIMathVector<Type> &val) {return PIMathMatrix<Type>(val.size(), 1, val.toVector());}
/** //! \~english
* \brief Creates a column matrix of every element that is equal to every element of the vector //! \brief Creates a column matrix of every element that is equal to every element of the vector
* //! \param val is the vector type \a PIMathVector
* @param val is the vector type PIMathVector //! \return column matrix of every element that is equal to every element of the vector
* @return column matrix of every element that is equal to every element of the vector //! \~russian
*/ //! \brief Создает матрицу-столбец, каждый элемент которой равен каждому элементу вектора
static _CMatrix matrixCol(const PIMathVector<Type> &val) {return _CMatrix(1, val.size(), val.toVector());} //! \param val вектор типа \a PIMathVector
//! \return матрица-столбец, каждый элемент которой равен каждому элементу вектора
static PIMathMatrix<Type> matrixCol(const PIMathVector<Type> &val) {return PIMathMatrix<Type>(1, val.size(), val.toVector());}
/** //! \~english
* \brief Set the selected column in matrix. If there are more elements of the vector than elements in the column of the matrix //! \brief Set the selected column in matrix.
* or index larger than the number of columns otherwise there will be "undefined behavior" //! \details If there are more elements of the vector than elements in the column of the matrix
* //! or index larger than the number of columns otherwise there will be "undefined behavior".
* @param index is the number of the selected column //! \param index is the number of the selected column.
* @param v is a vector of the type _CMCol that needs to fill the column //! \param v is a vector of the type \a PIMathVector<Type> that needs to fill the column.
* @return matrix type _CMatrix //! \return matrix type \a PIMathMatrix<Type>
*/ //! \~russian
_CMatrix &setCol(uint index, const PIMathVector<Type> &v) { //! \brief Определить выбранный столбец матрицы.
//! \details Если элементов в векторе больше, чем элементов в столбце матрицы
//! или индекс больше количества стобцов, то поведение не определено ("undefined behavior").
//! \param index номер выбранного столбца.
//! \param v вектор типа \a PIMathVector<Type>, которым нужно заполнить столбец.
//! \return матрица типа \a PIMathMatrix<Type>.
PIMathMatrix<Type> &setCol(uint index, const PIMathVector<Type> &v) {
assert(_V2D::rows() == v.size()); assert(_V2D::rows() == v.size());
PIMM_FOR_R _V2D::element(i, index) = v[i]; PIMM_FOR_R _V2D::element(i, index) = v[i];
return *this; return *this;
} }
/** //! \~english
* \brief Set the selected row in matrix. If there are more elements of the vector than elements in the row of the matrix, //! \brief Set the selected row in matrix.
* or index larger than the number of rows otherwise there will be "undefined behavior" //! \details If there are more elements of the vector than elements in the row of the matrix,
* @param index is the number of the selected row //! or index larger than the number of rows otherwise there will be "undefined behavior".
* @param v is a vector of the type _CMCol that needs to fill the row //! \param index is the number of the selected row.
* @return matrix type _CMatrix //! \param v is a vector of the type \a PIMathVector<Type> that needs to fill the row.
*/ //! \return matrix type \a PIMathMatrix<Type>.
_CMatrix &setRow(uint index, const PIMathVector<Type> &v) { //! \~russian
//! \brief Определить выбранную строку матрицы.
//! \details Если элементов в векторе больше, чем элементов в строке матрицы
//! или индекс больше количества стобцов, то поведение не определено ("undefined behavior").
//! \param index номер выбранной строки.
//! \param v вектор типа \a PIMathVector<Type>, которым нужно заполнить строку.
//! \return матрица типа \a PIMathMatrix<Type>.
PIMathMatrix<Type> &setRow(uint index, const PIMathVector<Type> &v) {
assert(_V2D::cols() == v.size()); assert(_V2D::cols() == v.size());
PIMM_FOR_C _V2D::element(index, i) = v[i]; PIMM_FOR_C _V2D::element(index, i) = v[i];
return *this; return *this;
} }
/** //! \~english
* \brief Method which replace selected columns in a matrix. You cannot use an index larger than the number of columns, //! \brief Method which swaps selected columns in a matrix.
* otherwise there will be "undefined behavior" //! \details You cannot use an index larger than the number of columns,
* //! otherwise there will be "undefined behavior".
* @param r0 is the number of the first selected row //! \param r0 is the number of the first selected column.
* @param r1 is the number of the second selected row //! \param r1 is the number of the second selected column.
* @return matrix type _CMatrix //! \return matrix type \a PIMathMatrix<Type>.
*/ //! \~russian
_CMatrix &swapCols(uint r0, uint r1) { //! \brief Метод меняющий местами выбранные строки в матрице.
//! \details Вы не можете использовать индекс, который больше количества столбцов,
//! иначе будет неопределенное повередение ("undefined behavior").
//! \param r0 номер первой выбранного стобца.
//! \param r1 номер второй выбранного столбца.
//! \return матрица типа \a PIMathMatrix<Type>.
PIMathMatrix<Type> &swapCols(uint r0, uint r1) {
PIMM_FOR_C piSwap<Type>(_V2D::element(i, r0), _V2D::element(i, r1)); PIMM_FOR_C piSwap<Type>(_V2D::element(i, r0), _V2D::element(i, r1));
return *this; return *this;
} }
/** //! \~english
* \brief Method which replace selected rows in a matrix. You cannot use an index larger than the number of rows, //! \brief Method which replace selected rows in a matrix.
* otherwise there will be "undefined behavior" //! \details You cannot use an index larger than the number of rows,
* //! otherwise there will be "undefined behavior"
* @param c0 is the number of the first selected row //! \param c0 is the number of the first selected row.
* @param c1 is the number of the second selected row //! \param c1 is the number of the second selected row.
* @return matrix type _CMatrix //! \return matrix type \a PIMathMatrix<Type>.
*/ //! \~russian
_CMatrix &swapRows(uint c0, uint c1) { //! \brief Метод меняющий местами выбранные строки в матрице.
//! \details Вы не можете использовать индекс, который больше количества строк,
//! иначе будет неопределенное повередение ("undefined behavior").
//! \param с0 номер первой выбранной строки.
//! \param с1 номер второй выбранной строки.
//! \return матрица типа \a PIMathMatrix<Type>.
PIMathMatrix<Type> &swapRows(uint c0, uint c1) {
PIMM_FOR_R piSwap<Type>(_V2D::element(c0, i), _V2D::element(c1, i)); PIMM_FOR_R piSwap<Type>(_V2D::element(c0, i), _V2D::element(c1, i));
return *this; return *this;
} }
/** //! \~english
* \brief Method which fills the matrix with selected value //! \brief Method which fills the matrix with selected value.
* //! \param v is a parameter the type and value of which is selected and later filled into the matrix.
* @param v is a parameter the type and value of which is selected and later filled into the matrix //! \return filled matrix type \a PIMathMatrix<Type>.
* @return filled matrix type _CMatrix //! \~russian
*/ //! \brief Метод заполняющий матрицу выбранным значением.
_CMatrix &fill(const Type &v) { //! \param v параметр выбранного типа и значения, которым будет заполнена матрица.
//! \return заполненная матрица типа \a PIMathMatrix<Type>.
PIMathMatrix<Type> &fill(const Type &v) {
PIMM_FOR_A _V2D::mat[i] = v; PIMM_FOR_A _V2D::mat[i] = v;
return *this; return *this;
} }
/** //! \~english
* \brief Method which checks if matrix is square //! \brief Method which checks if matrix is square.
* //! \return true if matrix is square, else false.
* @return true if matrix is square, else false //! \~russian
*/ //! \brief Метод, проверющий является ли матрица квадратной.
//! \return true если матрица квадратная, иначе false.
bool isSquare() const { return _V2D::cols_ == _V2D::rows_; } bool isSquare() const { return _V2D::cols_ == _V2D::rows_; }
/** //! \~english
* \brief Method which checks if main diagonal of matrix consists of ones and another elements are zeros //! \brief Method which checks if main diagonal of matrix consists of ones and another elements are zeros.
* //! \return true if matrix is identitied, else false.
* @return true if matrix is identity, else false //! \~russian
*/ //! \brief Метод, проверяющий содержит ли главная диагональ единицы и все остальные поля нули.
//! \return true если матрица единичная, иначе false.
bool isIdentity() const { bool isIdentity() const {
PIMM_FOR if ((c == r) ? _V2D::element(r, c) != Type(1) : _V2D::element(r, c) != Type(0))return false; PIMM_FOR if ((c == r) ? _V2D::element(r, c) != Type(1) : _V2D::element(r, c) != Type(0))return false;
return true; return true;
} }
/** //! \~english
* \brief Method which checks if every elements of matrix are zeros //! \brief Method which checks if every elements of matrix are zeros.
* //! \return true if matrix is null, else false.
* @return true if matrix elements equal to zero, else false //! \~russian
*/ //! \brief Метод, являются ли все элементы матрицы нулями.
//! \return true если матрица нулевая, иначе false.
bool isNull() const { bool isNull() const {
PIMM_FOR_A if (_V2D::mat[i] != Type(0)) return false; PIMM_FOR_A if (_V2D::mat[i] != Type(0)) return false;
return true; return true;
} }
/** //! \~english
* \brief Method which checks if matrix is empty //! \brief Method which checks if matrix is empty.
* //! \return true if matrix is valid, else false.
* @return true if matrix is valid, else false //! \~russian
*/ //! \brief Метод, который проверяет является ли матрица пустой.
//! \return true если матрица действительна, иначе false.
bool isValid() const { return !PIVector2D<Type>::isEmpty(); } bool isValid() const { return !PIVector2D<Type>::isEmpty(); }
/** //! \~english
* \brief Addition assignment with matrix "sm" //! \brief Addition assignment with matrix `sm`.
* //! \param sm matrix for the addition assigment.
* @param sm matrix for the addition assigment //! \~russian
*/ //! \brief Сложение с присваиванием с матрицей `sm`.
void operator+=(const _CMatrix &sm) { //! \param sm матрица для сложения с присваиванием.
void operator+=(const PIMathMatrix<Type> &sm) {
assert(_V2D::rows() == sm.rows()); assert(_V2D::rows() == sm.rows());
assert(_V2D::cols() == sm.cols()); assert(_V2D::cols() == sm.cols());
PIMM_FOR_A _V2D::mat[i] += sm.mat[i]; PIMM_FOR_A _V2D::mat[i] += sm.mat[i];
} }
/** //! \~english
* \brief Subtraction assignment with matrix "sm" //! \brief Subtraction assignment with matrix `sm`.
* //! \param sm matrix for the subtraction assigment.
* @param sm matrix for the subtraction assigment //! \~russian
*/ //! \brief Вычитание с присваиванием с матрицей `sm`.
void operator-=(const _CMatrix &sm) { //! \param sm матрица для вычитания с присваиванием.
void operator-=(const PIMathMatrix<Type> &sm) {
assert(_V2D::rows() == sm.rows()); assert(_V2D::rows() == sm.rows());
assert(_V2D::cols() == sm.cols()); assert(_V2D::cols() == sm.cols());
PIMM_FOR_A _V2D::mat[i] -= sm.mat[i]; PIMM_FOR_A _V2D::mat[i] -= sm.mat[i];
} }
/** //! \~english
* \brief Multiplication assignment with value "v" //! \brief Multiplication assignment with value `v`.
* //! \param v value for the multiplication assigment.
* @param v value for the multiplication assigment //! \~russian
*/ //! \brief Умножение с присваиванием с матрицей `v`.
//! \param sm матрица для умножения с присваиванием.
void operator*=(const Type &v) { void operator*=(const Type &v) {
PIMM_FOR_A _V2D::mat[i] *= v; PIMM_FOR_A _V2D::mat[i] *= v;
} }
/** //! \~english
* \brief Division assignment with value "v" //! \brief Division assignment with value `v`.
* //! \param v value for the division assigment.
* @param v value for the division assigment //! \~russian
*/ //! \brief Деление с присваиванием с матрицей `v`.
//! \param sm матрица для деления с присваиванием.
void operator/=(const Type &v) { void operator/=(const Type &v) {
assert(piAbs<Type>(v) > PIMATHVECTOR_ZERO_CMP); assert(piAbs<Type>(v) > PIMATHVECTOR_ZERO_CMP);
PIMM_FOR_A _V2D::mat[i] /= v; PIMM_FOR_A _V2D::mat[i] /= v;
} }
/** //! \~english
* \brief Matrix substraction //! \brief Negation operation
* //! \return copy of the negative matrix
* @return the result of matrix substraction //! \~russian
*/ //! \brief Операция отрицания
_CMatrix operator-() const { //! \return копия отрицательной матрицы
_CMatrix tm(*this); PIMathMatrix<Type> operator-() const {
PIMathMatrix<Type> tm(*this);
PIMM_FOR_A tm.mat[i] = -_V2D::mat[i]; PIMM_FOR_A tm.mat[i] = -_V2D::mat[i];
return tm; return tm;
} }
/** //! \~english
* \brief Matrix addition //! \brief Matrix addition.
* //! \param sm is matrix term.
* @param sm is matrix term //! \return the result of matrix addition.
* @return the result of matrix addition //! \~russian
*/ //! \brief Матричное сложение.
_CMatrix operator+(const _CMatrix &sm) const { //! \param sm матричное слагаемое.
_CMatrix tm(*this); //! \return результат матричного сложения.
PIMathMatrix<Type> operator+(const PIMathMatrix<Type> &sm) const {
PIMathMatrix<Type> tm(*this);
assert(tm.rows() == sm.rows()); assert(tm.rows() == sm.rows());
assert(tm.cols() == sm.cols()); assert(tm.cols() == sm.cols());
PIMM_FOR_A tm.mat[i] += sm.mat[i]; PIMM_FOR_A tm.mat[i] += sm.mat[i];
return tm; return tm;
} }
/** //! \~english
* \brief Matrix subtraction //! \brief Matrix substraction.
* //! \param sm is matrix subtrahend.
* @param sm is matrix subtractor //! \return the result of matrix substraction.
* @return the result of matrix subtraction //! \~russian
*/ //! \brief Матричная разность.
_CMatrix operator-(const _CMatrix &sm) const { //! \param sm матричное вычитаемое.
_CMatrix tm(*this); //! \return результат матричной разности.
PIMathMatrix<Type> operator-(const PIMathMatrix<Type> &sm) const {
PIMathMatrix<Type> tm(*this);
assert(tm.rows() == sm.rows()); assert(tm.rows() == sm.rows());
assert(tm.cols() == sm.cols()); assert(tm.cols() == sm.cols());
PIMM_FOR_A tm.mat[i] -= sm.mat[i]; PIMM_FOR_A tm.mat[i] -= sm.mat[i];
return tm; return tm;
} }
/** //! \~english
* \brief Matrix multiplication //! \brief Matrix multiplication.
* //! \param v is value factor.
* @param v is value factor //! \return the result of matrix multiplication.
* @return the result of matrix multiplication //! \~russian
*/ //! \brief Матричное произведение.
_CMatrix operator*(const Type &v) const { //! \param v множитель.
_CMatrix tm(*this); //! \return результат произведения.
PIMathMatrix<Type> operator*(const Type &v) const {
PIMathMatrix<Type> tm(*this);
PIMM_FOR_A tm.mat[i] *= v; PIMM_FOR_A tm.mat[i] *= v;
return tm; return tm;
} }
/** //! \~english
* \brief Matrix division //! \brief Matrix division.
* //! \param v is value divider.
* @param v is value divider //! \return the result of matrix division.
* @return the result of matrix division //! \~russian
*/ //! \brief Матричное деление.
_CMatrix operator/(const Type &v) const { //! \param v делитель.
//! \return результат деления.
PIMathMatrix<Type> operator/(const Type &v) const {
assert(piAbs<Type>(v) > PIMATHVECTOR_ZERO_CMP); assert(piAbs<Type>(v) > PIMATHVECTOR_ZERO_CMP);
_CMatrix tm(*this); PIMathMatrix<Type> tm(*this);
PIMM_FOR_A tm.mat[i] /= v; PIMM_FOR_A tm.mat[i] /= v;
return tm; return tm;
} }
/** //! \~english
* \brief Determinant of the self matrix is calculated. Works only with square matrix, nonzero matrices and invertible matrix //! \brief Calculate Determinant of the matrix.
* //! \details Works only with square matrix, nonzero matrices and invertible matrix.
* @param ok is a parameter with which we can find out if the method worked correctly //! \param ok is a parameter with which we can find out if the method worked correctly.
* @return matrix determinant //! \return matrix determinant.
*/ //! \~russian
//! \brief Вычислить определитель матрицы.
//! \details Работает только с квадратными, ненулевыми и обратимыми матрицами.
//! \param ok это параметр, с помощью которого мы можем узнать, правильно ли сработал метод.
//! \return опеределитель матрицы.
Type determinant(bool *ok = 0) const { Type determinant(bool *ok = 0) const {
_CMatrix m(*this); PIMathMatrix<Type> m(*this);
bool k; bool k;
m.toUpperTriangular(&k); m.toUpperTriangular(&k);
Type ret = Type(0); Type ret = Type(0);
@@ -1001,11 +1206,14 @@ public:
return ret; return ret;
} }
/** //! \~english
* \brief Trace of the matrix is calculated. Works only with square matrix, nonzero matrices and invertible matrix //! \brief Calculate the trace of a matrix.
* //! \details Works only with square matrix matrix.
* @return matrix trace //! \return matrix trace.
*/ //! \~russian
//! \brief Вычислить след матрицы.
//! \details Работает только с квадратными матрицами.
//! \return след матрицы.
Type trace() const { Type trace() const {
assert(isSquare()); assert(isSquare());
Type ret = Type(0); Type ret = Type(0);
@@ -1015,15 +1223,19 @@ public:
return ret; return ret;
} }
/** //! \~english
* \brief Transforming matrix to upper triangular. Works only with square matrix, nonzero matrices and invertible matrix //! \brief Transforming matrix to upper triangular.
* //! \details Works only with square matrix, nonzero matrices and invertible matrix.
* @param ok is a parameter with which we can find out if the method worked correctly //! \param ok is a parameter with which we can find out if the method worked correctly.
* @return copy of transformed upper triangular matrix //! \return copy of transformed upper triangular matrix.
*/ //! \~russian
_CMatrix &toUpperTriangular(bool *ok = 0) { //! \brief Преобразование матрицы в верхнетреугольную.
//! \details Работает только с квадратными, ненулевыми и обратимыми матрицами.
//! \param ok это параметр, с помощью которого мы можем узнать, правильно ли сработал метод.
//! \return копия преобразованной верхнетреугольной матрицы.
PIMathMatrix<Type> &toUpperTriangular(bool *ok = 0) {
assert(isSquare()); assert(isSquare());
_CMatrix smat(*this); PIMathMatrix<Type> smat(*this);
bool ndet; bool ndet;
uint crow; uint crow;
Type mul; Type mul;
@@ -1055,16 +1267,19 @@ public:
return *this; return *this;
} }
/** //! \~english
* \brief Matrix inversion operation. Works only with square matrix, nonzero matrices and invertible matrix //! \brief Matrix inversion operation.
* //! \details Works only with square matrix, nonzero matrices and invertible matrix.
* @param ok is a parameter with which we can find out if the method worked correctly //! \param ok is a parameter with which we can find out if the method worked correctly.
* @param sv is a vector multiplier //! \return inverted matrix.
* @return copy of inverted matrix //! \~russian
*/ //! \brief Операция обращения матрицы.
_CMatrix &invert(bool *ok = 0, PIMathVector<Type> *sv = 0) { //! \details Работает только с квадратными, ненулевыми и обратимыми матрицами.
//! \param ok это параметр, с помощью которого мы можем узнать, правильно ли сработал метод.
//! \return обратная матрица.
PIMathMatrix<Type> &invert(bool *ok = 0, PIMathVector<Type> *sv = 0) {
assert(isSquare()); assert(isSquare());
_CMatrix mtmp = _CMatrix::identity(_V2D::cols_, _V2D::rows_), smat(*this); PIMathMatrix<Type> mtmp = PIMathMatrix<Type>::identity(_V2D::cols_, _V2D::rows_), smat(*this);
bool ndet; bool ndet;
uint crow; uint crow;
Type mul, iddiv; Type mul, iddiv;
@@ -1114,25 +1329,32 @@ public:
return *this; return *this;
} }
/** //! \~english
* \brief Matrix inversion operation. Works only with square matrix, nonzero matrices and invertible matrix //! \brief Matrix inversion operation.
* //! \details Works only with square matrix, nonzero matrices and invertible matrix.
* @param ok is a parameter with which we can find out if the method worked correctly //! \param ok is a parameter with which we can find out if the method worked correctly.
* @return inverted matrix //! \return copy of inverted matrix.
*/ //! \~russian
_CMatrix inverted(bool *ok = 0) const { //! \brief Операция обращения матрицы.
_CMatrix tm(*this); //! \details Работает только с квадратными, ненулевыми и обратимыми матрицами.
//! \param ok это параметр, с помощью которого мы можем узнать, правильно ли сработал метод.
//! \return копия обратной матрицы.
PIMathMatrix<Type> inverted(bool *ok = 0) const {
PIMathMatrix<Type> tm(*this);
tm.invert(ok); tm.invert(ok);
return tm; return tm;
} }
/** //! \~english
* \brief Matrix transposition operation //! \brief Matrix transposition operation.
* //! \details Works only with square matrix matrix.
* @return transposed matrix //! \return copy of transposed matrix
*/ //! \~russian
_CMatrix transposed() const { //! \brief Транспонирование матрицы.
_CMatrix tm(_V2D::rows_, _V2D::cols_); //! \details Работает только с квадратными матрицами.
//! \return копия транспонированной матрицы.
PIMathMatrix<Type> transposed() const {
PIMathMatrix<Type> tm(_V2D::rows_, _V2D::cols_);
PIMM_FOR tm.element(c, r) = _V2D::element(r, c); PIMM_FOR tm.element(c, r) = _V2D::element(r, c);
return tm; return tm;
} }
@@ -1144,13 +1366,16 @@ template<typename Type>
inline std::ostream & operator <<(std::ostream & s, const PIMathMatrix<Type> & m) {s << "{"; for (uint r = 0; r < m.rows(); ++r) { for (uint c = 0; c < m.cols(); ++c) { s << m.element(r, c); if (c < m.cols() - 1 || r < m.rows() - 1) s << ", ";} if (r < m.rows() - 1) s << std::endl << " ";} s << "}"; return s;} inline std::ostream & operator <<(std::ostream & s, const PIMathMatrix<Type> & m) {s << "{"; for (uint r = 0; r < m.rows(); ++r) { for (uint c = 0; c < m.cols(); ++c) { s << m.element(r, c); if (c < m.cols() - 1 || r < m.rows() - 1) s << ", ";} if (r < m.rows() - 1) s << std::endl << " ";} s << "}"; return s;}
#endif #endif
/** //! \~english
* \brief Inline operator for outputting the matrix to the console //! \brief Inline operator for outputting the matrix to the console.
* //! \param s \a PICout type.
* @param s PICout type //! \param the matrix type \a PIMathMatrix that we print to the console.
* @param the matrix type PIMathMatrix that we print to the console //! \return \a PIMathMatrix printed to the console.
* @return PIMathMatrix printed to the console //! \~russian
*/ //! \brief Inline-оператор для вывода матрицы в консоль.
//! \param s типа \a PICout.
//! \param m типа \a PIMathMatrixT.
//! \return непечатанная в консоль \a PICout.
template<typename Type> template<typename Type>
inline PICout operator<<(PICout s, const PIMathMatrix<Type> &m) { inline PICout operator<<(PICout s, const PIMathMatrix<Type> &m) {
s << "Matrix{"; s << "Matrix{";
@@ -1165,26 +1390,28 @@ inline PICout operator<<(PICout s, const PIMathMatrix<Type> &m) {
return s; return s;
} }
/** //! \~english
* \brief Inline operator for serializing a matrix into a PIByteArray //! \brief Inline operator for serializing a matrix into a \a PIBinaryStream.
* //! \param s \a PIBinaryStream type.
* @param s PIByteArray type //! \param v \a PIMathMatrix type.
* @param v PIMathMatrix type //! \~russian
* @return PIBiteArray serialized PIMathMatrix //! \brief Inline-оператор для сериализации матрицы в \a PIBinaryStream.
*/ //! \param s типа \a PIBinaryStream.
//! \param v типа \a PIMathMatrix.
template <typename P, typename T> template <typename P, typename T>
inline PIBinaryStream<P> & operator <<(PIBinaryStream<P> & s, const PIMathMatrix<T> & v) { inline PIBinaryStream<P> & operator <<(PIBinaryStream<P> & s, const PIMathMatrix<T> & v) {
s << (const PIVector2D<T> &) v; s << (const PIVector2D<T> &) v;
return s; return s;
} }
/** //! \~english
* \brief Inline operator to deserialize matrix from PIByteArray //! \brief Inline operator to deserialize matrix from \a PIByteArray.
* //! \param s \a PIBinaryStream type.
* @param s PIByteArray type //! \param v \a PIMathMatrix type.
* @param v PIMathMatrix type //! \~russian
* @return PIMathMatrix deserialized from PIByteArray //! \brief Inline-оператор для сериализации матрицы в \a PIByteArray.
*/ //! \param s типа \a PIBinaryStream.
//! \param v типа \a PIMathMatrix.
template <typename P, typename T> template <typename P, typename T>
inline PIBinaryStream<P> & operator >>(PIBinaryStream<P> & s, PIMathMatrix<T> & v) { inline PIBinaryStream<P> & operator >>(PIBinaryStream<P> & s, PIMathMatrix<T> & v) {
s >> (PIVector2D<T> &) v; s >> (PIVector2D<T> &) v;
@@ -1192,13 +1419,18 @@ inline PIBinaryStream<P> & operator >>(PIBinaryStream<P> & s, PIMathMatrix<T> &
} }
/** //! \~english
* \brief Multiplying matrices by each other. If you enter an index out of the border of the matrix there will be "undefined behavior" //! \brief Multiplying matrices by each other.
* //! \details If you enter an index out of the border of the matrix there will be "undefined behavior".
* @param fm first matrix multiplier //! \param fm first matrix multiplier.
* @param sm second matrix multiplier //! \param sm second matrix multiplier.
* @return matrix that is the result of multiplication //! \return matrix that is the result of multiplication.
*/ //! \~russian
//! \brief Умножение матриц друг на друга.
//! \details Если вы введете индекс вне границ матрицы, то поведение не определено ("undefined behavior").
//! \param fm первый множитель-матрица.
//! \param sm вторая множитель-матрица.
//! \return матрица, являющаяся результатом умножения.
template<typename Type> template<typename Type>
inline PIMathMatrix<Type> operator*(const PIMathMatrix<Type> &fm, inline PIMathMatrix<Type> operator*(const PIMathMatrix<Type> &fm,
const PIMathMatrix<Type> &sm) { const PIMathMatrix<Type> &sm) {
@@ -1216,13 +1448,18 @@ inline PIMathMatrix<Type> operator*(const PIMathMatrix<Type> &fm,
return tm; return tm;
} }
/** //! \~english
* \brief Multiplying matrix and vector. If you enter an index out of the border of the matrix there will be "undefined behavior" //! \brief Multiplying a matrix by a vector.
* //! \details If you enter an index out of the border of the matrix there will be "undefined behavior".
* @param fm first matrix multiplier //! \param fm first matrix multiplier
* @param sv second vector multiplier //! \param sv second vector multiplier
* @return vector that is the result of multiplication //! \return vector that is the result of multiplication
*/ //! \~russian
//! \brief Умножения матрицы на вектор.
//! \details Если вы введете индекс вне границ матрицы, то поведение не определено ("undefined behavior").
//! \param fm первый множитель-матрица.
//! \param sv второй множитель-вектор.
//! \return вектор, являющийся результатом умножения.
template<typename Type> template<typename Type>
inline PIMathVector<Type> operator*(const PIMathMatrix<Type> &fm, inline PIMathVector<Type> operator*(const PIMathMatrix<Type> &fm,
const PIMathVector<Type> &sv) { const PIMathVector<Type> &sv) {
@@ -1238,13 +1475,18 @@ inline PIMathVector<Type> operator*(const PIMathMatrix<Type> &fm,
return tv; return tv;
} }
/** //! \~english
* \brief Multiplying vector and matrix. If you enter an index out of the border of the matrix there will be "undefined behavior" //! \brief Multiplying a vector by a matrix.
* //! \details If you enter an index out of the border of the matrix there will be "undefined behavior".
* @param sv first vector multiplier //! \param sv first vector multiplier
* @param fm second matrix multiplier //! \param fm second matrix multiplier
* @return vector that is the result of multiplication //! \return vector that is the result of multiplication
*/ //! \~russian
//! \brief Умножения вектора на матрицу.
//! \details Если вы введете индекс вне границ матрицы, то поведение не определено ("undefined behavior").
//! \param sv второй множитель-вектор.
//! \param fm первый множитель-матрица.
//! \return вектор, являющийся результатом умножения.
template<typename Type> template<typename Type>
inline PIMathVector<Type> operator*(const PIMathVector<Type> &sv, inline PIMathVector<Type> operator*(const PIMathVector<Type> &sv,
const PIMathMatrix<Type> &fm) { const PIMathMatrix<Type> &fm) {
@@ -1260,13 +1502,16 @@ inline PIMathVector<Type> operator*(const PIMathVector<Type> &sv,
return tv; return tv;
} }
/** //! \~english
* \brief Multiplying value of type Type and matrix //! \brief Multiplying a value of type `Type` by a matrix.
* //! \param x first multiplier of type `Type`.
* @param x first multiplier of type Type //! \param v second matrix multiplier.
* @param v second matrix multiplier //! \return matrix that is the result of multiplication.
* @return matrix that is the result of multiplication //! \~russian
*/ //! \brief Умножение значения тип `Type` на матрицу.
//! \param x первый множитель типа `Type`.
//! \param v второй множитель-матрица.
//! \return матрица, являющаяся результатом умножения.
template<typename Type> template<typename Type>
inline PIMathMatrix<Type> operator*(const Type &x, const PIMathMatrix<Type> &v) { inline PIMathMatrix<Type> operator*(const Type &x, const PIMathMatrix<Type> &v) {
return v * x; return v * x;
@@ -1275,12 +1520,14 @@ inline PIMathMatrix<Type> operator*(const Type &x, const PIMathMatrix<Type> &v)
typedef PIMathMatrix<int> PIMathMatrixi; typedef PIMathMatrix<int> PIMathMatrixi;
typedef PIMathMatrix<double> PIMathMatrixd; typedef PIMathMatrix<double> PIMathMatrixd;
/** //! \~english
* \brief Searching hermitian matrix //! \brief Searching hermitian matrix.
* //! \param m conjugate transpose matrix.
* @param m conjugate transpose matrix //! \return result of the hermitian.
* @return result of the hermitian //! \~russian
*/ //! \brief Поиск эрмитовой матрицы.
//! \param m сопряженная транспонированная матрица.
//! \return результат преобразования.
template<typename T> template<typename T>
PIMathMatrix<complex<T> > hermitian(const PIMathMatrix<complex<T> > &m) { PIMathMatrix<complex<T> > hermitian(const PIMathMatrix<complex<T> > &m) {
PIMathMatrix<complex<T> > ret(m); PIMathMatrix<complex<T> > ret(m);

View File

@@ -27,6 +27,11 @@
//! \brief //! \brief
//! \~english Two-dimensional point class //! \~english Two-dimensional point class
//! \~russian Класс двумерной точки //! \~russian Класс двумерной точки
//! \details
//! Данный класс позволяет хранить и работать с двумерными точками.
//! Для работы с объектами реализованы операторы сложения, вычитания и проверки на ревенство и неравенство.
//! Также доступны методы для перемещения точек \a translate(), \a translated(), \a move(), \a moved()
//! и перевода из декартовой системы координат в полярную \a toPolar() и обратно \a fromPolar().
template<typename Type> template<typename Type>
class PIP_EXPORT PIPoint { class PIP_EXPORT PIPoint {
static_assert(std::is_arithmetic<Type>::value, "Type must be arithmetic"); static_assert(std::is_arithmetic<Type>::value, "Type must be arithmetic");
@@ -34,112 +39,118 @@ public:
Type x; Type x;
Type y; Type y;
//! //! \~russian Создает новую точку.
PIPoint() {x = y = Type();} PIPoint() {x = y = Type();}
//! //! \~russian Создает новую точку с заданными координатами.
PIPoint(Type x_, Type y_) {set(x_, y_);} PIPoint(Type x_, Type y_) {set(x_, y_);}
//! //! \~russian Задать новые координаты точке.
PIPoint<Type> & set(Type x_, Type y_) { PIPoint<Type> & set(Type x_, Type y_) {
x = x_; x = x_;
y = y_; y = y_;
return *this; return *this;
} }
//! //! \~russian Задать новые координаты точке.
PIPoint<Type> & set(const PIPoint<Type> & p) { PIPoint<Type> & set(const PIPoint<Type> & p) {
x = p.x; x = p.x;
y = p.y; y = p.y;
return *this; return *this;
} }
//! //! \~russian Переместить точку.
PIPoint<Type> & translate(Type x_, Type y_) { PIPoint<Type> & translate(Type x_, Type y_) {
x += x_; x += x_;
y += y_; y += y_;
return *this; return *this;
} }
//! //! \~russian Переместить точку.
PIPoint<Type> & translate(const PIPoint<Type> & p) { PIPoint<Type> & translate(const PIPoint<Type> & p) {
x += p.x; x += p.x;
y += p.y; y += p.y;
return *this; return *this;
} }
//! //! \~russian Создать копию точки и переместить её.
PIPoint<Type> translated(Type x_, Type y_) const { PIPoint<Type> translated(Type x_, Type y_) const {
PIPoint<Type> rp(*this); PIPoint<Type> rp(*this);
rp.translate(x_, y_); rp.translate(x_, y_);
return rp; return rp;
} }
//! //! \~russian Создать копию точки и переместить её.
PIPoint<Type> translated(const PIPoint<Type> & p) const { PIPoint<Type> translated(const PIPoint<Type> & p) const {
PIPoint<Type> rp(*this); PIPoint<Type> rp(*this);
rp.translate(p); rp.translate(p);
return rp; return rp;
} }
//! //! \~russian Переместить точку.
//! \details Является копией метода \a translate().
PIPoint<Type> & move(Type x_, Type y_) {return translate(x_, y_);} PIPoint<Type> & move(Type x_, Type y_) {return translate(x_, y_);}
//! //! \~russian Переместить точку.
//! \details Является копией метода \a translate().
PIPoint<Type> & move(const PIPoint<Type> & p) {return translate(p);} PIPoint<Type> & move(const PIPoint<Type> & p) {return translate(p);}
//! //! \~russian Создать копию точки и переместить её.
//! \details Является копией метода \a translated().
PIPoint<Type> moved(Type x_, Type y_) const { PIPoint<Type> moved(Type x_, Type y_) const {
PIPoint<Type> rp(*this); PIPoint<Type> rp(*this);
rp.translate(x_, y_); rp.translate(x_, y_);
return rp; return rp;
} }
//! //! \~russian Создать копию точки и переместить её.
//! \details Является копией метода \a translated().
PIPoint<Type> moved(const PIPoint<Type> & p) const { PIPoint<Type> moved(const PIPoint<Type> & p) const {
PIPoint<Type> rp(*this); PIPoint<Type> rp(*this);
rp.translate(p); rp.translate(p);
return rp; return rp;
} }
//! //! \~russian Посчитать угол(радианы) в поолярной системе координат.
double angleRad() const {return atan2(y, x);} double angleRad() const {return atan2(y, x);}
//! //! \~russian Посчитать угол(градусы) в поолярной системе координат.
double angleDeg() const {return toDeg(atan2(y, x));} double angleDeg() const {return toDeg(atan2(y, x));}
//! //! \~russian Перевести копию точки в полярную систему координат.
PIPoint<Type> toPolar(bool isDeg = false) const {return PIPoint<Type>(sqrt(x*x + y*y), isDeg ? angleDeg() : angleRad());} PIPoint<Type> toPolar(bool isDeg = false) const {return PIPoint<Type>(sqrt(x*x + y*y), isDeg ? angleDeg() : angleRad());}
//! //! \~russian Перевести копию точки из полярной системы координат в декартовую.
static PIPoint<Type> fromPolar(const PIPoint<Type> & p) {return PIPoint<Type>(p.y * cos(p.x), p.y * sin(p.x));} static PIPoint<Type> fromPolar(const PIPoint<Type> & p) {return PIPoint<Type>(p.y * cos(p.x), p.y * sin(p.x));}
//! //! \~russian
//! Прибавить координаты второй точки и сохранить.
//! \details Является копией метода \a translate().
void operator +=(const PIPoint<Type> & p) {translate(p);} void operator +=(const PIPoint<Type> & p) {translate(p);}
//! //! \~russian Сложить координаты двух точек.
PIPoint<Type> operator +(const PIPoint<Type> & p) {return PIPoint<Type>(x + p.x, y + p.y);} PIPoint<Type> operator +(const PIPoint<Type> & p) {return PIPoint<Type>(x + p.x, y + p.y);}
//! //! \~russian Прибавить к координатам одинаковое значение.
PIPoint<Type> operator +(const Type & p) {return PIPoint<Type>(x + p, y + p);} PIPoint<Type> operator +(const Type & p) {return PIPoint<Type>(x + p, y + p);}
//! //! \~russian Вычесть из координат координаты второй точки - найти смещение.
PIPoint<Type> operator -(const PIPoint<Type> & p) {return PIPoint<Type>(x - p.x, y - p.y);} PIPoint<Type> operator -(const PIPoint<Type> & p) {return PIPoint<Type>(x - p.x, y - p.y);}
//! //! \~russian Вычесть из координат одинаковое значение.
PIPoint<Type> operator -(const Type & p) {return PIPoint<Type>(x - p, y - p);} PIPoint<Type> operator -(const Type & p) {return PIPoint<Type>(x - p, y - p);}
//! //! \~russian Инвертировать координаты точки.
PIPoint<Type> operator -() {return PIPoint<Type>(-x, -y);} PIPoint<Type> operator -() {return PIPoint<Type>(-x, -y);}
//! //! \~russian Проверить равенство координат двух точек.
bool operator ==(const PIPoint<Type> & p) const {return (x == p.x && y == p.y);} bool operator ==(const PIPoint<Type> & p) const {return (x == p.x && y == p.y);}
//! //! \~russian Проверить неравенство координат двух точек.
bool operator !=(const PIPoint<Type> & p) const {return (x != p.x || y != p.y);} bool operator !=(const PIPoint<Type> & p) const {return (x != p.x || y != p.y);}
}; };
//! \~russian Перегруженный оператор для вывода координат в \a PICout.
template<typename Type> template<typename Type>
PICout operator <<(PICout & s, const PIPoint<Type> & v) { PICout operator <<(PICout & s, const PIPoint<Type> & v) {
s.setControl(0, true); s.setControl(0, true);