/
lyapdy
/
skillbox_controllers
Обзор
Документация
Войти
/
lyapdy
/
skillbox_controllers
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
Project7/src/matrix.cpp
129 строк
3 KB
danillyapunov
Second commit
09 дек 2025, 18:41
09 дек 2025, 18:41
2c9c8f9
Код
Авторство
О чём код?
#include "matrix.h" #include <iostream> #include <cmath> using namespace math; real& Matrix::operator()(int row, int col) { if (row >= this->rows_) { std::cerr << "Matrix row number out of bounds" << std::endl; // return 0; } if (col >= this->cols_) { std::cerr << "Matrix column number out of bounds" << std::endl; // return 0; } int pos{0}; pos = cols_ * row + col; return this->mvec_.at(pos); } real Matrix::operator()(int row, int col) const { if (row >= this->rows_) { std::cerr << "Matrix row number out of bounds" << std::endl; // return 0; } if (col >= this->cols_) { std::cerr << "Matrix column number out of bounds" << std::endl; // return 0; } int pos{0}; pos = cols_ * row + col; return this->mvec_.at(pos); } void Matrix::print() const { for (int i = 0; i < this->rows_; ++i) { for (int j = 0; j < this->cols_; ++j) { std::cout << this->mvec_.at(cols_ * i + j) << " "; } std::cout << std::endl; } } Matrix math::operator+(const Matrix &A, const Matrix &B) { if ((A.cols_ != B.cols_) || (A.rows_ != B.rows_)) { std::cerr << "Matrix: Matrices can't be added!" << std::endl; return Matrix(0, 0); } Matrix M(A.cols_, A.rows_); for (int i = 0; i < M.mvec_.size(); ++i) { M.mvec_.at(i) = A.mvec_.at(i) + B.mvec_.at(i); } return M; } Matrix math::operator-(const Matrix &A, const Matrix &B) { if ((A.cols_ != B.cols_) || (A.rows_ != B.rows_)) { std::cerr << "Matrix: Matrices can't be subtracted!" << std::endl; return Matrix(0, 0); } Matrix M(A.cols_, A.rows_); for (int i = 0; i < M.mvec_.size(); ++i) { M.mvec_.at(i) = A.mvec_.at(i) - B.mvec_.at(i); } return M; } Matrix math::operator*(const Matrix &A, const Matrix &B) { if(A.cols_ != B.rows_) { std::cerr << "Matrix: Matrices can't be multiplied!" << std::endl; return Matrix(0,0); } Matrix M(A.rows_, B.cols_); for(int pos = 0; pos < M.mvec_.size(); ++pos) { int row = (int)std::floor((double)pos/M.cols_); int col = pos - row * M.cols_; for (int k = 0; k<A.cols_;++k) M.mvec_.at(pos) += A(row,k)*B(k,col); } return M; } // int main() // { // math::Matrix A(2, 3); // math::Matrix B(2, 3); // // Initialize test matrices // A(0, 0) = 1; A(0, 1) = 2; A(0, 2) = 3; // A(1, 0) = 4; A(1, 1) = 5; A(1, 2) = 6; // B(0, 0) = 1; B(0, 1) = 1; B(0, 2) = 1; // B(1, 0) = 1; B(1, 1) = 1; B(1, 2) = 1; // std::cout << "Matrix A:" << std::endl; // A.print(); // std::cout << "\nMatrix B:" << std::endl; // B.print(); // math::Matrix C = A + B; // std::cout << "\nA + B:" << std::endl; // C.print(); // return 0; // }