Services & Resources / Wolfram Forums
-----
 /
MathGroup Archive
2005
*January
*February
*March
*April
*May
*June
*July
*August
*September
*October
*November
*December
*Archive Index
*Ask about this page
*Print this page
*Give us feedback
*Sign up for the Wolfram Insider

MathGroup Archive 2005

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: Applying function to nested lists

  • To: mathgroup at smc.vnet.net
  • Subject: [mg57892] Re: Applying function to nested lists
  • From: Curt Fischer <tentrillion at gmail.NOSPAM.com>
  • Date: Sun, 12 Jun 2005 04:34:14 -0400 (EDT)
  • References: <d8e525$gnl$1@smc.vnet.net>
  • Sender: owner-wri-mathgroup at wolfram.com

Kerry Kim wrote:
> Hello,
> 
> I'm trying to get Mathematica to do the following:
> 
> Suppose
> x = {{1,2,3},{{4,5,6},7,8},9}
> f = some function
> 
> How can I get f applied to each element of x but with the list structure 
> intact?  I.e. I want something that generates:
> 
> {{f[1],f[2],f[3]},{{f[4],f[5],f[6]},f[7],f[8]},f[9]}
> 
> Thank you!
> -Kerry Kim

One way is just to tell Mathematica to Map your function across any List 
it comes across.  In the example below I've left f undefined for any 
inputs except lists, but you could easily define it for other inputs 
with an f[n_Integer]:= <formula> type of statement, for integers, for 
example.

In[1]:=
x = {{1, 2, 3}, {{4, 5, 6}, 7, 8}, 9};

In[2]:=
f[n_List] := f /@ n

In[3]:=
f[x]

Out[3]=
{{f[1], f[2], f[3]}, {{f[4], f[5], f[6]}, f[7], f[8]}, f[9]}

You can accomplish the same thing by changing the attribute of your 
function to Listable, a course which I'm sure other posts will provide 
more details on.

-- 
Curt Fischer


  • Prev by Date: Re: "expanding a list"
  • Next by Date: Re: saving the kernel
  • Previous by thread: Re: Applying function to nested lists
  • Next by thread: Re: Applying function to nested lists