將任意時髦的嵌套列表expr
映射到函數unflatten
以便[email protected]@[email protected]
的最簡單方法是什麼?Mathematica:在拼合之後重建任意的嵌套列表
動機: Compile
只能處理全陣列(這是我剛剛學會 - 但不是從錯誤信息),這樣的想法是與扁平式的編譯版本一起使用unflatten
:
fPrivate=Compile[{x,y},[email protected]@expr];
f[x_?NumericQ,y_?NumericQ]:[email protected]@fPrivate[x,y]
解決一個少一般問題的例子: 我真正需要做的是計算所有衍生品對於給定的多元函數達到某種秩序。對於這種情況,我按照如下方式破解了我的方式:
expr=Table[D[x^2 y+y^3,{{x,y},k}],{k,0,2}];
unflatten=Module[{f,x,y,a,b,sslot,tt},
tt=Table[D[f[x,y],{{x,y},k}],{k,0,2}] /.
{Derivative[a_,b_][_][__]-> x[a,b], f[__]-> x[0,0]};
(Evaluate[tt/.MapIndexed[#1->sslot[#2[[1]]]&,
Flatten[tt]]/. sslot-> Slot]&) ]
Out[1]= {x^2 y + y^3, {2 x y, x^2 + 3 y^2}, {{2 y, 2 x}, {2 x, 6 y}}}
Out[2]= {#1, {#2, #3}, {{#4, #5}, {#5, #7}}} &
這樣的工作,但它既不優雅也不普遍。
編輯:這裏是AAZ提供的解決方案中的「就業保障」的版本:
makeUnflatten[expr_List]:=Module[{i=1},
[email protected]@ReplaceAll[
If[ListQ[#1],Map[#0,#1],i++]&@expr,
i_Integer-> Slot[i]]]
它的工作原理魅力:
In[2]= makeUnflatten[expr]
Out[2]= {#1,{#2,#3},{{#4,#5},{#6,#7}}}&
我沒有測試它,但獅子座希夫林的修改`rearrangeAs`可能工作http://stackoverflow.com/questions/4811082/applying-transformation-of-gatherby-to-a-different-list/4811794# 4811794 – 2011-02-15 08:05:02
謝謝,雅羅斯拉夫:這當然看起來相關 - 但有點難以理解:)。我最終做了一件我自己的事情,如果沒有人咬我就會發布......總是有同樣的故事:1)爲你解決特定情況的問題,2)認識到一個更普遍的解決方案可能很有趣,3)避免浪費時間在切線上,把它張貼在SO上,讓別人去做你的切線工作,4)自己去做。嘆息 – Janus 2011-02-15 08:49:11
這個問題似乎相關http://stackoverflow.com/questions/3807976/inverse-of-flatten-in-mathematica – dbjohn 2011-02-15 12:15:11