简体   繁体   English

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

[英]Using matrix multiplication @ operator in sympy expression

If I make a Sympy expression with symbols a,b,c as follows如果我用符号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)

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.我这里的问题是,lambdify 在numpy中使用*这只是逐元素乘法,但我需要在上面的 function 中使用 matmul 或@运算符。以上代码只是一个示例,在我的一些使用中情况下表达式变得难以使用。 I tried to look for methods to achieve this in Sympy, but lambdify does not work with this operator.我试图在 Sympy 中寻找实现此目的的方法,但lambdify不适用于此运算符。 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.我想知道是否存在一个符号,它在 Sympy 中充当乘法运算符的矩阵,其中不需要矩阵大小规范,但我找不到任何符号。 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.对我来说同样重要的是,我可以使用相同的 function 来选择 a、b 和 c 的不同大小的矩阵。任何建议都会非常有帮助。 Thanks!谢谢!

The normal usage of arrays with lambdify is to evaluate a scalar expression over many values of the symbols in the expression. arrays 与lambdify的正常用法是根据表达式中符号的许多值计算标量表达式。 If you want to use arrays as matrices and have matrix multiplication then your symbols need to be MatrixSymbol :如果你想使用 arrays 作为矩阵并进行矩阵乘法,那么你的符号需要是MatrixSymbol

In [235]: A = MatrixSymbol('A', 2, 2)

In [236]: B = MatrixSymbol('B', 2, 2)

In [237]: f = lambdify((A, B), A*B)

In [238]: import inspect

In [239]: inspect.getsource(f)
Out[239]: 'def _lambdifygenerated(A, B):\n    return (A).dot(B)\n'

In [240]: print(inspect.getsource(f))
def _lambdifygenerated(A, B):
    return (A).dot(B)

In [241]: a = np.array([[1, 2], [3, 4]])

In [242]: f(a, a)
Out[242]: 
array([[ 7, 10],
       [15, 22]])

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

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