在 sympy 表达式中使用矩阵乘法 @ 运算符
如果我使用符号 a,b,c
制作一个 Sympy 表达式,如下所示,
import sympy as sm
import numpy as np
a,b,c = sm.symbols("a,b,c")
expr = 4*a + b*a + b*c + a*b*c
f = sm.lambdify((a,b,c), expr)
a_1 = np.random.rand(10,10)
b_1 = np.random.rand(10,10)
c_1 = np.random.rand(10,10)
f(a_1, b_1, c_1)
对我来说,问题是lambdaify 在 numpy
中使用 *
,其中只是逐个元素相乘,但我需要上述函数中的 matmul 或 @
运算符。上面的代码只是一个示例,在我的一些用例中,表达式的使用变得很复杂。我尝试在 Sympy 中寻找实现此目的的方法,但 lambdify 不适用于此运算符。我想知道是否存在一个符号,其作用类似于 Sympy 中的乘法运算符矩阵,其中不需要矩阵大小规范,但我找不到任何符号。对我来说也很重要的是,我可以对 a、b 和 c 的不同大小选择的矩阵使用相同的函数。任何建议都会非常有帮助。谢谢!
If I make a Sympy expression with symbols a,b,c
as follows
import sympy as sm
import numpy as np
a,b,c = sm.symbols("a,b,c")
expr = 4*a + b*a + b*c + a*b*c
f = sm.lambdify((a,b,c), expr)
a_1 = np.random.rand(10,10)
b_1 = np.random.rand(10,10)
c_1 = np.random.rand(10,10)
f(a_1, b_1, c_1)
The problem here for me, is that lambdify uses *
in numpy
which is just the element-by-element multiplication, but I need the matmul or @
operator in the above function. Above code is just an example, and in some of my use cases the expression becomes complicated to use. I tried to look for methods to achieve this in Sympy, but lambdify
does not work with this operator. I was wondering whether a symbol existed which acts like a matrix for multiplication operators in Sympy, where the matrix size specification is not necessary, but I could not find any. It is also important for me that I can use the same function for matrices of different size choice of a, b and c. Any suggestion would be very helpful. Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
带有
lambdify
的数组的正常用法是根据表达式中符号的许多值来计算标量表达式。如果您想使用数组作为矩阵并进行矩阵乘法,那么您的符号需要是 MatrixSymbol :The normal usage of arrays with
lambdify
is to evaluate a scalar expression over many values of the symbols in the expression. If you want to use arrays as matrices and have matrix multiplication then your symbols need to beMatrixSymbol
: