I noticed that for the computation of the trace of a product of two matrices, using Tr[Dot[A,B]]
is a little inefficient. Dot
is computing all the elements of the matrix product, while Tr
only needs the diagonal.
Is there a low-level, or fast implementation of trace-dot in Mathematica? (It needs to be able to work on matrices of mixed datatypes)
Look, I made a top-level implementation of trace-dot that is faster than Trace[Dot[...]]
:
myTrDot[m1_,m2_]:=Total[MapThread[Dot, {m1, Transpose[m2]}]];
exMat1 = RandomVariate[GaussianOrthogonalMatrixDistribution[1000]];
exMat2 = RandomVariate[GaussianOrthogonalMatrixDistribution[1000]];
Tr[Dot[exMat1, exMat2]]; // AbsoluteTiming
(* 0.020229 *)
myTrDot[exMat1, exMat2]; // AbsoluteTiming
(* 0.015503 *)
Symbol
). $\endgroup$Flatten[m1].Flatten[Transpose[m2]]]
is probably the best you can achieve. $\endgroup$