#ifndef MATRIX_H_ #define MATRIX_H_ #include #include #include #include #include template struct Matrix { std::uint32_t rows; std::uint32_t cols; std::vector data; Matrix(std::uint32_t _rows, std::uint32_t _cols) : rows(_rows), cols(_cols) { data.resize(rows * cols); } Matrix(const char *filepath) { std::ifstream matfs(filepath); if (matfs.fail() || !matfs.is_open()) { throw std::runtime_error("Error opening matrix file"); } matfs >> this->rows >> this->cols; this->data.resize(this->rows * this->cols); for (std::uint32_t i = 0; i < rows; i++) { for (std::uint32_t j = 0; j < cols; j++) { matfs >> (*this)(j, i); } } matfs.close(); } T &operator()(std::uint32_t x, std::uint32_t y) { return data[y * cols + x]; } Matrix &operator=(const Matrix &mat) { this->rows = mat.rows; this->cols = mat.cols; this->data = data; return *this; } Matrix t() const { Matrix transposed = *this; for (std::uint32_t i = 0; i < this->rows; i++) { for (std::uint32_t j = 0; j < this->cols; j++) { transposed(i, j) = (*this)(j, i); } } return transposed; } T sum() const { return std::accumulate(data.begin(), data.end(), 0); } }; template std::ostream &operator<<(std::ostream &os, Matrix &mat) { for (std::uint32_t i = 0; i < mat.rows; i++) { for (std::uint32_t j = 0; j < mat.cols; j++) { os << mat(j, i) << "\t"; } os << "\n"; } return os; } #endif // MATRIX_H_