如何在 mathematica 中为矩阵乘法重载 Times 和 Plus [英] how to overload Times and Plus for matrix multiplication in mathematica
问题描述
我想为mathematica中的矩阵乘法重载Times
和Plus
,例如,让Times
成为BitAnd
>,加为BitOr
,然后做矩阵乘法.
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?
谢谢.
推荐答案
问题是你想改变什么 - Times
和 Plus
或 的行为>点
.通常,Block
技巧通常是最简单的方法.在这种情况下,由于 Dot
没有调用高级 Plus
或 Times
,你可以这样做:
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}}
但请注意,这是有效地重新实现矩阵乘法(使用 Inner
) - 没有其他方法,因为 Dot
在内部实现并且不使用 Plus
或 Times
.
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
.
这篇关于如何在 mathematica 中为矩阵乘法重载 Times 和 Plus的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!