20 template <
typename _Scalar,
typename _Dim>
34 Matrix(_Dim rows, _Dim columns, _Scalar val = 0) : _rows(rows), _cols(columns) {
35 _data =
new _Scalar[rows * columns];
44 if (_data) {
delete [] _data; }
45 if (_rows * _cols != 0) {
46 _data =
new _Scalar[_rows * _cols];
47 for (_Dim r = 0; r < _rows; ++r) {
48 for (_Dim c = 0; c < _cols; ++c) {
49 _data[r * _cols + c] = other._data[r * _cols + c];
64 void fill(_Scalar val = 0) {
65 for (_Dim r = 0; r < _rows; ++r) {
66 for (_Dim c = 0; c < _cols; ++c) {
67 _data[r * _cols + c] = val;
76 if (_data) {
delete [] _data; }
77 if (_rows * _cols != 0) {
78 _data =
new _Scalar[_rows * _cols];
79 for (_Dim r = 0; r < _rows; ++r) {
80 for (_Dim c = 0; c < _cols; ++c) {
81 _data[r * _cols + c] = other._data[r * _cols + c];
91 void resize(_Dim rows, _Dim columns) {
94 if (_data) {
delete [] _data; }
95 _data =
new _Scalar[_rows * _cols];
99 _Dim rows()
const {
return _rows; }
102 _Dim cols()
const {
return _cols; }
106 _Scalar& operator()(_Dim row, _Dim col) {
108 if (!(row >= 0 && row < _rows && col >= 0 && col < _cols)) {
throw(std::runtime_error(
"Rows / columns number check failed!")); }
110 return _data[row * _cols + col];
114 const _Scalar& operator()(_Dim row, _Dim col)
const {
116 if (!(row >= 0 && row < _rows && col >= 0 && col < _cols)) {
throw(std::runtime_error(
"Rows / columns number check failed!")); }
118 return _data[row * _cols + col];
123 bool operator==(
const Matrix &other)
const {
124 if (_rows != other._rows || _cols != other._cols) {
return false; }
126 for (_Dim r = 0; r < _rows; ++r) {
127 for (_Dim c = 0; c < _cols; ++c) {
128 if (_data[r * _cols + c] != other._data[r * _cols + c]) {
141 if (_cols != other._rows) {
throw(std::runtime_error(
"Multiplication of matrices with wrong dimensions!")); }
144 Matrix res(_rows, other._cols, 0);
145 for (_Dim i = 0; i < _rows; ++i) {
146 for (_Dim j = 0; j < other._cols; ++j) {
147 for (_Dim k = 0; k < _cols; ++k) {
148 res(i, j) += (*this)(i, k) * other(k, j);
157 Matrix operator*(
const _Scalar &val)
const {
159 for (_Dim i = 0; i < _rows; ++i) {
160 for (_Dim j = 0; j < _cols; ++j) {
161 res(i, j) = (*this)(i, j) * val;
168 size_t nonzeros()
const {
170 for (_Dim i = 0; i < _rows; ++i) {
171 for (_Dim j = 0; j < _cols; ++j) {
172 res += (*this)(i, j) != 0;
179 size_t zeros()
const {
181 for (_Dim i = 0; i < _rows; ++i) {
182 for (_Dim j = 0; j < _cols; ++j) {
183 res += (*this)(i, j) == 0;
190 std::string print()
const {
191 std::string res =
"";
192 for (
size_t i = 0; i < _rows; ++i) {
193 for (
size_t j = 0; j < _cols; ++j) {
194 res += std::to_string((*
this)(i, j)) +
"\t";
210 template <
typename _Scalar,
typename _Dim>
213 for (_Dim i = 0; i < rhs.rows(); ++i) {
214 for (_Dim j = 0; j < rhs.cols(); ++j) {
215 res(i, j) = rhs(i, j) * val;
223 #endif //YMIR_MATRIX_H
Simple matrix class.
Definition: matrix.h:21