点列表上的功能映射

时间:2011-10-03 21:18:13

标签: wolfram-mathematica

我有一个点列表:

points = {{0.144, 1.20}, {0.110, 1.60}, {0.083, 2.00}, {0.070, 2.40},
         {0.060, 2.80}, {0.053, 3.20}, {0.050, 3.60}, {0.043, 4.00}}

我想将每个点传递给此函数,返回一个新点:

coordinate[length_,frequence_] = {(1/(2*length)) , (frequence*1000)}

哪个应该产生如下列表:

 { {3.47, 12 000}, {4.54, 16 000}, ... }

我一直在尝试使用map:

 data = Map[coordinate, points]

它产生类似于:

 {coordinate[{0.144, 1.2}], coordinate[{0.11, 1.6}]}

首先看起来是正确的,除了它传递一个列表而不仅仅是参数。但是,即使我将coordinate函数更改为接受列表(通过将预期参数更改为list_并将length更改为list[[1]]frequence更改为{ {1}}),我将无法使用该地图返回的列表,例如list[[2]]的线性回归。

6 个答案:

答案 0 :(得分:9)

使用您的定义的最简单方法是 Apply在第1级,其中有简写@@@。 (参见Apply documentation的更多信息部分。)所以,你想要

points = {{0.144, 1.20}, {0.110, 1.60}, {0.083, 2.00}, {0.070, 
   2.40}, {0.060, 2.80}, {0.053, 3.20}, {0.050, 3.60}, {0.043, 4.00}}

coordinate[length_, frequence_] := {(1/(2*length)), (frequence*1000)}

coordinate @@@ points

请注意,我已将您的定义更改为SetDelayed而非Set(请注意语法突出显示右侧的本地化变量)。请参阅Immediate and Delayed Definitions指南页。

这就是说,最好让coordinate取一个列表而不是序列,就像在belisarius'和ninjagecko的答案中所做的那样,即

coordinate[{length_, frequence_}] := {(1/(2*length)), (frequence*1000)}

答案 1 :(得分:4)

coordinate[{length_, frequence_}] := {(1/(2*length)), (frequence*1000)}
data = coordinate /@ points
(*
->{{3.47222, 1200.}, {4.54545, 1600.}, {...
*)

并且

lm = LinearModelFit[data, x, x]
(*
-> -40.3573 + 348.678 x
*)

Show[ListPlot[data], Plot[lm[x], {x, 0, 15}], Frame -> True]

enter image description here

答案 2 :(得分:3)

将您的定义更改为

coordinate[point_] := {(1/(2*point[[1]])) , (point[[2]]*1000)}

答案 3 :(得分:3)

coordinate[{length_, frequence_}] := {1/(2*length), frequence*1000}
coordinate /@ points

旁注:我个人会远离其他答案中提出的@@@,因为作为一名程序员,我觉得很尴尬。但这些答案肯定也是有效的。

答案 4 :(得分:2)

或者,您可以使用Apply代替Map

coordinate @@@ points

输出:

{{3.47222, 1200.}, {4.54545, 1600.}, {6.0241, 2000.}, {7.14286, 2400.}, 
 {8.33333, 2800.}, {9.43396, 3200.}, {10., 3600.}, {11.6279, 4000.}}

答案 5 :(得分:1)

我觉得@@@是解决这个问题最干净的方法。但是,如果您可以重新定义coordinate但不想删除其现有语法,则可以考虑使用此构造。

Clear[coordinate]
coordinate[length_, frequence_] := {(2 length)^-1, 1000 frequence}
coordinate[l_List] := Apply[coordinate, l, {-2}]

新行添加了处理列表的定义。这假定您的参数本身不是具有深度的对象。它允许您使用该功能的方式具有相当大的灵活性:

coordinate[0.144, 1.20]

(*Out= {3.47222, 1200.} *)

coordinate[{0.144, 1.20}]

(*Out= {3.47222, 1200.} *)

coordinate[points]

(*Out= {{3.47222, 1200.}, {4.54545, 1600.}, {6.0241, 
  2000.}, {7.14286, 2400.}, {8.33333, 2800.}, {9.43396, 3200.}, {10., 
  3600.}, {11.6279, 4000.}} *)

coordinate /@ points

(*Out= {{3.47222, 1200.}, {4.54545, 1600.}, {6.0241, 
  2000.}, {7.14286, 2400.}, {8.33333, 2800.}, {9.43396, 3200.}, {10., 
  3600.}, {11.6279, 4000.}} *)

coordinate @@@ points

(*Out= {{3.47222, 1200.}, {4.54545, 1600.}, {6.0241, 
  2000.}, {7.14286, 2400.}, {8.33333, 2800.}, {9.43396, 3200.}, {10., 
  3600.}, {11.6279, 4000.}} *)