Problem: explicit index contractions for matrices using the Sum
command take too long, and I want to improve the performance for complicated computations.
Let me give you an example, let M
be a random $8\times 8$ matrix:
M = RandomReal[{0, 1}, {8, 8}];
If I want to multiply 8 of those matrices and take a trace I would write something like
Tr[M.M.M.M.M.M.M.M]
This gives me the result almost instantaneously.
I can write the same computation in a more complicated way by using the Sum
or equivalently ParallelSum
command and writing out the index contractions explicitly:
ParallelSum[
M[[i1, i2]] M[[i2, i3]] M[[i3, i4]] M[[i4, i5]]
M[[i5, i6]] M[[i6, i7]] M[[i7, i8]] M[[i8, i1]],
{i1, 1, 8}, {i2, 1, 8}, {i3, 1, 8}, {i4, 1, 8},
{i5, 1, 8}, {i6, 1, 8}, {i7, 1, 8}, {i8, 1, 8}]
This computation takes literally ages, and I actually never waited till the end to see the final result.
Question: how can I implement explicit contractions like in the last example efficiently? I need to do this because in more complicated computations with multidimensional tensors contractions cannot be written using matrix multiplication and traces. What is the best practise for this kind of computations?
Dot
(which is more general than just matrix multiplication),Transpose
,Flatten
, andTr
? I'm willing to bet that it can be done with those optimized built-ins. Also, at least, please provide an example of one that can't be done with matrix multiplication andTr
for us to play with. $\endgroup$MatrixPower[]
, right? $\endgroup$