... until the collector arrives ...

This "blog" is really just a scratchpad of mine. There is not much of general interest here. Most of the content is scribbled down "live" as I discover things I want to remember. I rarely go back to correct mistakes in older entries. You have been warned :)


How Not to Use For in Mathematica

Someone was asking about this the other day...

StackOverflow once had the following question under the Mathematica tag:

How could I calculate the trace of a n*n matrix, with a for loop? I know that the trace is the sum of the terms on the diagonal, but I haven't got a clue how to do it...

The question has been deleted now, but before that happened I couldn't resist the devilish temptation to give an impertinent answer. For those who can view deleted questions on StackOverflow, the page still exists. For those who can't, my response is quoted below...

Let's start with a 5x5 matrix, m:

m = Partition[Range[25], 5];
m // MatrixForm

which looks like this:

 1   2   3   4   5
 6   7   8   9  10
11  12  13  14  15
16  17  18  19  20
21  22  23  24  25

In Mathematica, there are many ways use For to compute the trace. Here is a simple way:

For[tr=0; i=0, i<10000, ++i, tr+=RandomInteger[10]; tr]; Tr[m]

More efficient ways include:

Unevaluated[For[tr=0; i=1, i <= Dimensions[m][[1]], ++i, tr += m[[i,i]]]; tr] /.
  _For :> (tr = Tr[m])


For[,True,,Return[Tr[m], For]]


For[,False,,] /. Null -> Tr[m]


Blog Archive