0
$\begingroup$

How can I obtain the current iteration number of the "Do" command? For example I want $N$ to be my iteration number in the following command:

Do[k = 3 i; Print[{N, k}], {i, 2, 6, 2}]

So I essentially want

Do[k = 3 i; Print[{N, k}], {i, 2, 6, 2}]
{1,6}
{2,12}
{3,18}
$\endgroup$
  • $\begingroup$ In this case, does it not make sense to say Do[k=6i; Print[{i, k}] , {i, 1, 3}] ? But anyway, just set count = 1 before the Do and then Print[{count++, k}] inside... $\endgroup$ – Marius Ladegård Meyer May 1 at 21:05
  • $\begingroup$ Do[k = 3 i; Print[{i/2, k}], {i, 2, 6, 2}] or more simply Do[Print[{i/2, 3 i}], {i, 2, 6, 2}] $\endgroup$ – Bob Hanlon May 1 at 21:07
  • 2
    $\begingroup$ Just to state the obvious, though, have you considered Table[{i, 6 i}, {i, 3}] instead? Typically procedural loops are not the done thing in Mathematica. $\endgroup$ – MarcoB May 1 at 21:44
  • $\begingroup$ Oh my example wasn't what I'm actually running, I only added it to clarify what I'm asking. I want a general method. Chris Degnen's answer below answers my question in a general method. $\endgroup$ – flyingdutchman May 1 at 22:59
  • 1
    $\begingroup$ As a heads up, you cannot use N as a variable, it is a built-in function in Mathematica. $\endgroup$ – evanb May 1 at 23:29
2
$\begingroup$
x = 0;
Do[k = 3 i; Print[{++x, k}], {i, 2, 6, 2}]
| improve this answer | |
$\endgroup$
0
$\begingroup$

Another approach is to use a progress indicator, which shows in real time how the calculations are progressing:

ProgressIndicator[Dynamic[k/(3 20)]]

Table[Pause[0.1]; k = 3 i, {i, 1, 20, 1}]
| improve this answer | |
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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