Define Matlab-like. * operator in C ++?

Matlab is able to distinguish between โ€œcorrectโ€ matrix multiplication and matrix matrix multiplication by different operators, so that the former is executed as A * B , and the latter as A .* B This is pretty convenient, and I was wondering if there is a way to do the same in C ++ for a custom matrix class (as well as for ./ and .^ ). That is, I was wondering if it is possible, through the definition of macros or any other method, to have something like the following, actually compiled:

 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 to do this with the simple #define function and could not get it to work, so I decided that I would put it in SO. I can take "misses", i.e. If .* Can't work, but somehow :* maybe pretty good. NB, I am specifically looking for operators - of course, this behavior can be performed using functions in an obvious way, but Matlab-like operators would be quite convenient.

+4
source share
2 answers

Not that I really offered to do this (it's an abomination). You could, for example, create a small wrapper class so that when you multiply by a matrix, elemental multiplication is performed. Then we give a matrix method a element_wise() , which returns such a shell. Then you create the cold "create" statements _* , _/ , etc.:

 #define _ .element_wise() A = B _* C; // really B.element_wise() * C 

Or remove the preprocessor from it by providing each matrix with such a shell during construction and calling it _ , which will allow:

 A = B ._* C; B = A ._/ C; 
+2
source

Here is a technique that is similar to Managu's answer only without using macros ...

 struct Mat; struct EleWise { EleWise(){} double mat[3][3]; }; struct Mat { Mat(){} friend Mat operator / ( EleWise& e, const Mat& m ) { return Mat(); // perform elewise divide } EleWise _; }; int main( int argc, char** arg ) { Mat a; Mat b; Mat c = a ._/ b; return 0; }; 
+4
source

All Articles