From b919f4a24983a72e953843e33fc30165a505f828 Mon Sep 17 00:00:00 2001 From: Leto Date: Tue, 24 Dec 2024 14:17:08 +0100 Subject: [PATCH] Added - operator --- main.cpp | 4 ++-- matrices.h | 32 ++++++++++++++++++++++---------- 2 files changed, 24 insertions(+), 12 deletions(-) diff --git a/main.cpp b/main.cpp index 3f21ff6..69c991d 100644 --- a/main.cpp +++ b/main.cpp @@ -12,8 +12,8 @@ int main() a.Print("A"); b.Print("B"); - Matrix result = a + &b; - result.Print("A + B"); + Matrix result = a - &b; + result.Print("A - B"); return 0; } \ No newline at end of file diff --git a/matrices.h b/matrices.h index 7b043d6..e8dbca2 100644 --- a/matrices.h +++ b/matrices.h @@ -24,8 +24,8 @@ class Matrix{ inline Matrix Add(float); inline Matrix Add(const Matrix*); - inline void Substract(float); - inline void Substract(const Matrix*); + inline Matrix Substract(float); + inline Matrix Substract(const Matrix*); inline void Print(std::string_view); @@ -35,6 +35,7 @@ class Matrix{ // Assign inline Matrix operator=(const Matrix*); inline Matrix operator+(const Matrix*); + inline Matrix operator-(const Matrix*); // Constructors inline Matrix(int, int); @@ -49,6 +50,10 @@ Matrix Matrix::operator+(const Matrix* other){ return this->Add(other); } +Matrix Matrix::operator-(const Matrix* other){ + return this->Substract(other); +} + // Constructs a zero matrix Matrix::Matrix(int rows, int cols){ for(int m = 0; m < rows; m++){ @@ -118,16 +123,21 @@ Matrix Matrix::Add(const Matrix* other){ } // Substract 2 matrices -void Matrix::Substract(const Matrix* other){ +Matrix Matrix::Substract(const Matrix* other){ // Matrices need to be the same size assertm(this->values.size() == other->values.size() && this->values[0].size() == other->values[0].size(), "Wrong matrix 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]; + + Matrix result = this; + + for(int m = 0; m < result.values.size(); m++){ + for(int n = 0; n < result.values[m].size(); n++){ + result.values[m][n] -= other->values[m][n]; } } + + return result; } // Print a matrix in terminal, with a title @@ -154,12 +164,14 @@ Matrix Matrix::Add(float value){ } // Substract a constant value to every matrix case -void Matrix::Substract(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; +Matrix Matrix::Substract(float value){ + Matrix result = this; + for(int m = 0; m < result.values.size(); m++){ + for(int n = 0; n < result.values[m].size(); n++){ + result.values[m][n] -= value; } } + return result; } // Multiply every matrix case by a given factor