Services & Resources / Wolfram Forums
MathGroup Archive
*Archive Index
*Ask about this page
*Print this page
*Give us feedback
*Sign up for the Wolfram Insider

MathGroup Archive 2004

[Date Index] [Thread Index] [Author Index]

Search the Archive

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

  • To: mathgroup at
  • Subject: [mg50336] Re: Is a For loop always a no-no?
  • From: Paul Abbott <paul at>
  • Date: Fri, 27 Aug 2004 02:57:59 -0400 (EDT)
  • Organization: The University of Western Australia
  • References: <cgkg6v$g97$>
  • Sender: owner-wri-mathgroup at

In article <cgkg6v$g97$1 at>, "1.156" <rob at> 

> 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]


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 

  • Prev by Date: Re: Is a For loop always a no-no?
  • Next by Date: Re: Re: subscripted function variables
  • Previous by thread: Re: Is a For loop always a no-no?
  • Next by thread: Re: Is a For loop always a no-no?