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 *)
Answer
myTrDot2 =
Compile[{{m1, _Real, 2}, {m2, _Real, 2}},
Flatten[m1].Flatten[Transpose[m2]]]
exMat1 = RandomVariate[GaussianOrthogonalMatrixDistribution[10000]];
exMat2 = RandomVariate[GaussianOrthogonalMatrixDistribution[10000]];
Tr[Dot[exMat1, exMat2]]; // AbsoluteTiming
myTrDot[exMat1, exMat2]; // AbsoluteTiming
myTrDot2[exMat1, exMat2]; // AbsoluteTiming
{18.0692, Null}
{1.64879, Null}
{1.42026, Null}
Comments
Post a Comment