如何在Sympy中实现IndexedBase符号的逐元素乘法且结果仍为IndexedBase?
实现方案
方案1:基于IndexedBase封装逐点乘积类(最贴合需求)
直接自定义可索引的乘积类,完全匹配你要的myProduct(U,V)[x] = U[x]*V[x]效果,不需要转换为矩阵:
import sympy as s class ElementwiseProduct: def __init__(self, *indexed_arrays): self.arrays = indexed_arrays def __getitem__(self, idx): # 支持多个IndexedBase逐点相乘 result = 1 for arr in self.arrays: result *= arr[idx] return result # 你的原始代码 N = 10 U = s.IndexedBase('U') V = s.IndexedBase('V') x = s.Idx('x', N) # 使用示例 my_prod = ElementwiseProduct(U, V) print(my_prod[x]) # 输出 U[x]*V[x]
这个方案不需要提前指定数组维度,还支持同时对3个及以上的IndexedBase做逐点乘积,调用方式完全符合预期。
方案2:封装Hadamard乘积适配1维场景
如果你已经在使用MatrixSymbol做其他矩阵运算,可以对Hadamard乘积做简单封装,隐藏固定行索引的逻辑:
import sympy as s def hadamard_1d(*row_vecs): return lambda idx: s.HadamardProduct(*row_vecs)[0, idx] # 你的矩阵定义代码 N = 10 U = s.MatrixSymbol('U',1,N) V = s.MatrixSymbol('V',1,N) x = s.Idx('x', N) # 使用示例 my_prod = hadamard_1d(U, V) print(my_prod(x)) # 输出 HadamardProduct(U, V)[0, x]
封装后不需要每次手动写行索引0,调用逻辑更简洁。
内容的提问来源于stack exchange,提问作者Andrew Yuan
相关产品推荐
相关产品推荐

