SYCL_MatMul/matrix.hpp
2023-10-02 09:51:49 +02:00

74 lines
1.6 KiB
C++

#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_