Lists

• To: mathgroup at yoda.physics.unc.edu
• Subject: Lists
• From: gaylord at ux1.cso.uiuc.edu
• Date: Wed, 24 Mar 1993 04:32:31 -0600

```Regarding message from Richard ?? and Ed Boss about applying a function
to the second entries of a list of ordered pairs:

A more elegant solution is:
list = {{1,2},{3,4},{5,6}}
MapAt[Sin,#,2]& /@ list

This does the trick. Of course Sin can be replaced by any other function,
(you may need to define it first so you can refer to it by name) and by
replacing 2 by some other integer you can access any entry of an n-tuple.

Richard Mercer

==========

In[25]:=
list = {{1,2},{3,4},{5,6}};

In[26]:=
Map[MapAt[Sin,#, 2]&, list]
Out[26]=
{{1, Sin[2]}, {3, Sin[4]}, {5, Sin[6]}}
==========

a faster alternative:

In[27]:=
Transpose[{#[[1]],Sin[#[[2]]]}&[Transpose[list]]]
Out[27]=
{{1, Sin[2]}, {3, Sin[4]}, {5, Sin[6]}}

In[34]:=
list = Table[Random[], {3}, {2}]
Out[34]=
{{0.868593, 0.617715}, {0.270917, 0.0799992},   {0.0144145, 0.343787}}

In[35]:=
list = Table[Random[], {500}, {2}];

In[36]:=
Timing[Map[MapAt[Sin,#, 2]&, list];]
Out[36]=
{1.35 Second, Null}

In[37]:=
Timing[Transpose[{#[[1]],Sin[#[[2]]]}&[Transpose[list]]];]
Out[37]=
{0.833333 Second, Null}

In[38]:=
list = Table[Random[], {5000}, {2}];

In[39]:=
Timing[Map[MapAt[Sin,#, 2]&, list];]
Out[39]=
{13.4833 Second, Null}

In[40]:=
Timing[Transpose[{#[[1]],Sin[#[[2]]]}&[Transpose[list]]];]
Out[40]=
{7.91667 Second, Null}

richard j. gaylord, university of illinois, gaylord at ux1.cso.uiuc.edu

"if you're not programming functionally, then you must be programming
dysfunctionally"

```

• Prev by Date: RHIT please come in