1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
|
#include <vector>
#include <cmath>
#include <cassert>
#include <iostream>
#include <random>
template<typename Type>
class Matrix {
std::vector<std::vector<Type>> data;
public:
const size_t cols {};
const size_t rows {};
const size_t elementCount {};
Matrix(size_t rowsArg, size_t colsArg) : cols(colsArg), rows(rowsArg), elementCount(rowsArg * colsArg),
data(std::vector<std::vector<Type>>(rowsArg, std::vector<Type>(colsArg))) {}
Matrix() {}
void print() const;
Matrix<Type> matmul(const Matrix<Type>& m) const;
Type& operator()(size_t row, size_t col) {
assert(row < data.size() && col < data[0].size());
return data[row][col];
}
Type operator()(size_t row, size_t col) const {
assert(row < data.size() && col < data[0].size());
return data[row][col];
}
};
template<typename Type>
void Matrix<Type>::print() const {
for (const auto& r : data) {
for (const auto& e : r)
std::cout << e << ' ';
std::cout << '\n';
}
std::cout << '\n';
}
template <typename Type>
Matrix<Type> Matrix<Type>::matmul(const Matrix<Type>& target) const {
assert(cols == target.rows);
Matrix output(rows, target.cols);
for (size_t r {}; r < output.rows; ++r) {
for (size_t c {}; c < output.cols; ++c)
for (size_t k {}; k < target.rows; ++k)
output(r, c) += (r, k) * target(k, c);
}
return output;
};
template <typename T>
struct mtx {
static inline std::mt19937 gen { std::random_device {}() };
static Matrix<T> randn(size_t rows, size_t cols) {
Matrix<T> M(rows, cols);
const T stdev { 1.0 / std::sqrt(static_cast<T>(M.elementCount)) };
std::normal_distribution<T> d { 0, stdev };
for (size_t r {}; r < rows; ++r)
for (size_t c {}; c < cols; ++c)
M(r, c) = d(gen);
return M;
}
};
int main() {
const auto A { mtx<double>::randn(2, 3) };
const auto B { mtx<double>::randn(3, 2) };
A.print();
B.print();
A.matmul(B).print();
}
|