1
0
forked from leto/LeMA

Added Adding and Substracting matrices

This commit is contained in:
Leto 2024-12-23 21:24:53 +01:00
parent e53df84e46
commit 8418342bf7
2 changed files with 53 additions and 5 deletions

View File

@ -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;
}

View File

@ -1,5 +1,8 @@
#include <string>
#include <vector>
#include <cassert>
#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++){