Dot Product of Two Matrices

Hello!

I have written a function two dot multiply a 3x3 matrix and another 3x3 matrix. But, for some reason, it gives garbage output…
Here’s the function:

void TransformMatrix::dot(float other[3][3]){
	float newMatrix[3][3];
	for(byte i=0;i<3;i++){//For each row of matrix a...
		for(byte j=0;j<3;j++){//For each column of matrix b...
			for(byte k=0;k<3;k++)//For each cell...
				newMatrix[j][i]+=matrix[k][i]*other[j][k];
		}
	}
	memcpy(&matrix,&newMatrix,sizeof(matrix));//Copy newMatrix over old matrix;
	isUnit=false;//probably.
}

However, I ran this test:

1 0 0
0 1 0
0 0 1

DOT

1 0 0
0 1 0
0 0 1

and got:

1 1.98 1.97
0 1 0
0 -170141183460469269661530233861412853002.54 1

Which is, clearly, not correct.

What am I doing wrong?
(Sorry if it’s something silly, I’m just learning this stuff today)

Thanks!

Where is newMatrix zeroed?

It doesn't initialize to a 0-filled matrix?

No - should "it"?

Welp, that fixes it. How strange!
Thank you, I would’ve never thought of that.

new code:

void TransformMatrix::dot(float other[3][3]){
	float newMatrix[3][3];
	memset(&newMatrix,0.0,sizeof(newMatrix));
	for(byte i=0;i<3;i++){//For each row of matrix a...
		for(byte j=0;j<3;j++){//For each column of matrix b...
			for(byte k=0;k<3;k++)//For each cell...
				newMatrix[j][i]+=matrix[k][i]*other[j][k];
		}
	}
	memcpy(&matrix,&newMatrix,sizeof(matrix));//Copy newMatrix over old matrix;
	isUnit=false;//probably.
}

You would've thought of it, if you'd added some debug prints.

Fuzzyzilla:
Welp, that fixes it. How strange!
Thank you, I would’ve never thought of that.

new code:

void TransformMatrix::dot(float other[3][3]){
float newMatrix[3][3];
memset(&newMatrix,0.0,sizeof(newMatrix));
for(byte i=0;i<3;i++){//For each row of matrix a...
	for(byte j=0;j<3;j++){//For each column of matrix b...
		for(byte k=0;k<3;k++)//For each cell...
			newMatrix[j][i]+=matrix[k][i]*other[j][k];
	}
}
memcpy(&matrix,&newMatrix,sizeof(matrix));//Copy newMatrix over old matrix;
isUnit=false;//probably.

}

Local primitive* variables are not initialized in C++. Whatever value that was in that memory location before is not overwritten, so you can’t assume any initial value. You must explicitly initialize them. This is one of the major traps for new people, along with its case sensitivity.

  • The primitive types in C++ are: char, int, float, double, bool, and void. This includes the types of int modified with the keywords short, long, signed, or unsigned.