3
$\begingroup$

Suppose I have the matrix

 MatrixForm[A = {{8, 1, 6}, {3, 5, 7}, {4, 9, 2}}]

with Tr[A] I can sum the elements of the main diagonal. To sum the elements of the opposite diagonal, which runs from upper right to lower left I type

Tr[Reverse[A]]

How can I obtain the desired result differently?

$\endgroup$
8
$\begingroup$

First I thought "Why would you want to do that?" but using Reverse has indeed some performance issues. Here is an alternative involving Extract and Total:

A = RandomReal[{-1, 1}, {10000, 10000}];
a = Tr[Reverse[A]]; // AbsoluteTiming // First
b = Total[Extract[A, Transpose[{Range[Length[A]], Range[Length[A], 1, -1]}]]]; // 
  AbsoluteTiming // First
a == b

0.487564

0.000616

True

$\endgroup$

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.