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

  • $\begingroup$ 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$
    – Nasser
    Nov 16, 2014 at 18:56
  • 2
    $\begingroup$ Do[If[i != j, ...], {i, n}, {j, n}]. If you're a beginner, try to avoid For in favour of functional constructs and Do. $\endgroup$
    – Szabolcs
    Nov 16, 2014 at 18:59
  • $\begingroup$ Do[..., {i, n}, {j, Drop[Range[n], {i}]}] is an alternative. $\endgroup$
    – Michael E2
    Nov 16, 2014 at 20:58
  • $\begingroup$ To close-voters: It seems to me that the answer to the main question of how to skip 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$
    – Michael E2
    Nov 17, 2014 at 13:39

1 Answer 1


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.


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