0
$\begingroup$

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=?

       ]
]```


$\endgroup$
2
  • $\begingroup$ You can print it in the loop: Print["S1=" <> ToString@S1]; $\endgroup$
    – flinty
    Jun 6, 2020 at 20:09
  • 6
    $\begingroup$ 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...). $\endgroup$ Jun 6, 2020 at 20:22

1 Answer 1

2
$\begingroup$

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}]
      ]
     ]

Mathematica graphics

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

Mathematica graphics

an example with Table application

result = First@Last@Reap@Do[
     Do[
      Sow[{i, j}]
      ,
      {j, 1, 3}
      ],
     {i, 1, 3}
     ]

Mathematica graphics

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]]

Mathematica graphics

result[[All, 1]] // Column

Mathematica graphics

$\endgroup$
2
  • $\begingroup$ Thank you, Nasser, Can you please provide me an example with Table application. $\endgroup$ Jun 7, 2020 at 0:36
  • $\begingroup$ @MehdiEbadi fyi, added Table example $\endgroup$
    – Nasser
    Jun 7, 2020 at 0:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.