Re: To apply a function to a List
- To: mathgroup at smc.vnet.net
- Subject: [mg65641] Re: [mg65597] To apply a function to a List
- From: János <janos.lobb at yale.edu>
- Date: Tue, 11 Apr 2006 04:04:54 -0400 (EDT)
- References: <200604100631.CAA14845@smc.vnet.net>
- Sender: owner-wri-mathgroup at wolfram.com
On Apr 10, 2006, at 2:31 AM, Francisco Javier wrote:
> Dear all,
>
> Let f, l be a function and a list respectively. How can we do
>
> Table[f[list[[n]]],{n,1, Length[list]}]
>
> in another way?
>
> Thanks.
>
> --
> ----
> Francisco Javier García Capitán
> http://garciacapitan.auna.com
Here are two newbie approaches;
In[1]:=
lst = Table[a[i], {i, 1, 10}]
Out[1]=
{a[1], a[2], a[3], a[4],
a[5], a[6], a[7], a[8],
a[9], a[10]}
In[2]:=
f[x_] := func[x]
The first is to use Map.
In[3]:=
(f[#1] & ) /@ lst
Out[3]=
{func[a[1]], func[a[2]],
func[a[3]], func[a[4]],
func[a[5]], func[a[6]],
func[a[7]], func[a[8]],
func[a[9]], func[a[10]]}
The second is to set f Listable:
Here it is f without Listable:
In[4]:=
f[lst]
Out[4]=
func[{a[1], a[2], a[3], a[4],
a[5], a[6], a[7], a[8],
a[9], a[10]}]
Let now set Listable for f:
In[5]:=
SetAttributes[f, Listable]
In[6]:=
f[lst]
Out[6]=
{func[a[1]], func[a[2]],
func[a[3]], func[a[4]],
func[a[5]], func[a[6]],
func[a[7]], func[a[8]],
func[a[9]], func[a[10]]}
With 10^6 elements on my machine the Map takes 3.03 second, the
direct apply of the Listable f takes about 2.25 seconds.
I am sure, there are some other more cleaver ways.
János
----------------------------------------------
Trying to argue with a politician is like lifting up the head of a
corpse.
(S. Lem: His Master Voice)
- References:
- To apply a function to a List
- From: Francisco Javier <pacoga@ctv.es>
- To apply a function to a List