如果我想从两个列表list1
和list2
找到所有可能的和,我用的是Outer[]
功能与Plus
说明书中作为合并算:在Mathematica中,如何为任意数量的参数编译函数Outer []?
In[1]= list1 = {a, b}; list2 = {c, d}; Outer[Plus, list1, list2]
Out[1]= {{a + c, a + d}, {b + c, b + d}}
如果我想能够处理任意数量的列表,比如列表清单,
In[2]= listOfLists={list1, list2};
然后我知道如何找到所有可能的和唯一的办法是使用Apply[]
功能(具有短手@@
)与Join
一起:
In[3]= argumentsToPass=Join[{Plus},listOfLists]
Out[3]= {Plus, {a, b}, {c, d}}
In[4]= Outer @@ argumentsToPass
Out[4]= {{a + c, a + d}, {b + c, b + d}}
或者干脆
In[5]= Outer @@ Join[{Plus},listOfLists]
Out[5]= {{a + c, a + d}, {b + c, b + d}}
问题是当我尝试编译:
In[6]= Compile[ ..... Outer @@ Join[{Plus},listOfLists] .... ]
Compile::cpapot: "Compilation of [email protected]@Join[{Plus},listOfLists]] is not supported for the function argument Outer. The only function arguments supported are Times, Plus, or List. Evaluation will use the uncompiled function. "
的事情是,我上午用一根S支持的功能,即Plus
。这个问题似乎只与Apply[]
函数有关。因为如果我把它列出来固定数量的外加在一起,它工作正常
In[7]= Compile[{{bob, _Integer, 1}, {joe, _Integer, 1}}, Outer[Plus, bob, joe]]
Out[7]= CompiledFunction[{bob, joe}, Outer[Plus, bob, joe],-CompiledCode-]
,但只要我用Apply
,它打破
In[8]= Compile[{{bob, _Integer, 1}, {joe, _Integer, 1}}, Outer @@ Join[{Plus}, {bob, joe}]]
Out[8]= Compile::cpapot: "Compilation of [email protected]@Join[{Plus},{bob,joe}] is not supported for the function argument Outer. The only function arguments supported are Times, Plus, or List. Evaluation will use the uncompiled function."
所以我的问题是:有没有办法来规避这个错误,或者,一种方法来计算从编译函数中的任意数量的列表中拉出的元素的所有可能的总和?
(另外,我不知道,如果“汇编”是一个合适的标签。请指教。)
非常感谢。
关于您期望使用多少个列表以及多长时间?根据答案,编译可能不是执行此操作的最快方法。 – joebolte 2011-02-12 00:14:59