Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

I would like to do a For loop with a jump 2*Pi instead of 1.

For[j = 0, j <= nmax, (incr = 2 Pi), ...]

Actually what I want to do is j = n 2 Pi, where n takes values from 0 to n-1, so the iteration stops at nmax = (n - 1) 2 Pi.

I know this is a pretty trivial question, but I have not found anything equivalent in the "Documentation center".

Please use these tools to format your question. –  Mr.Wizard Mar 14 '13 at 11:46
You posted questions about looping before. Loops are discouraged in Mathematica. Please have a look at this post: mathematica.stackexchange.com/q/18393/193 –  belisarius Mar 14 '13 at 11:50
Arguably this is too trivial to feature in the documentation, although perhaps not since really the only reasonable use of For in Mathematica is for iterations having a very complicated structure that cannot easily be expressed otherwise (which isn't the case here, incidentally). Anyway, you can write whatever you want as the increment. In this case just put j += 2 Pi. –  Oleksandr R. Mar 14 '13 at 12:22

2 Answers 2

up vote 11 down vote accepted

All the iterators in Mathematica work pretty much the same way.

(i, a, b, c}

means the variable is $i$, the starting value is $a$, the ending value is $b$ and the interval is $c$. So in your case,

 {j, 0, nmax, 2 Pi}

would do it. Honestly though, you should be able to program whatever it is you are doing without the For loop at all. For instance:

 Table[i, {i, 1.1, 2.3, Pi/10}]

gives you the values, $i$ in the specified range, and you can of course take any function of them using a construct like

 Table[f[i], {i, 1.1, 2.3, Pi/10}]

which applies the function f to the $i$. Somewhat more concise is

 Range[1.1, 2.3, Pi/10]

Just to get it on the record, the strict answer to your question is

With[{n =. ..}, For[j = 0, j <= (n - 1) 2 Pi, j += 2 Pi, ...]]

For example,

With[{n = 3}, For[j = 0, j <= (n - 1) 2 Pi, j += 2 Pi, Print[j]]]


2 π
4 π

Not very different from what you would do in C.


This site is currently not accepting new answers.

Not the answer you're looking for? Browse other questions tagged .