Trouble Multiplying Matrices

Hello everyone, new to this site.

Basically, I am trying to multiply 2 4x4 matrices in the following form:
AB and BA.

Now, I think I managed to get it to multiply in the form of AB:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
Matrix& Multiply(Matrix& A, Matrix& B, Matrix& ResultantMatrix)
{
	for (int i = 0; i < 4; ++i) 
	{
		for (int j = 0; j < 4; ++j)
		{
			for (int k = 0; k < 4; ++k) 
			{
				ResultantMatrix[i][j] += A[i][k] * B[k][j];
			}
		}
	}
	return ResultantMatrix;
}


However, I am having trouble figuring out how to multiply it in the form of BA, here is my attempt:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Matrix& MultiplyBandA(Matrix& A, Matrix& B, Matrix& ResultantMatrix)
{
	Matrix A;
	for (int i = 0; i < 4; ++i) 
	{
		for (int j = 0; j < 4; ++j)
		{
			for (int k = 0; k < 4; ++k) 
			{
				ResultantMatrix[i][j] += A[i][k] * B[k][j];
				ResultantMatrix.Transpose(ResultantMatrix, A);
			}
		}
	}
	return A;
}


Can anyone spot what I'm doing wrong?

Thank you!
Basically what's happening currently, the BA multiplication is returning 0's. I have checked my transpose over and over and it works fine, so it cannot be from the transpose, however, I think I may have gotten the wrong logic here. I have a feeling that there's a simple solution to this but I can't seem to be able to figure it out myself :'(
Maima,

Why do you want to write TWO different functions to do the same mathematical operation? The whole idea of functions is that they are re-usable for different parameters: in this case, just the parameters in reverse order.

Also, if you want to return a result, either do it through the value of the function OR as a (reference) argument - don't do both.


As the return value of the function:-
If you want AB then
C = Multiply( A, B );

If you want BA then
C = Multiply( B, A );


If you prefer your result to be a function argument instead, then just:-
For AB then:
Multiply( A, B, C );

For BA then:
Multiply( B, A, C );


You have to decide which of these routes to take and write your function accordingly.
Second snippet
Line 3: Why are you declaring A here? This creates a local variable (empty matrix) which hides the argument A on line 1.

Line 15: You're returning a reference to a local variable. The local variable A goes out of scope when the function exits meaning the reference is no longer valid.

Thank you guys. :)
Topic archived. No new replies allowed.