Tr


Tr computes the trace of a rectangular matrix.  Some examples are given in
the next two cells.

Clear["Global`*"] ;  Tr[{{a, b, c, d, e}, {v, w, x, y, z}}]

a + w

mtrx = { {a1, a2, a3},  {b1, b2, b3},  {c1, c2, c3} } ;  Tr[mtrx, Max]

Max[a1, b2, c3]

Computing the trace of a matrix is a common operation in linear algebra.   Mathematica generalizes the notion of trace to make it so we can compute Tr[vector].   When Tr is given a vector we get the sum of the elements.  The use of (Tr) in  the next cell does the same thing as Plus @@ {a, b, c, d}.  Rob Knapp showed us that when a vector is a packed array  (Tr[vector] ) is much faster than (Plus @@ vector).  My timing tests vary, but I found Tr to be at least 25 times faster  when given a packed array.

Tr[{a, b, c, d, e}]

a + b + c + d + e


Next I give some examples that go down to different levels of a tensor.

t1 = {{{{a1, b1}, {a2, b2}, {a3, b3}}, {{c1, d1}, {c2, d2}, {c3, d3}}},  {{{e1, f1}, {e2, f2}, {e3, f3}}, {{g1, h1}, {g2, h2}, {g3, h3}}}} ;    Dimensions[t1]

{2, 2, 3, 2}


By default Tr works at the deepest level, which is level 4 in this example.

Tr[t1]

a1 + h2

Tr[t1, Plus, 4]

a1 + h2

t1[[1, 1, 1, 1]] + t1[[2, 2, 2, 2]]

a1 + h2

Next Tr is used at level 3.

Tr[t1, Plus, 3]

{a1 + g2, b1 + h2}

t1[[1, 1, 1]] + t1[[2, 2, 2]]

{a1 + g2, b1 + h2}

Next Tr is used at level 2.

Tr[t1, Plus, 2]

{{a1 + g1, b1 + h1}, {a2 + g2, b2 + h2}, {a3 + g3, b3 + h3}}

t1[[1, 1]] + t1[[2, 2]]

{{a1 + g1, b1 + h1}, {a2 + g2, b2 + h2}, {a3 + g3, b3 + h3}}

Finally Tr is used at level 1.

Tr[t1, Plus, 1]

{{{a1 + e1, b1 + f1}, {a2 + e2, b2 + f2}, {a3 + e3, b3 + f3}}, {{c1 + g1, d1 + h1}, {c2 + g2, d2 + h2}, {c3 + g3, d3 + h3}}}

t1[[1]] + t1[[2]]

{{{a1 + e1, b1 + f1}, {a2 + e2, b2 + f2}, {a3 + e3, b3 + f3}}, {{c1 + g1, d1 + h1}, {c2 + g2, d2 + h2}, {c3 + g3, d3 + h3}}}


Created by Mathematica  (May 16, 2004)

Back to Ted’s Tricks index page