Re: Getting rid of those deprecated Do[] loops?

• To: mathgroup at smc.vnet.net
• Subject: [mg92784] Re: Getting rid of those deprecated Do[] loops?
• From: mark mcclure <mcmcclur at unca.edu>
• Date: Mon, 13 Oct 2008 06:18:56 -0400 (EDT)
• References: <gcsctj\$8mj\$1@smc.vnet.net>

```On Oct 12, 4:36 am, AES <sieg... at stanford.edu> wrote:
> Trying to think of a "two-variable iterator" approach that will let one
> produce the same results as
> data = { };
> Do[Do[data = AppendTo[data, {aa, bb, xx, yy}],
>     {bb, 10, 30, 10}], {aa, 1, 2}];
> without using those universally deprecated (and even worse, nested)
> Do[ ] loops, not to mention the equally deprecated AppendTo[].

I think that Do has actually received a bit of a bum wrap in
the discussion on procedural programming in Mathematica.
The syntax of Do is, after all, identical to that of Table
(as well as to that of Plot, Integrate, Manipulate, and
others).  Not surprisingly, a command like
Do[Prime[n],{n,100000}]
runs a bit faster than the corresponding Table command.

The egregious part of the code is clearly the AppendTo
statement.  AppendTo is inefficient since lists are stored
as arrays that need to be recopied with each call.  This is
particularly problematic with long lists.  It's fairly easy

Reap[Do[Sow[{aa, bb, xx, yy}],
{aa, 1, 2}, {bb, 10, 30, 10}]][[2, 1]]

If you're interested in efficiency, check out the following
timings:

data = {};
First[Timing[Do[Do[data =
AppendTo[data, {aa, bb, xx, yy}], {bb, 100}], {aa, 100}]]]
6.09818
----
First[Timing[Reap[Do[Sow[{aa, bb, xx, yy}],
{bb, 100}, {aa, 100}]][[2, 1]];]]
0.01853

Mark McClure

```

• Prev by Date: Re: Getting rid of those deprecated Do[] loops?
• Next by Date: Re: Getting rid of those deprecated Do[] loops?
• Previous by thread: Re: Getting rid of those deprecated Do[] loops?
• Next by thread: Re: Getting rid of those deprecated Do[] loops?