3

I want to overload Times and Plus for matrix multiplication in mathematica, for example, let Times be BitAnd, and Plus be BitOr, then do the matrix multiplication.

Is there anyway to do this in a simple way, without rewriting my own matrix multiplication?

Thanks.

Qiang Li
  • 10,593
  • 21
  • 77
  • 148
  • Note that redefining built-in `Times` will break any Mathematica functions that expect standard behavior from `Times` on matrices. A safer alternative is to define `MyTimes` and use Notation package to give it own appearance and shortcut – Yaroslav Bulatov Mar 09 '11 at 21:18
  • 3
    Isn't the idea of overloading providing an operator functionality for additional data types? In this case, Times already is defined for matrices. So, do you want to lose this predefined meaning and overwrite this with the BitAnd and BitOr behaviors? Why don't you just use the latter functions? Or do you want to use their symbols? There are better solutions for that. – Sjoerd C. de Vries Mar 09 '11 at 21:19

1 Answers1

4

The question is what you want to alter - the behavior of Times and Plus, or Dot. Generally, Block trick is often the simplest way. In this case, since Dot does not call high-level Plus or Times, you can do:

mat1 = {{1,2},{3,4}};
mat2= {{5,6},{7,8}};
Block[{Dot = Inner[BitAnd,#1,#2,BitOr]&},
  mat1.mat2]

{{3,0},{5,2}}

But note that this is effectively re-implementing the matrix multiplication (using Inner) - there is no other way since Dot is implemented internally and does not use Plus or Times.

Leonid Shifrin
  • 22,449
  • 4
  • 68
  • 100
  • 5
    One should not under any circumstances overload Plus or Times. Leonid Shifrin's method would be a good way to go about this particular task. Though changing Dot inside Block is not really necessary for general usage, since you can just define myDot or some such. – Daniel Lichtblau Mar 09 '11 at 21:33
  • @Daniel Thanks for making this clear. I am guilty of having done that (overloading Times or Plus) a couple of times in the past (mostly when I was learning mma), but I always had a bad feeling about it. – Leonid Shifrin Mar 09 '11 at 21:39