Re: Is a For loop always a no-no?
- To: mathgroup at smc.vnet.net
- Subject: [mg50336] Re: Is a For loop always a no-no?
- From: Paul Abbott <paul at physics.uwa.edu.au>
- Date: Fri, 27 Aug 2004 02:57:59 -0400 (EDT)
- Organization: The University of Western Australia
- References: <cgkg6v$g97$1@smc.vnet.net>
- Sender: owner-wri-mathgroup at wolfram.com
In article <cgkg6v$g97$1 at smc.vnet.net>, "1.156" <rob at pio-vere.com> wrote: > 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. Since y is a matrix, you want to Map (shorthand /@) the above differencing operation over each row. Also, you can use Most (in version 5) instead of Drop[ ,-1] yd = Most /@ (RotateLeft[#] - # & /@ y) However, instead of using RotateLeft you can use ListConvolve: yd2 = ListConvolve[{1, -1}, #] & /@ y or better still, make the kernel the same dimension as the matrix: yd3 = ListConvolve[{{1, -1}}, y] Cheers, Paul -- Paul Abbott Phone: +61 8 9380 2734 School of Physics, M013 Fax: +61 8 9380 1014 The University of Western Australia (CRICOS Provider No 00126G) 35 Stirling Highway Crawley WA 6009 mailto:paul at physics.uwa.edu.au AUSTRALIA http://physics.uwa.edu.au/~paul