Question

In mathematics, if three matrices, 'A', 'B' and 'C' are multiplied, such that a fourth matrix 'D = A * B * C', then the order must be computed right to left. Using parentheses to clarify, the previous statement is exactly equivalent to the following; 'D = (A * (B * C))'.

You can see how this applies for the expression '{ M = A * B * C * D } == { M = (A * (B * (C * (D)))) }', which is another example.

In C, C++, I ran a test using division to check the order in which operations are done in C and C++.

There is probably a better way of doing this my compiling assembly code, however:

float a = 1.0;
float b = 2.0;
float c = 2.0;
float ans = a / b / c;
printf("answer is %f\n", ans);

This gives the output:

answer is 0.25

This suggests to me that if I were to create a class to represent a matrix, then the order of multiplication would be left to right, the reverse of what is desired, since the example with floating point operations and division is evaluated left to right since the three operations have equal precedence.

In the OpenGL Mathematics library, GLM, matrix operations are computed in the correct order, without the requirement for parentheses.

How is operator*() made to behave in this way?

Edit

Err, yeah, so it doesn't actually matter as it has been pointed out to me. In which case my question becomes "is it possible to change the order"? (Maybe I am sleepy?)

Was it helpful?

Solution

The C++ / and binary * operators are both left-to-right associative. End of story - there's no way to change that.

Matrix multiplication is associative, though, so that shouldn't affect you.

OTHER TIPS

The reason is simple: matrix multiplication is associative; scalar division is not. (A / (B / C)) is not the same as ((A / B) / C). But (A * (B * C)) is the same as ((A * B) * C), for both matrix and scalar multiplication.

So the order that C++ calls operators in just doesn't matter for matrix multiplication.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top