这是我在执行
Generalized Distributive Law
. 假设您需要自动生成以下表单的表达式
http://yaroslavvb.com/upload/sum-prod-formula.png
sumProduct(factors,fixedVariables,fixedValues,freeVariables,freeRanges)
哪里
factors={{1,4},{3,4},{3,4,5}}
fixedVariables={1,3}
fixedValues={-1,9}
freeVariables={4,5}
freeRanges={Range[5],Range[6]}
该函数的输出将等于
Total[{f14[-1,1]f34[9,1]f345[9,1,1],f14[-1,2]f34[9,2]f345[9,2,1],....}]
f项的表示可能不同,即f[1,4,-1,1]而不是f14[-1,1]。使用整数引用每个变量也是一种设计选择。
有人能建议一种优雅的方法来实现SumProduct吗?
编辑11/11
Janus的解决方案,为可读性重写
factors = {{1, 4}, {3, 4}, {3, 4, 5}};
vars = {{1, {-1}}, {3, {9}}, {4, Range[5]}, {5, Range[6]}};
(* list of numbers => list of vars *)
arglist[factor_] := Subscript[x, #] & /@ factor;
(* list of factors => list of functions for those factors *)
terms = Apply[f[#], arglist[#]] & /@ factors;
(* {var,range} pairs for each variable *)
args = {Subscript[x, #1], #2} & @@@ vars;
Sum[Times @@ terms, Sequence @@ args]