在Mathematica中映射两个自变量函数

问题描述

| 我要存档:
Map2[f,{a,b,c,d}]
{f[a,b],f[b,c],f[c,d]}
但是由于某种原因,我只能想到迭代方法。 什么是功能方式? 编辑: 以此来生成图形示例。如果给出了数字列表,则following生成顺序访问所有节点的含义图。 例如:
Map2 = # @@@ Partition[#2,2,1] &;
MG[elems_] := Graph[Map2[DirectedEdge,elems]]
nrs = RandomInteger[{1,15},20]
MG[nrs]
{10,13,9,7,3,5,1,15,10,6,14,11,4,8,5} 径向布局:     

解决方法

        最简单的:
Map2 = # @@@ Partition[#2,2,1] &;
或者,可能使用较少的内存,但运行速度稍慢:
Map2[f_,lst_] := Developer`PartitionMap[f @@ # &,lst,1]
另外,请注意相关的
Differences
Accumulate
。 其他方法:
Inner[#,Most@#2,Rest@#2,List] &
请注意,在此“ 7”可能是另一种功能。
MapThread[#,{Most@#2,Rest@#2}] &

Most@MapThread[#,{#2,RotateLeft@#2}] &

Rest@MapThread[#,{RotateRight@#2,#2}] &

Table[# @@ #2[[i ;; i + 1]],{i,Length@#2 - 1}] &
现在,是时候了。我将使用Timo的
timeAvg
f1 = # @@@ Partition[#2,1] &;
f2[f_,1]
f3 = Inner[#,List] &;
f4 = MapThread[#,Rest@#2}] &;
f5 = Most@MapThread[#,RotateLeft@#2}] &;
f6 = Table[# @@ #2[[i ;; i + 1]],Length@#2 - 1}] &;

timings = 
  Table[
   list = RandomReal[99,10^i];
   func = Plus;
   timeAvg[#[func,list]] & /@ {f1,f2,f3,f4,f5,f6},6}
  ];

TableForm[timings,TableHeadings -> {10^Range@6,{\"f1\",\"f2\",\"f3\",\"f4\",\"f5\",\"f6\"}}]

ListLogPlot[timings\\[Transpose],Joined -> True]
表格左侧的数字是每次运行的实数列表的长度。 请注意,该图是对数的。 以下是处理最长列表(1,000,000)时使用的内存字节: 经过上述计时后,我发现通过消除eliminating12ѭ(
@@
),可以使
f6
更快。现在显然是较长列表中最快的。我不会将其添加到上表中,因为它已经足够宽了,但是这里是函数及其时序:
f7 = Table[#2[[i]] ~#~ #2[[i + 1]],Length@#2 - 1}] &;
    ,        如Mathematica食谱中所述,可以使用ListConvole函数很好地解决在移动子列表上映射函数的问题:
Map2[f_,l_List] := ListConvolve[{1,1},l,{-1,{},#2 &,f]

In[11]:= Map2[f,{a,b,c,d}]
Out[11]= {f[a,b],f[b,c],f[c,d]}
向导先生在这里,并根据sakra的要求添加了比较时间。     ,        我喜欢:
Map2[f_,l_List]:= MapThread[f,{Most@l,Rest@l}]

In[988]:= Map2[f,d}]
Out[988]= {f[a,d]}
    ,        我最近重新阅读了您的问题,并看到了您的
Graph[ ]
申请。 我认为这样做的自然方法是:
f[l_] := Graph[Thread[Most@l -> Rest@l]]
所以
f[{10,13,9,7,3,5,1,15,10,6,14,11,4,8,5}]  
    ,        跟随belisarius的领导,并解决了您的
Graph
申请,这应该更快一些:
f = Inner[Rule,Most@#,Rest@#,Composition[Graph,List]] &;
    ,        哇,我看到了其他解决方案,它们看起来相当复杂且模糊。这很容易理解,至少在您希望使用更实用的方法的情况下:
MapApplyImpl[fun_] := Function[{args},Apply[fun,args]]
MapApply[fun_,argList_] := Map[MapApplyImpl[fun],argList]
和用法示例:
ff := Function[{t,phi},t*phi]
MapApply[ff,{{0,Pi/4},{(Pi/4)/(10^3),0},{(2*Pi/(10^3)),Pi/4}}]
    

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...