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];