Re: Is a For loop always a no-no?

*To*: mathgroup at smc.vnet.net*Subject*: [mg50323] Re: [mg50312] Is a For loop always a no-no?*From*: "Wolf, Hartmut" <Hartmut.Wolf at t-systems.com>*Date*: Fri, 27 Aug 2004 02:57:45 -0400 (EDT)*Sender*: owner-wri-mathgroup at wolfram.com

>-----Original Message----- >From: 1.156 [mailto:rob at pio-vere.com] To: mathgroup at smc.vnet.net >Sent: Thursday, August 26, 2004 12:51 PM >To: mathgroup at smc.vnet.net >Subject: [mg50323] [mg50312] Is a For loop always a no-no? > > >I realize that many times some form of Mathematica built in >array function will >do the needed job. Here I have a matrix containing individual data >traces in rows y[[i]]. I want to make matrix containing the >corresponding >derivative signals in rows yd[[i]]. I get this done using the >following >For loop. Matrix yd has been initialized (it wouldn't work >with out it). > >For[i = 1, i < n, i++, yd[[i]] = Drop[RotateLeft[y[[i]]] - >y[[i]], -1]]; > >I tried the obvious (to me): >yd = Drop[RotateLeft[y] -y, -1]; > >But I get garbage. It seems the whole matrix has been flattened to a >single list and the whole list is rotated --instead of doing it row >by row as I need. > >Wizzards all: is there some slick way to do this without the For loop? >If so, it's probably faster and sure would look better in the code. >Suggestions appreciated as usual. > >Rob > > Rob, it's always good to make up an (even trivial) example: In[1]:= y = Partition[Range[15]^2, 3] Out[1]= {{1, 4, 9}, {16, 25, 36}, {49, 64, 81}, {100, 121, 144}, {169, 196, 225}} Our data. We have n sets: In[2]:= n = Length[y] Out[2]= 5 Initializing: In[3]:= yd = PadLeft[{}, n, 0] Out[3]= {0, 0, 0, 0, 0} Your program delivers: In[4]:= For[i = 1, i < n + 1, i++, yd[[i]] = Drop[RotateLeft[y[[i]]] - y[[i]], -1]] In[5]:= yd Out[5]= {{3, 5}, {9, 11}, {15, 17}, {21, 23}, {27, 29}} This does the same ("obviously") : In[6]:= Drop[RotateLeft[#] - #, -1] & /@ y Out[6]= {{3, 5}, {9, 11}, {15, 17}, {21, 23}, {27, 29}} This, perhaps, is slick: In[7]:= ListConvolve[{{1, -1}}, y] Out[7]= {{3, 5}, {9, 11}, {15, 17}, {21, 23}, {27, 29}} As to your heading, certainly not! -- Hartmut