Using Array and Table Functions in Mathematica. Which is best when

后端 未结 5 1989
执念已碎
执念已碎 2021-01-30 14:38

I have been mostly a Table functions user in mathematica. However I have noticed that in several examples where I used Array instead of Table to express the same result, it ran

5条回答
  •  爱一瞬间的悲伤
    2021-01-30 15:19

    Michael Trott in Programming (pp 707 - 710) address the issue of the differences between Array and Table and argues that as Table has the attribute HoldAll it computes its argument for every call, whereas Array "to the extent possible" computes its argument only at the beginning. This may lead to differences in behaviour as well as speed.

    Attributes[Table]
    

    {HoldAll, Protected}

    Attributes[Array]
    

    {Protected}

    Michael Trott uses the following examples to illustrate the difference in both speed and behaviour. I am taking them verbatim from his book (disc). I hope I am not breaking any rules by doing so.

    Remove[a, i, j];
    a = 0;
    Table[a = a + 1; ToExpression[StringJoin["a" <> ToString[a]]][i, j],
           {i, 3}, {j, 3}]
    

    {{a1[1, 1], a2[1, 2], a3[1, 3]}, {a4[2, 1], a5[2, 2], a6[2, 3]}, {a7[3, 1], a8[3, 2], a9[3, 3]}}

    a = 0;
    Array[a = a + 1; 
     ToExpression[StringJoin["a" <> ToString[a]]], {3, 3}] 
    

    {{a1[1, 1], a1[1, 2], a1[1, 3]}, {a1[2, 1], a1[2, 2], a1[2, 3]}, {a1[3, 1], a1[3, 2], a1[3, 3]}}

    (Note the difference in behaviour)

    To illustrate the effect of precomputing the first argument he uses the following example (again verbatim, p 709).

    o[a = 0;
      Table[a = a + 1; 
       ToExpression[StringJoin["a" <> ToString[a]]][i, j],
             {i, 3}, {j, 3}], {2000}] // Timing
    Do[a = 0;
      Array[a = a + 1; ToExpression[ StringJoin["a" <> ToString[a]]], 
                                                {3, 3}], {2000}] // Timing
    

    {0.700173, Null}

    {0.102587, Null}

    (I am using mma7 on a Mac. My copy of Programming uses v5.1. There may well be an update to this)

    This is not the only difference between Array and Table discussed in Programming, of course.

    I view of other answers, I'll be interested to learn what others think of this point.

提交回复
热议问题