简体   繁体   English

在 sympy 表达式中使用矩阵乘法运算符

[英]Using a matrix multiplication operator in a sympy expression

I am trying to implement a function using a Sympy expression with multiple parameters.我正在尝试使用带有多个参数的 Sympy 表达式来实现一个函数。 For example, I used the following code:例如,我使用了以下代码:

import sympy
a = sympy.symbols("a")
ad = sympy.symbols("ad")
x = sympy.symbols("x")
c = sympy.symbols("c")
f = (ad*a)*c + x
func = sympy.lambdify((a,ad,x,c),f)

And what I would like to evaluate is the following:我想评估的是以下内容:

func(M_A,M_B,0,1)

When I use two matrices M_A and M_B , the function performs just an element-wise multiplication, but I need it to be a matrix multiplication for the objects a and ad .当我使用两个矩阵M_AM_B ,函数执行只是一个元素方式乘法,但我需要它的对象矩阵乘法aad I do know that it is possible to do so when I define the variables using MatrixSymbol instead of symbols , but this is not possible in my case as I have implemented a scenario which uses diagonal matrices where element-wise or matrix multiplication would not make a difference.我不知道这是可以这样做的时候,我定义使用变量MatrixSymbol而不是symbols ,但这是不可能在我的情况,我已经实现了它采用对角矩阵,其中的元素明智或矩阵乘法不会让一个场景区别。 Further, it is also possible to do something like this with normal symbols此外,也可以用普通符号做这样的事情

x_vars = [symbols("x"+i) for i in range(1,4)]
trans_mat = np.random.random([3,3])
y_vars = trans_mat.dot(x_vars)

which just does not seem to work when I am using MatrixSymbol .当我使用MatrixSymbol时,这似乎MatrixSymbol

So, I was thinking if I could just compute the expression and perform all the manipulations using the regular symbols and at the end replace all the multiplication operators with numpy.matmul .所以,我在想是否我可以只计算表达式并使用常规符号执行所有操作,最后用numpy.matmul替换所有乘法运算符。 Please let me know if this is possible somehow, or any other suggestion which can help is also welcome.请让我知道这是否可行,或者也欢迎任何其他可以提供帮助的建议。

Thanks!谢谢!

Doing help(func) we can see the code produced by lambdify :执行help(func)我们可以看到lambdify生成的代码:

Help on function _lambdifygenerated:

_lambdifygenerated(a, ad, x, c)
    Created with lambdify. Signature:
    
    func(a, ad, x, c)
    
    Expression:
    
    a*ad*c + x
    
    Source code:
    
    def _lambdifygenerated(a, ad, x, c):
        return a*ad*c + x

That's a straightforward translation to python/numpy.这是对 python/numpy 的直接翻译。 Sounds like you want (a@ad)*c+x .听起来你想要(a@ad)*c+x

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM