Message Boards Message Boards

How to generate a list from a loop?

Posted 9 years ago

Hi,

How can I turn my output associated with 'updateList' into a list in the format?

{{1,1,1},{2,4,8},{3,9,27}}

It's currently,

{1,1,1}
{2,4,8}
{3,9,27}

Here is a simplification of the function that I'm attempting,

updateList =
 Do[
  Do[
   If[
    j*RandomReal[] > 1/2
    ,
    , Print[{i, i^2, i^3}]
     Break[]]
   , {j, 1, 9, 1}]
  , {i, 1, 3, 1}]

I found a StackExchange post on the topic, but have been unable thus far to apply it successfully. This will operate on a list about 4,000 items long. http://mathematica.stackexchange.com/questions/2930/creating-a-table-matrix-during-a-for-loop

Any help very much appreciated!

Greg

POSTED BY: Greg
3 Replies

I had the same idea using Sow & Reap, but used Table in place of Do:

First@Last@Reap[
   Table[ 
    If[ j*RandomReal[] > 1/2
     , Null
     , Sow[{i, i^2, i^3}]]
    , {i, 3}, {j, 9}
    ]]

Each time it's executed, the length of output lists varied. For example:

{{1, 1, 1}, {1, 1, 1}, {3, 9, 27}, {3, 9, 27}}

{{1, 1, 1}, {2, 4, 8}, {3, 9, 27}}

{{1, 1, 1}, {1, 1, 1}, {2, 4, 8}, {2, 4, 8}, {2, 4, 8}, {2, 4, 8}}

The iterators i and j could be swapped for a different effect.

POSTED BY: Carl Verdon

one way

First@Last@Reap@Do[Do[If[j*RandomReal[] > 1/2, Sow@{i, i^2, i^3}; Break[]], {j, 1, 9, 1}], {i, 1, 3, 1}]
   (*{{1, 1, 1}, {2, 4, 8}, {3, 9, 27}}*)
POSTED BY: Nasser M. Abbasi
Posted 9 years ago

That works very nicely. It looks to me like Reap/Sow is a great way when table won't work (as it doesn't for me in this instance). Concise, and functional, thanks!

POSTED BY: Greg
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract