0
|
12475 Views
|
3 Replies
|
0 Total Likes
View groups...
Share
GROUPS:

# How to generate a list from a loop?

Posted 10 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
3 Replies
Sort By:
Posted 10 years ago
 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 10 years ago
 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 10 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!