I'm actually the first time using loops in Mathematica. For example, I have:
For[i = 1, i <= n, i++,
For[j = 1, j <= n, j++, ....]
How it is possible now to loop only over i≠j ?
Best regards
In Mathematica you can iterate over i != j
with
Do[<code>, {i, n}, {j, Drop[Range[n], {i}]}]
In a sense it really does the actual iteration desired. The following iterates over all pairs {i, j}
, although <code>
is executed only for i != j
.
Do[If[i != j, <code>], {i, n}, {j, n}]
The difference in speed is minimal but measurable:
With[{n = 2000},
Do[1, {i, n}, {j, Drop[Range[n], {i}]}]
] // AbsoluteTiming
(* {0.216874, Null} *)
With[{n = 2000},
Do[If[i != j, 1], {i, n}, {j, n}]
] // AbsoluteTiming
(* {2.202791, Null} *)
It may seem like a lot, but the execute time of <code>
is likely to be an order of magnitude larger at least.
To save a couple of milliseconds over the first loop, there's this:
With[{n = 2000},
With[{r = Range[n]},
Do[1, {i, n}, {j, Drop[r, {i}]}]
]] // AbsoluteTiming
(* {0.210090, Null} *)
A very small, but seemingly persistent advantage, even with GeneralUtilities`AccurateTiming
.
n = 5; For[i = 1, i <= n, i++, For[j = 1, j <= n, j++, If[i != j , Print["i=", i, " j=", j] ] ] ]
screen shot to confirm the result !Mathematica graphics $\endgroup$Do[If[i != j, ...], {i, n}, {j, n}]
. If you're a beginner, try to avoidFor
in favour of functional constructs andDo
. $\endgroup$Do[..., {i, n}, {j, Drop[Range[n], {i}]}]
is an alternative. $\endgroup$i == j
is not easily deduced from the cited duplicate. It may not be a very deep question but it does have at least one efficient solution peculiar to Mathematica (and perhaps others) that is not the standard Fortran/C/Java solution. $\endgroup$