While there are some cases where a For
loop might be reasonable, it's a general mantra – one I subscribe to myself – that "if you are using a For
loop in Mathematica, you are probably doing it wrong". But For
and Do
loops are familiar to people who already know other programming languages. It is common for new Mathematica users to rely on loop constructs, only to become frustrated with performance or code complexity.
My question is: are there some general rules of thumb that would help new users select the appropriate alternative to a procedural
For
orDo
loop, and are there other useful Mathematica constructs, aside fromRandomVariate
/Nest
/Fold
/Inner
/Outer
/Tuples
that they should know about in order to avoid those loops?
In particular, there are a number of ways of iterating over lists:
The
For
loop:For[i = 1, i <= 10, i++, list[[i]] = func[ list[[i]]]
The
Table
function operating over each part of a list in turn:Table[func[ list[[i]] ], {i, Length[list]}]
The
Do
loop operating over each part of a list in turn:lst = {88, 42, 25, 75, 35, 97, 12};
t = 9;
Do[
x = lst[[i]];
t += Mod[x, t],
{i, 1, Length[lst]}
];
tMap
ping a function onto each element of a list:(3 - #)/(7 * #) & /@ list
And for nested lists, there are constructs like
MapThread
:f = Mod[#, #2] Floor[#3/#] &;
a = {{18, 85, 22, 20, 39}, {17, 67, 76, 96, 58}, {40, 97, 56, 60, 53}};
MapThread[f, a]
New users of Mathematica will usually pick options 1 or 3 and use C-style or Matlab approaches that involve the following multistep process:
- Defining an empty list
- Setting up a loop
- Optionally define a variable (usually not localised) to equal the iterator, which is then used in subsequent calculations within the loop
- Within each loop iteration, use the local variable defined to equal the iterator to redefine each element of that list in turn according to some function
- If the list is multidimensional, nest another loop inside that.
What are some useful guides to help users coming from other languages to Mathematica to improve the conciseness and efficiency of their code by avoiding unnecessary loops?
Comments
Post a Comment