Skip to main content

performance tuning - Alternatives to procedural loops and iterating over lists in Mathematica


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 or Do loop, and are there other useful Mathematica constructs, aside from RandomVariate/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:




  1. The For loop:


    For[i = 1, i <= 10, i++, list[[i]] = func[ list[[i]]]


  2. The Table function operating over each part of a list in turn:



    Table[func[ list[[i]] ], {i, Length[list]}]


  3. 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]}

    ];
    t


  4. Mapping a function onto each element of a list:


    (3 - #)/(7 * #) & /@ list


  5. 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:



  1. Defining an empty list

  2. Setting up a loop


  3. Optionally define a variable (usually not localised) to equal the iterator, which is then used in subsequent calculations within the loop

  4. 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

  5. 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