From 6698c826917486775f8218ddbd62915df9ba132e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Max=20L=C3=BCbke?= Date: Mon, 2 Oct 2023 09:51:49 +0200 Subject: [PATCH] provide matrix struct with basic operations --- matrix.hpp | 73 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 73 insertions(+) create mode 100644 matrix.hpp diff --git a/matrix.hpp b/matrix.hpp new file mode 100644 index 0000000..a4aedab --- /dev/null +++ b/matrix.hpp @@ -0,0 +1,73 @@ +#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_