Skip to main content
replaced http://mathematica.stackexchange.com/ with https://mathematica.stackexchange.com/
Source Link

Another way to avoid nested loops is with Tuples, as discussed herehere. This nested For loop:

Another way to avoid nested loops is with Tuples, as discussed here. This nested For loop:

Another way to avoid nested loops is with Tuples, as discussed here. This nested For loop:

added 1465 characters in body
Source Link
Verbeia
  • 34.5k
  • 10
  • 110
  • 225

There are many alternative ways to approach various programming problems that do not use loops and are more efficient (and concise) in Mathematica. Most of them execute faster, but even where they do not, they are faster to type: development time matters, too!

Here are some rules of thumb for easier programming and iterating on lists.

1. Most arithmetic operations and many other functions are Listable, meaning that they operate element by element without having to set up a loop or operate explicitly on each element

Addition, multiplication and other standard operations work element by element when they are given conformable vectors, matrices, tensors or generalised lists:

list1 = {a, b, c};
list2 = {e, f, g};
list1 + list2
(* {a + e, b + f, c + g} *)

Listable functions include standard arithmetic and trigonometric functions, Log, Exp, Mod, Abs and a huge range of exponential, Bessel-related and other special functions. The following code returns the whole list of Listable functions:

With[{names = Names["System`*"]}, 
 Pick[names, MemberQ[Attributes[#], Listable] & /@ names, True] ]

(see also the answer by Jagra)

2. In Mathematica, you do not need to declare an empty list and then fill each element in with the desired value one by one

For example, typical procedural programming will create an empty vector, and replace each element in turn to create the desired data.

3. If the i-th element of your list depends on the previous elements, you can construct the list using Nest, Fold, FixedPoint and their variants NestList, FoldList and FixedPointList

Another common use of For loops is when output i+1i depends on output i-1. In Mathematica, this is a canonical use of Nest and Fold, and their NestList and FoldList counterparts that also return the intermediate results. For example, here is the For loop way to create autoregressive noise:

4. You can combine lists in very general ways using Inner and Outer.

There are many alternative ways to approach various programming problems that do not use loops and are more efficient (and concise) in Mathematica.

For example, typical procedural programming will create an empty vector, and replace each element in turn to create the desired data.

Another common use of For loops is when output i+1 depends on output i. In Mathematica, this is a canonical use of Nest and Fold, and their NestList and FoldList counterparts that also return the intermediate results. For example, here is the For loop way to create autoregressive noise:

There are many alternative ways to approach various programming problems that do not use loops and are more efficient (and concise) in Mathematica. Most of them execute faster, but even where they do not, they are faster to type: development time matters, too!

Here are some rules of thumb for easier programming and iterating on lists.

1. Most arithmetic operations and many other functions are Listable, meaning that they operate element by element without having to set up a loop or operate explicitly on each element

Addition, multiplication and other standard operations work element by element when they are given conformable vectors, matrices, tensors or generalised lists:

list1 = {a, b, c};
list2 = {e, f, g};
list1 + list2
(* {a + e, b + f, c + g} *)

Listable functions include standard arithmetic and trigonometric functions, Log, Exp, Mod, Abs and a huge range of exponential, Bessel-related and other special functions. The following code returns the whole list of Listable functions:

With[{names = Names["System`*"]}, 
 Pick[names, MemberQ[Attributes[#], Listable] & /@ names, True] ]

(see also the answer by Jagra)

2. In Mathematica, you do not need to declare an empty list and then fill each element in with the desired value one by one

For example, typical procedural programming will create an empty vector, and replace each element in turn to create the desired data.

3. If the i-th element of your list depends on the previous elements, you can construct the list using Nest, Fold, FixedPoint and their variants NestList, FoldList and FixedPointList

Another common use of For loops is when output i depends on output i-1. In Mathematica, this is a canonical use of Nest and Fold, and their NestList and FoldList counterparts that also return the intermediate results. For example, here is the For loop way to create autoregressive noise:

4. You can combine lists in very general ways using Inner and Outer.

Post Merged (destination) from mathematica.stackexchange.com/questions/7921/…
Source Link
Verbeia
  • 34.5k
  • 10
  • 110
  • 225

There are many alternative ways to approach various programming problems that do not use loops and are more efficient (and concise) in Mathematica.

For example, typical procedural programming will create an empty vector, and replace each element in turn to create the desired data.

vec = Table[0, {100}]; For[i = 1, i <= 100, vec[[i]] = RandomReal[]+2; i++]; vec

In Mathematica, one can use RandomVariate and its cousins directly, or perhaps a Table command. This generalizes to other more complex definitions inside the Table function, and one can use the fact that many arithmetic operations are Listable to avoid looping. (Yes, I know this could be written as RandomReal[{2, 3}, 100], but I wanted a simple example of vectorized arithmetic operations.)

vec = RandomReal[{0, 1}, 100]+2.;

vec = Table[RandomReal[], {100}]+2.;

Another common use of For loops is when output i+1 depends on output i. In Mathematica, this is a canonical use of Nest and Fold, and their NestList and FoldList counterparts that also return the intermediate results. For example, here is the For loop way to create autoregressive noise:

vec = Table[0, {100}]; For[i = 2, i <= 100, 
  vec[[i]] = vec[[i - 1]] + RandomReal[]; i++];

Of course, you have to start at i=2 to avoid adding the zeroth part, which is the Head, List, to the vector.

Here is the FoldList way:

FoldList[#1 + #2 &, 0, RandomReal[{0, 1}, 99] ]

People also often use nested For loops when they want to build up matrices depending on elements of two different vectors. Here is where the generalised structure of Outer is useful:

Outer[N@Kurtosis[#1[#2]] &, {StudentTDistribution, ExponentialDistribution, 
  ChiSquareDistribution}, Range[5, 15] ]

(* {{9., 6., 5., 4.5, 4.2, 4., 3.85714, 3.75, 3.66667, 3.6, 3.54545}, {9., 9., 
  9., 9., 9., 9., 9., 9., 9., 9., 9.}, {5.4, 5., 4.71429, 4.5, 4.33333, 4.2, 
  4.09091, 4., 3.92308, 3.85714, 3.8}} *)

Another way to avoid nested loops is with Tuples, as discussed here. This nested For loop:

l = 0;
For[i = 0, i < 10, i++,
 For[j = 0, j < 10, j++,
  For[k = 0, k < 10, k++,
   Xarray[l] = A[i, j, k];   
   Print[Xarray[l]];
   l++;
   ]
  ]
 ]
Xarray[5]

Can be rewritten faster as:

Xarray = A @@@ Tuples[Range[0, 9], 3];