2
$\begingroup$

I have a list of 2 by 2 matrices and I want the list of their traces. I have been using

Map[Tr,mylistofmatrices]

But I wonder if there is a way to make Tr Listable so I can just call

Tr[mylistofmatrices]
$\endgroup$
1
7
$\begingroup$

No, there isn't. There are several reasons for that:

  • Tr operates on tensors of arbitrary rank, not just matrices

  • Listable functions will automatically thread to the deepest level of lists, so if you set Tr to be Listable, it'll individually wrap each deepest element of a nested list, e.g. Tr[{{1,2},{3,4}}] would transform to {{Tr[1], Tr[2]}, {Tr[3], Tr[4]}}.

Just use Map, which is unambiguous and takes just one extra character to type ... Tr /@ list vs Tr @ list.

$\endgroup$
0
3
$\begingroup$

If you have version 10 or later you can use operators forms, i.e. Map[Tr] acts as a function:

mylistofmatrices = {{{a, b}, {c, d}}, {{q, r, s}, {t, u, v}}};

Map[Tr][mylistofmatrices]
{a + d, q + u}

This is a subtle difference but it may be useful nevertheless.

If you always want the trace of a tensor with a specific array depth you can check for that. If you want only a two-dimensional tensor (which is what you state in your question) you can use MatrixQ; otherwise look at ArrayDepth and TensorRank. One implementation:

myTr[m_?MatrixQ] := Tr[m]
myTr[{m__?MatrixQ}] := Tr /@ {m}

Now:

myTr @ foo
myTr @ {1, 2, 3}
myTr @ {{a, b}, {c, d}}
myTr @ mylistofmatrices
myTr[foo]

myTr[{1, 2, 3}]

a + d

{a + d, q + u}
$\endgroup$
5
  • 1
    $\begingroup$ Re: TensorRank[], how very odd. "Introduced in 2012 (9.0)", and yet it's been around since the first version, and at one point "replaced by ArrayDepth". $\endgroup$ May 21 '15 at 16:48
  • $\begingroup$ @Guess The poor developers are run every which direction. Rube Goldberg would love the present state of affairs. :o) $\endgroup$
    – Mr.Wizard
    May 21 '15 at 16:50
  • $\begingroup$ I am slightly frightened whenever I get into a situation where it turns out that I know even slightly more than the supposed experts… :o $\endgroup$ May 21 '15 at 16:56
  • $\begingroup$ @Guess I wouldn't jump to that conclusion in this case; I imagine the developers are well aware that this was a v1 function but someone probably told them to pretend that it was a new function in v9 as that has better publicity than "oops, we deprecated that but now see value in reintroducing it and applying it to this shiny new tensor stuff we'd like you to upgrade for" ;-) $\endgroup$
    – Mr.Wizard
    May 21 '15 at 16:59
  • $\begingroup$ Good point; but then, I spent some amount of time bitching about why they renamed TensorRank[], so reading that "new" bit gave mixed emotions. :) Oh well, glad that it's "back". $\endgroup$ May 21 '15 at 17:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.