2

For example when would you use a Do loop over a For loop? For which tasks would you use Map, Table, Scan, et cetera? I'm quite new to Mathematica and I don't really get what the advantages of any of these loops are over the standard For loop whose use seems to be so harshly discouraged here on StackExchange.

m_goldberg
  • 107,779
  • 16
  • 103
  • 257
Aron
  • 1,722
  • 1
  • 12
  • 30
  • 3
    Regarding Do vs For: if you can use Do, do not use For. For is less readable and introduces global variables which you'd have to localize manually. For is not generally standard, it is just a convenient construct in some procedural languages. If you compare code using For with code equivalent using Do, it should be clear why Do is usually much more convenient in Mathematica. – Szabolcs Jan 02 '14 at 18:49
  • 2
    Regarding functional vs procedural (Table/Map vs Do), the functional approach typically gives better performance and more concise and readable code in Mathematica. You'll of course need to get used to thinking in terms of these constructs first, and if you're used to writing C code, using these will not come naturally right away. – Szabolcs Jan 02 '14 at 18:51
  • 4
    But in any case - use whatever makes you happy. Once performance becomes important, you´ll notice the differences. Otherwise your question is rather broad... – Yves Klett Jan 02 '14 at 18:55
  • 1
    Do can directly loop over the elements of a list, For can't. Compare Do[Print[i],{i,myList}] vs For[i=1,i<Length[myList],i++,Print[myList[[i]]]]. Of course, Map (/@) is shorter: Print/@myList. – Sjoerd C. de Vries Jan 02 '14 at 18:56
  • 1
    You are new, so you will be tempted to use the most general and powerful functions, and the ones you are most used to from other languages. For, Part, etc. That's great, you can – Rojo Jan 02 '14 at 19:00
  • However, as time goes by, you'll learn more specific functions that will have, when they are applicable, advantages, either in computational efficiency, readability, debugability, etc. – Rojo Jan 02 '14 at 19:01
  • 2
    In the particular case of For, I think it's our collective experience that you very very rarely need to go "so general"; almost always there's a better alternative. – Rojo Jan 02 '14 at 19:02
  • 1
    I recommend you download and read Wagner's book, in particular, chapter 4. You can download the book for free here. – m_goldberg Jan 03 '14 at 03:18
  • Check out this question, http://mathematica.stackexchange.com/questions/7924/alternatives-to-procedural-loops-and-iterating-over-lists-in-mathematica Should cover most of the cases. – FredrikD Jan 03 '14 at 13:13

0 Answers0