Mathematica 9 is now available
Services & Resources / Wolfram Forums
-----
 /
MathGroup Archive
2000
*January
*February
*March
*April
*May
*June
*July
*August
*September
*October
*November
*December
*Archive Index
*Ask about this page
*Print this page
*Give us feedback
*Sign up for the Wolfram Insider

MathGroup Archive 2000

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

Search the Archive

RE: Building a Table with initially unknown length?

  • To: mathgroup at smc.vnet.net
  • Subject: [mg24234] RE: [mg24248] Building a Table with initially unknown length?
  • From: "David Park" <djmp at earthlink.net>
  • Date: Tue, 4 Jul 2000 15:22:00 -0400 (EDT)
  • Sender: owner-wri-mathgroup at wolfram.com


> -----Original Message-----
> From: AES [mailto:siegman at stanford.edu]
To: mathgroup at smc.vnet.net
>
> Is there a clean and transparent way to build a Table which grows in
> length either to some initially specified maximum length, or until a
> test is met?
>
> One way to do this is obviously to use a While[ ] loop, adding an
> element to the table each time around the loop -- but I've been led to
> believe that Append'ing an elements to a list is a slower process.
>

The Mathematica Book discusses one relatively efficient way to built lists
at the end of Section 2.4.4. It is more efficient to build up a nested list
structure and then Flatten it. The following code generates random numbers
that have a small chance of being negative. It builds up a list to a maximum
length of 10000 or until it generates the first negative number.

Timing[result = Module[{list={}, x, i = 0, max = 10000},
      While[x = Random[Integer, {-2, 10000}];
        i++;  !(i > max || x < 0), list = {x, list}];
      Flatten[list]]; Length[result]]
{0.22 Second, 7425}

David Park
djmp at earthlink.net
http://home.earthlink.net/~djmp/



  • Prev by Date: Re: Re: Evaluate and HoldAll
  • Next by Date: Memory problems using mathlink (Sparse Matrix)
  • Previous by thread: Building a Table with initially unknown length?
  • Next by thread: Re: Building a Table with initially unknown length?