Matlab is able to distinguish between ‘proper’ matrix multiplication and element-wise matrix multiplication with different operators, so that the former is done as A * B and the latter as A .* B. This is pretty convenient and I was wondering if there was a way to achieve the same thing in C++ for a custom matrix class (and likewise for ./ and .^). That is, I was wondering if it is possible, through defining macros or any other method, to have something like the following actually compile:
MyMatrix A(2,3), B(2,3), C(2,3); //These are 2x3 matrices for the sake of concreteness
C = A .* B; //Similarly for ./, .^
I tried doing this with some simple function #defines and couldn’t get it to work, so I figured I’d put it to SO. I can accept ‘near misses’, i.e. if .* can’t work but somehow :* can, good enough. NB, I’m specifically looking for operators–of course, this behavior can be accomplished with functions in the obvious way but Matlab-like operators would be pretty convenient.
Not that I’m really suggesting this be done (it’s an abomination). You could, say, create a small wrapper class, that when multiplied by a matrix performs an elementwise multiplication. Then give the matrix class a
element_wise()method, which returns such a wrapper. Then, you cold “create” operators_*,_/, etc:Or keep the preprocessor out of it, by giving each matrix such a wrapper at construction and calling it
_, thus allowing: