RE: Building a list

*To*: mathgroup at smc.vnet.net*Subject*: [mg47195] RE: [mg47114] Building a list*From*: "Wolf, Hartmut" <Hartmut.Wolf at t-systems.com>*Date*: Mon, 29 Mar 2004 04:22:41 -0500 (EST)*Sender*: owner-wri-mathgroup at wolfram.com

>-----Original Message----- >From: Mark Coleman [mailto:mark at markscoleman.com] To: mathgroup at smc.vnet.net >Sent: Friday, March 26, 2004 9:56 AM >To: mathgroup at smc.vnet.net >Subject: [mg47195] [mg47114] Building a list > > >Greetings, > >I've got a relatively simple function f[a_,b_,c_,d_], where a >and b are >integers and c and d are lists (of reals), and f returns a real. > >I need to evaluate f on (potentially long) sets of lists and >calculate >a square "matrix" from the possible permutations of the >elements in the >lists. For instance > >If > >xlist={x1,x2,x3} > > >I need to calculate > >{{f[a,b,x1,x1],f[a,b,x1,x2],f[a,b,x1,x3]},{f[a,b,x2,x1],f[a,b,x >2,x2],f[a >,b,x2,x3]},{f[a,b,x3,x1],f[a,b,x3,x2],f[a,b,x3,x3]}} > >Note that f[a,b,c,d] does not equal f[a,b,d,c]. > >My first reaction was that Outer[] might do this, but I cannot >seem to >get it to work. I'd appreciate any suggestions. > >Thanks, > >Mark > The optimal solution depends a bit on the format of the result. If you don't need a resulting matrix structure prefer Distribute: In[1]:= l = {x1, x2, x3}; In[2]:= Outer[f[a, b, ##] &, l, l] Out[2]= {{f[a, b, x1, x1], f[a, b, x1, x2], f[a, b, x1, x3]}, {f[a, b, x2, x1], f[a, b, x2, x2], f[a, b, x2, x3]}, {f[a, b, x3, x1], f[a, b, x3, x2], f[a, b, x3, x3]}} In[3]:= Distribute[f[a, b, l, l], List] Out[3]= {f[a, b, x1, x1], f[a, b, x1, x2], f[a, b, x1, x3], f[a, b, x2, x1], f[a, b, x2, x2], f[a, b, x2, x3], f[a, b, x3, x1], f[a, b, x3, x2], f[a, b, x3, x3]} For large lists look at: In[4]:= ll = Table[Unique[x], {1000}]; In[5]:= (r2 = Distribute[f[a, b, ll, ll], List]); // Timing Out[5]= {3.826 Second, Null} In[6]:= (r2 = Partition[r2, 1000]); // Timing Out[6]= {1.141 Second, Null} In[7]:= (r1 = Outer[f[a, b, ##] &, ll, ll]); // Timing Out[7]= {9.143 Second, Null} In[8]:= r1 === r2 Out[8]= True So Distribute-ing and then Partition-ing is faster than Outer (at not packed arrays, at least). -- Hartmut Wolf