MathGroup Archive 2004

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

Search the Archive

RE: Understanding Flatten

  • To: mathgroup at smc.vnet.net
  • Subject: [mg46365] RE: [mg46314] Understanding Flatten
  • From: "Wolf, Hartmut" <Hartmut.Wolf at t-systems.com>
  • Date: Mon, 16 Feb 2004 23:41:51 -0500 (EST)
  • Sender: owner-wri-mathgroup at wolfram.com

>-----Original Message-----
>From: Harold.Noffke at wpafb.af.mil [mailto:Harold.Noffke at wpafb.af.mil]
To: mathgroup at smc.vnet.net
>Sent: Saturday, February 14, 2004 3:58 AM
>To: mathgroup at smc.vnet.net
>Subject: [mg46365] [mg46314] Understanding Flatten
>
>
>Mathematica 5.0.1 on Windows 2000
>MathGroup:
>
>In my study of Flatten, the Mathematica Book gives this example ...
>
>	You can use Flatten to "splice" sequences of elements into lists
>	or other expressions.  
>
>	In[5]:= Flatten[ {a, f[b, c], f[a, b, d]}, 1, f ]
>
>	Out[5]= {a,b,c,a,b,d}
>
>I modified In[5] as follows ...
>
>	In[1]:= Flatten[ { {a, f[b, c], f[a, b, d]}, {g, f[e, g]} }]
>
>	Out[1]= {a, f[b, c], f[a, b, d], g, f[e, g]}	
>	
>I don't see why adding {g, f[e, g]} as a second list to the 
>In[5] example
>unflattens Flatten's answer.  What am I misunderstanding?
>
>Thanks.
>Harold
>

Harold,

not quite clear, what you want to attain; 
more possibilities:

In[7]:=
Flatten[#, 1, f] & /@ {{a, f[b, c], f[a, b, d]}, {g, f[e, g]}}
Out[7]=
{{a, b, c, a, b, d}, {g, e, g}}

or, more robust

In[26]:=
Map[Flatten[#, 1, f] &, {{a, f[b, c], f[a, b, d]}, {g, f[e, g]}}, {1, -3}]
Out[26]=
{{a, b, c, a, b, d}, {g, e, g}}


In[11]:=
FlattenAt[{{a, f[b, c], f[a, b, d]}, {g, f[e, g]}},
          {{1, 2}, {1, 3}, {2, 2}}]
Out[11]=
{{a, b, c, a, b, d}, {g, e, g}}


or, if you liked this

In[14]:=
FlattenAt[{{a, f[b, c], f[a, b, d]}, {g, f[e, g]}},
          {{1}, {1, 2}, {1, 3}, {2}, {2, 2}}]
Out[14]=
{a, b, c, a, b, d, g, e, g}


You may automate that a bit:

In[36]:=
FlattenAt[#, Position[#, f[___]]] &[{{a, f[b, c], f[a, b, d]}, {g, f[e,
g]}}]
Out[36]=
{{a, b, c, a, b, d}, {g, e, g}}

or, if you preferred

In[37]:=
FlattenAt[#, Position[#, (f | List)[___], Infinity]] &[{{a, f[b, c], 
      f[a, b, d]}, {g, f[e, g]}}]
Out[37]=
{a, b, c, a, b, d, g, e, g}


--
Hartmut Wolf


  • Prev by Date: Re: Solve or LinearSolve or ...?
  • Next by Date: Re: Solve or LinearSolve or ...?
  • Previous by thread: RE: Understanding Flatten
  • Next by thread: Equal, Inequality and TraditionalForm