Use MapThread not a For loop
- To: mathgroup at smc.vnet.net
- Subject: [mg18851] Use MapThread not a For loop
- From: "Ersek, Ted R" <ErsekTR at navair.navy.mil>
- Date: Thu, 22 Jul 1999 22:57:48 -0400
- Sender: owner-wri-mathgroup at wolfram.com
Bin Liu wrote: ------------------ ..... the last command (For loop) gives me no output. But it works if I input a specific number, 1 to 4, to substitute i in "Apply[mag,{Watoms[[i]],Gatoms[[i]]}]". watoms= Table[{{0,0,0},{0.5,-0.5,0.5},{0.5,0.5,0.5},{0,0,1}}] Bao = 2.8665; Watoms =watoms*Bao; gatoms=Table[ {{0,0,0},{0.5,-0.5,0.5},{0.5,0.5,0.5},{0,0,1}}] Fao = 3.5975 Gatoms =gatoms*Fao mag[{a1_,a2_,a3_},{b1_,b2_,b3_}]:=Sqrt[(a1-b1)^2+(a2-b2)^2+(a3-b3)^2] For[i=1,i<5,i++,Apply[mag,{Watoms[[i]],Gatoms[[i]]}]] -------------------------- REPLY: In Mathematica For[...] doesn't return anything (unless it evaluates Return[expr] inside the loop). For[...] only performs the calculation. Also your use of Apply[mag, ...] computes each mag, but doesn't change Watoms or Gatoms! One could get your For loop to do what you want, but with Mathematica it's the wrong way to go. Instead see what MapThread does below. In[1]:= Wat={{a1,b1},{a2,b2},{a3,b3}}; Gat={{x1,y1},{x2,y2},{x3,y3}}; In[3]:= MapThread[ff,{Wat,Gat}] Out[3]= {ff[{a1,b1},{x1,y1}],ff[{a2,b2},{x2,y2}],ff[{a3,b3},{x3,y3}]} ---------------------- MapThread is made for the sort of thing you want to do! What you should do is use the line below. In[4]:= MapThread[mag,{Watoms,Gatoms}] Out[4]= {0,0.633065,0.633065,0.731} ------------- Here are some other important features you should learn about: Map Apply Pattern matching (very powerful) Listable (this attribute is your friend) Select Cases Rule (as in -- expr/.lhs->rhs) RuleDelayed (as in -- expr/.lhs:>rhs) ------------- Here is a tip none of the books will tell you. You can get the wrong answer if you use a pattern on the left side of Rule. Instead use RuleDelayed. expr/.x_->x^2 (* Might give the wrong answer! *) expr/.x_:>x^2 (* Use this instead. *) ---------------- Regards, Ted Ersek ersektr at navair.navy.mil