provide matrix struct with basic operations
This commit is contained in:
parent
db765fff8d
commit
6698c82691
73
matrix.hpp
Normal file
73
matrix.hpp
Normal file
@ -0,0 +1,73 @@
|
||||
#ifndef MATRIX_H_
|
||||
#define MATRIX_H_
|
||||
|
||||
#include <cstdint>
|
||||
#include <fstream>
|
||||
#include <iostream>
|
||||
#include <numeric>
|
||||
#include <vector>
|
||||
|
||||
template <class T> struct Matrix {
|
||||
std::uint32_t rows;
|
||||
std::uint32_t cols;
|
||||
std::vector<T> data;
|
||||
|
||||
Matrix<T>(std::uint32_t _rows, std::uint32_t _cols)
|
||||
: rows(_rows), cols(_cols) {
|
||||
data.resize(rows * cols);
|
||||
}
|
||||
|
||||
Matrix<T>(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<T> &operator=(const Matrix<T> &mat) {
|
||||
this->rows = mat.rows;
|
||||
this->cols = mat.cols;
|
||||
this->data = data;
|
||||
|
||||
return *this;
|
||||
}
|
||||
|
||||
Matrix<T> t() const {
|
||||
Matrix<T> 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 <class T> std::ostream &operator<<(std::ostream &os, Matrix<T> &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_
|
||||
Loading…
x
Reference in New Issue
Block a user