From 8418342bf7c031c135ab95059b793aec9839a9a3 Mon Sep 17 00:00:00 2001 From: Leto Date: Mon, 23 Dec 2024 21:24:53 +0100 Subject: [PATCH] Added Adding and Substracting matrices --- main.cpp | 16 +++++++++++----- matrices.h | 42 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 53 insertions(+), 5 deletions(-) diff --git a/main.cpp b/main.cpp index 60b2481..ab8b16e 100644 --- a/main.cpp +++ b/main.cpp @@ -6,10 +6,16 @@ int main() { srand(time(0)); - Matrix test(3,2); - test.Randomize(); - test.Print(""); - test.Transpose(); - test.Print(""); + Matrix a(3,3); + Matrix b(3,3); + + a.Randomize(); + b.Randomize(); + + a.Print("A"); + b.Print("B"); + a.Add(&b); + a.Print("A+B"); + return 0; } \ No newline at end of file diff --git a/matrices.h b/matrices.h index 244bdb5..fba4ad9 100644 --- a/matrices.h +++ b/matrices.h @@ -1,5 +1,8 @@ #include #include +#include + +#define assertm(exp, msg) assert((void(msg), exp)) class Matrix{ private: @@ -13,6 +16,10 @@ class Matrix{ void Factor(float); void Add(float); + void Add(Matrix*); + + void Sub(float); + void Sub(Matrix*); void Print(std::string_view); @@ -33,6 +40,32 @@ Matrix::Matrix(int rows, int cols){ } } +// Add 2 matrices +void Matrix::Add(Matrix* other){ + // Matrices need to be the same size + assertm(this->values.size() == other->values.size() && + this->values[0].size() == other->values[0].size(), + "Matrices need to be the same size"); + for(int m = 0; m < this->values.size(); m++){ + for(int n = 0; n < this->values[m].size(); n++){ + this->values[m][n] += other->values[m][n]; + } + } +} + +// Substract 2 matrices +void Matrix::Sub(Matrix* other){ + // Matrices need to be the same size + assertm(this->values.size() == other->values.size() && + this->values[0].size() == other->values[0].size(), + "Matrices need to be the same size"); + for(int m = 0; m < this->values.size(); m++){ + for(int n = 0; n < this->values[m].size(); n++){ + this->values[m][n] -= other->values[m][n]; + } + } +} + // Print a matrix in terminal, with a title void Matrix::Print(std::string_view titre){ std::cout << titre << std::endl; @@ -54,6 +87,15 @@ void Matrix::Add(float value){ } } +// Substract a constant value to every matrix case +void Matrix::Sub(float value){ + for(int m = 0; m < this->values.size(); m++){ + for(int n = 0; n < this->values[m].size(); n++){ + this->values[m][n] -= value; + } + } +} + // Multiply every matrix case by a given factor void Matrix::Factor(float value){ for(int m = 0; m < this->values.size(); m++){