Looking through the reference.wolfram, I couldn't see an example of how to write a multiple line "for" loop in Mathematica. I need to nest many for-loops in such a way I can do many things in the innermost for-loop. How does one do this in Mathematica?
Here is an example (which you can may be use to demonstrate) of the kind of thing I want to do on Mathematica. In the following, a,b,c are integers such that $1 \leq a,b,c \leq (k-1)$ and w is the m^th of the k^th roots of unity.i.e $w = exp( (2 \pi I m)/k)$ . Now for a fixed value of $k$, I am running through all values of a,b,c and $1 \leq m \leq (k-1)$. And for each set I am evaluating the roots of the polynomial, $p(x) = x^4 - 6x^2 -x(w^{a-c} + w^{c-a} + w^b + w^{-b} + w^{b-c} + w^{c-b} + w^a + w^{-a}) +(3 -w^c - w^{-c} - w^{a+b-c} - w^{-a-b+c} - w^{a-b} - w^{-a+b} )$
To check if all the roots of it are in the interval $[-2\sqrt{2},2\sqrt{2}]$. If yes, then I am printing out the value of a,b and c.
Is such a kind of nested for-loop doable in Mathematica?
The following code I believe runs on Sage/Python. Since this is a quartic equation, I would think that Mathematica has a way of calculating the exact roots in terms of square-roots and then doing the comparison. Also since this polynomial evaluates the eigenvalues of a Hermitian matrix, all roots should be positive.
k=6;
var('x')
for a in range(1,k):
for b in range(1,k):
for c in range(1,k):
q = 1;
for m in range (1,k):
w = exp((2*pi*I*m )/k)
p(x) =
x^4 - 6*x^2 - x*(w^(a-c) +
w^(c-a) + w^b + w^(-b) + w^(b-c) + w^(c-b) + w^a + w^(-a)) +
(3 -w^c - w^(-c) - w^(a+b-c) - w^(-a-b+c) - w^(a-b) - w^(-a+b))
g(x)=real_part(p(x)).simplify()
U = (max([s.rhs() for s in g.solve(x)])).simplify_full()
L = (min([s.rhs() for s in g.solve(x)])).simplify_full()
if (U > 2*sqrt(2)):
q=0
if (L < -2*sqrt(2)):
q=0
if (q == 1):
print "a=",a,"b=",b,"c=",c
Do
orFor
calls... so, yes, doable. Please take a look at the documentation for details. $\endgroup$;
to separate commands, as usual.For[i=0, i < 10, i++, Print[i]; Print[i^2]]
. Pay attention to the difference between,
and;
. But please do not useFor
if you are a beginner in Mathematica ... take a look atDo
instead and try to use functional constructs such asTable
,Map
, etc. whenever possible. $\endgroup$For
has several examples with multipe commands in the body ofFor
. So does the documentation page ofDo
. Whether or not you write them on a single line or you break them across multiple ones makes no difference. $\endgroup$For[i = 1, i <= 3, i++, For[j = i^2, j <= i^2 + 3, j++, Print["{i,j}=", {i, j}] ] ]
$\endgroup$