# Assign the output of a loop [duplicate]

Possible Duplicate:
Creating a table/Matrix during a For loop

Yet another simple question.

For[i = 1, i < 3, i++,
For[j = 1, j < 3, j++,
Print[{i, j}]
]
]


I want to assign the output to a list, for example like:

tts = {{1, 1}, {1, 2}, {2, 1}, {2, 2}}


All my efforts did not gave me the desired result, but I am sure it is possible. Any suggestions are welcome.

• Have a look at Table. Jan 23, 2013 at 9:23
• ... and at the tutorial Loops and control structures
– kglr
Jan 23, 2013 at 9:26
• if you must use For loops: try tts={};For[..., For[..., Print[{i,j}];AppendTo[tts,{i,j}]]].
– kglr
Jan 23, 2013 at 10:31

When you have some procedural style loop where you want to output things, you can often get quite good results using Sow and Reap:

 For[i = 1, i < 3, i++,
For[j = 1, j < 3, j++,
Sow[{i, j}]
]
]//Reap
(* {Null, {{{1, 1}, {1, 2}, {2, 1}, {2, 2}}}} *)


Sow stores the expression it's given and when Reap is called, it will return a list where the first element is the result of the expression it was given, and the second argument is a collection of all the elements that where sowed during evaluation of that expression. Much more complex interaction is available if you look it up the doc, and often you can solve problems in an entirely procedural style and then just reap the results at the end, and perhaps reformat it if that is desired.

• thx jVincent, is there anyway to get rid of Null in the code, without doing it manually Jan 23, 2013 at 13:41
• @Darwin I'm not sure what you mean with manually. Normally if you are doing something where you only care about the sowed elements, you use code//Reap//Last. Jan 23, 2013 at 14:01
• i needed exactly that Last function! thx Jan 23, 2013 at 15:48

Mathematica tends to use print only for side effects. Also try to avoid the use of For.

You can just use the result of table to the variable.

tts=Table[{i,j},{i,1,3},{j,1,3}];


If you want to look at the contents of tts just enter it into a cell and press shift+return.

• hi, @ b.gatessucks and image_doctor , i would like to use Table but the code i have is bit complex, i am not sure if it is also possible with Tabel my For-Loop looks like this For[p = 1, p < Length[lss] - 20, q = p; dx = lss[[q, 2]]; ds = lss[[q, 3]]; For[r = 1, ds <= dx, ds = ds + lss[[++q, 3]], r++] Print[{lss[[p, 1]], lss[[q, 1]], 10*(lss[[p, 1]] - lss[[q, 1]])}] p++] Jan 23, 2013 at 9:53
• @Darwin You should have started with your real problem / code, as long as it is not too long. Jan 23, 2013 at 11:22