any better to apply a function...
- To: mathgroup at christensen.cybernetics.net
- Subject: [mg520] any better to apply a function...
- From: colinr at sue.econ.su.oz.au (Colin Rose)
- Date: Wed, 8 Mar 95 5:35:02 EET
Richard Chen writes: > Suppose I have list of numbers in pairs: > a = {{x1,y1},{x2,y2},...,{xn,yn}} > I would like to apply to the sequence {y1,y2,...,yn} the function > f so that a new sequence > b = {{x1,f[y1]},{x2,f[y2]},...,{xn,f[yn]}} > is generated. My current solution is > > b = Transpose[{First /@ a,f[Last /@ a]}] > > However, I suspect there should be a much more simpler way than this. > Does any body know a more straight forward way to do this? How about: Apply[{#1, f[#2]}&, a, 1] > Also, what if I have a matrix of 3 or more columns and I would apply > f to only the second column, say. What is a better way in this case? The same method works: Apply[{#1, f[#2], #3}&, a, 1] For instance: In[1]:= a = { {x1, y1, z1}, {x2, y2, z2}, {x3, y3, z3}}; In[2]:= Apply[{#1, f[#2], #3}&, a, 1] Out[2]= {{x1, f[y1], z1}, {x2, f[y2], z2}, {x3, f[y3], z3}} Hope this helps Colin Dr Colin Rose tr(I) - Theoretical Research Institute ______________________________________ colinr at extro.ucc.su.oz.au