*To*: mathgroup@smc.vnet.net*Subject*: [mg11911] Re: Thread*From*: Allan Hayes <hay@haystack.demon.co.uk>*Date*: Thu, 9 Apr 1998 00:33:12 -0400*References*: <6g27rm$1d2@smc.vnet.net>

Des Penny wrote: > > Hi Groupers: > > I've written a program to calculate the forces on charged particles. The > program works well except that parts are less than elegant. The key > questions I have concern the Thread function: > > ========================================== > > Question 1: > ------------ > > In[1]:= > Thread[f[a,{b,c}]] > > Out[1]= > {f[a,b],f[a,c]} > > We see that if "a" does not have head "List" it is automatically > replicated so that Thread works. > Now if a, b and c are defined as follows: > > In[2]:= > a={q1,{x1,y1,z1}};b={q2,{x2,y2,z2}};c={q3,{x3,y3,z3}}; > > I would LIKE to have the following output when I apply Thread: > > {f[{q1,{x1,y1,z1}},{q2,{x2,y2,z2}}],f[{q1,{x1,y1,z1}},{q3,{x3,y3,z3}]} > > However, since "a" now has head "List", Thread now gives me: > > In[3]:= > Thread[f[a,{b,c}]] > > Out[3]= > {f[q1,{q2,{x2,y2,z2}}],f[{x1,y1,z1},{q3,{x3,y3,z3}}]} > > Is there a way to force Thread to give me what I want? a={q1,{x1,y1,z1}};b={q2,{x2,y2,z2}};c={q3,{x3,y3,z3}}; Thread[f[a,{b,c}],List,{2}] (*thread over List at positin 2 only*) {f[{q1,{x1,y1,z1}},{q2,{x2,y2,z2}}],f[{q1,{x1,y1,z1}},{q3,{x3,y3,z3}}]} > ================================================================ > > Question 2: > ------------- > > I would like to be able to Thread g across two lists as follows: > > In[1]:= > ccs={a,b}; oc={x,y}; > Thread[g[ccs,oc]] > > Out[1]= > {g[a,x],g[b,y]} > > But unfortunately, since ccs and oc are lists, and since g is designed > to operate on lists, g executes before the thread takes place. > > If g is undefined everything is ok: > > In[3]:= > a={a1,a2}; b={b1,b2}; x={x1,x2}; y={y1,y2}; Thread[g[ccs,oc]] > > Out[3]= > {g[{a1,a2},{x1,x2}],g[{b1,b2},{y1,y2}]} > > If I now define g: > > In[4]:= > g[x1_List,x2_List]:=x1+x2^2 > > I would now LIKE the output of the Thread statement to be: > > In[6]:= > {g[{a1,a2},{x1,x2}],g[{b1,b2},{y1,y2}]} > > Out[6]= > {{a1 + x1^2, a2 + x2^2}, {b1 + y1^2, b2 + y2^2}} > > Instead the Thread statement now gives me: > > In[7]:= > Thread[g[ccs,oc]] > > Out[7]= > {{a1 + x1^2, b1 + y1^2}, {a2 + x2^2, b2 + y2^2}} a={a1,a2}; b={b1,b2}; x={x1,x2}; y={y1,y2}; g[x1_List,x2_List]:=x1+x2^2 MapThread[g,{ccs,oc}] 2 2 2 2 {{a1 + x1 , a2 + x2 }, {b1 + y1 , b2 + y2 }} -- Allan Hayes Mathematica Training and Consulting Leicester, UK hay@haystack.demon.co.uk http://www.haystack.demon.co.uk voice: +44 (0)116 271 4198 fax: +44 (0)116 271 8642