How can I get the results of a "for" loop for each iteration? For example, I have the following for loop and would like to know how I can get the value of S1 for each i value in the output. Also, I am just wondering is there any way to show the name of the variable in the output (e.g: S1 = {{1,2},{2,3}}) and not just {{1,2},{2,3}}?

Thank you and regards,

For [i=1,10,++

For [j=1,20,++

S1=?

]
]


• You can print it in the loop: Print["S1=" <> ToString@S1]; Jun 6, 2020 at 20:09
• This question has already been posed for hundreds of times and it was virtually always Table what the OP wanted (95% of questions that contain "loop" in its title). (result = Table[<<bla>>,{i,1,10},{j,1,10}]). (This post could be an exception, though...). Jun 6, 2020 at 20:22

As recommend in comments, better to use Table or Do.

how I can get the value of S1 for each i value in the output.

For For you can still use Sow and Reap as well

result = First@Last@Reap@For[i = 1, i <= 3, i++,
For[j = 1, j <= 3, j++,
Sow[{i, j}]
]
] to show the name of the variable in the output (e.g: S1 = {{1,2},{2,3}}) and not just {{1,2},{2,3}}?

What do you mean by show S1={...}? In Mathematica x=1 is assignment, and Mathematica displays back 1, not x=1. To show x=1 you would need to force things into strings. Something like

 ("S = " <> ToString[#]) & /@ result an example with Table application

result = First@Last@Reap@Do[
Do[
Sow[{i, j}]
,
{j, 1, 3}
],
{i, 1, 3}
] Or to make it do something more interesting

result = First@Last@Reap@Do[
Do[
Sow[{ Row[{"S[", i, ",", j, "]=", i + j}], i + j}]
,
{j, 1, 3}
],
{i, 1, 3}
];


And now the actual computation result is stored in result[[All,2]] and the display part is stored separately in result[[All,1]]

result[[All, 2]] result[[All, 1]] // Column • Thank you, Nasser, Can you please provide me an example with Table application. Jun 7, 2020 at 0:36
• @MehdiEbadi fyi, added Table` example Jun 7, 2020 at 0:53