|
[Date Index]
[Thread Index]
[Author Index]
Re: Is a For loop always a no-no?
- To: mathgroup at smc.vnet.net
- Subject: [mg50335] Re: [mg50312] Is a For loop always a no-no?
- From: "David Annetts" <davidannetts at ihug.com.au>
- Date: Fri, 27 Aug 2004 02:57:58 -0400 (EDT)
- Sender: owner-wri-mathgroup at wolfram.com
Hi Rob,
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.
-------------------
For[] (& Do[], While[], etc) loops have the advantage that they are usually
immediately understandable at a glance. Translating C++ or Fortran into
Mathematica is usually straightforward if a For (or Do for the Fortran
buffs:) is used.
Mathematica's functional shorthand usually takes a bit more thought, but its
advantage (usually) is speed.
Try defining the function
der[x_List] := Drop[RotateLeft[x] - x, -1]
This is applied to your matrix using
Map[der, y]
Having said that, I get little speed difference between the functional
approach and the For[] loop IN THIS CASE. I suspect this is because of the
RotateLeft[] function. In this case, the advantage of the functional
approach is that I don't need to worry about defining "n"; I can just do it.
Regards,
Dave.
Prev by Date:
Re: Q: Solve gives complex solution where there is a noncomplex solution how to get the last one?
Next by Date:
Re: Is a For loop always a no-no?
Previous by thread:
Re: Is a For loop always a no-no?
Next by thread:
Re: Is a For loop always a no-no?
|