Matrix extend functions and made hadamard return a Matrix

This commit is contained in:
LeLeLeLeto 2024-12-31 17:22:20 +01:00
parent fb49c794b2
commit 922321e9cb

View File

@ -9,9 +9,8 @@
#define assertm(exp, msg) assert((void(msg), exp)) #define assertm(exp, msg) assert((void(msg), exp))
class Matrix{ class Matrix{
private:
std::vector<std::vector<float>> values;
public: public:
std::vector<std::vector<float>> values;
inline void Randomize(); inline void Randomize();
inline void Randomize(float, float); inline void Randomize(float, float);
@ -22,7 +21,7 @@ class Matrix{
inline Matrix Multiply(float); inline Matrix Multiply(float);
inline Matrix Multiply(const Matrix*); inline Matrix Multiply(const Matrix*);
inline void Hadamard(const Matrix*); inline Matrix Hadamard(const Matrix*);
inline Matrix Add(float); inline Matrix Add(float);
inline Matrix Add(const Matrix*); inline Matrix Add(const Matrix*);
@ -32,6 +31,9 @@ class Matrix{
inline Matrix Function(float (*f)(float)); inline Matrix Function(float (*f)(float));
inline Matrix ExtendRight(int);
inline Matrix ExtendDown(int);
inline void Print(std::string_view); inline void Print(std::string_view);
inline Matrix Transpose(); inline Matrix Transpose();
@ -56,6 +58,28 @@ Matrix::Matrix(){
} }
Matrix Matrix::ExtendRight(int new_size){
// Extend the matrix to the right
Matrix result(this->values.size(), new_size);
for(int n = 0; n < result.values.size(); n++){
for(int m = 0; m < result.values[n].size(); m++){
result.values[n][m] = this->values[n][0];
}
}
return result;
}
Matrix Matrix::ExtendDown(int new_size){
// Extend the matrix down
Matrix result(new_size, this->values[0].size());
for(int n = 0; n < result.values.size(); n++){
for(int m = 0; m < result.values[n].size(); m++){
result.values[n][m] = this->values[0][m];
}
}
return result;
}
Matrix Matrix::operator=(const Matrix* other){ Matrix Matrix::operator=(const Matrix* other){
return this->Swap(other); return this->Swap(other);
} }
@ -115,16 +139,18 @@ Matrix Matrix::Swap(const Matrix* other){
return *this; return *this;
} }
void Matrix::Hadamard(const Matrix* other){ Matrix Matrix::Hadamard(const Matrix* other){
// Matrices need to be the same size // Matrices need to be the same size
assertm(this->values.size() == other->values.size() && assertm(this->values.size() == other->values.size() &&
this->values[0].size() == other->values[0].size(), this->values[0].size() == other->values[0].size(),
"Matrices need to be the same size"); "Matrices need to be the same size");
for(int m = 0; m < this->values.size(); m++){ Matrix result = this;
for(int n = 0; n < this->values[m].size(); n++){ for(int m = 0; m < result.values.size(); m++){
this->values[m][n] *= other->values[m][n]; for(int n = 0; n < result.values[m].size(); n++){
result.values[m][n] = this->values[m][n] * other->values[m][n];
} }
} }
return result;
} }
// Multiply 2 matrices (AxB = this x other) // Multiply 2 matrices (AxB = this x other)