Hello all I'm trying to write a simple matrix math library using structs to represent my vectors and matrices. While trying to write my matrix dot product function I decided to override the "*" operator I've encountered a rather peculiar bug, I've quite a lot of time trying to figure it out for about 4 hours and am completely stuck on the matter. the code is as follows. I've redacted a fair amount code and have found the problem area.
struct matrix {
private:
float* _mat;
int width, height, Size;
public:
float* T;
matrix(int _width, int _height) : _mat(new float[(_width * _height)]), width(_width), height(_height), Size(_height* _width) {}
matrix() = default;
void setIndex(int col, int row, float val) {
if (col > this->width || row > this->height) {
return;
}
_mat[(this->width * row) + col] = val;
//this->Transposition();
}
float getIndex(int col, int row) const {
if (col > this->width || row > this->height) {
return;
}
return this->_mat[(this->width * row) + col];
}
int getWidth()const{
return this->width;
}
int getHeight()const{
return this->height;
}
matrix operator*(const matrix& _exMat) const {
if(this->getWidth() != _exMat.getHeight()){
return;
}
matrix resultMat(_exMat.getWidth(), this->getHeight());
for (int i = 0; i < resultMat.getHeight(); i++) {
for (int j = 0; j < resultMat.getWidth(); j++) {
float sum = 0.0f;
for (int k = 0; k < this->getWidth(); k++) {
//Get index col row
sum += this->getIndex(k, i) * _exMat.getIndex(j, k);
}
//problem area here, honestly stuck println is for debugging
Serial.print(sum);
Serial.print(", ");
Serial.print(j);
Serial.print(", ");
Serial.println(i);
resultMat.setIndex(j, i, sum);
Serial.println(resultMat.getIndex(j,i));
}
}
return resultMat;
}
}
then in my .ino file I have
#include "matrix.h"
linear::matrix mat(2,2);
linear::matrix mat1(2,2);
linear::matrix mat2(2,2);
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
Serial.println("");
unsigned long startTime = millis();
linear::Matrix matHandler;
//linear::vector vec(2);
//col row val
mat.setIndex(0, 0, 1);
mat.setIndex(1, 0, 2);
mat.setIndex(0, 1, 3);
mat.setIndex(1, 1, 4);
mat1.setIndex(0, 0, 1);
mat1.setIndex(1, 0, 1);
mat1.setIndex(0, 1, 1);
mat1.setIndex(1, 1, 1);
mat2 = linear::matrix(mat * mat1);
unsigned long endTime = millis();
unsigned long elapsedTime = endTime - startTime;
// Print the time taken
Serial.print("Time taken: ");
Serial.print(elapsedTime);
Serial.println(" milliseconds");
Serial.println("metrix dot product: ");
matHandler._print(&mat2);
}
void loop(){}
and the output of my code to the console is

the desired output however should be 3,3
7,7
which is not what we get. I am completely stuck on this problem. I do apologise for the poor code quality too as of current I'm just trying to get the code working then working on tidying up later. If anyone could help I'd so grateful as I really am quite stuck. Many thanks ![]()
edit: matHandler isn't the source of the problem I checked and it works as intended.