Fast multiplication of high dimensional matrix
Better try
s = Total[a b, 3];
or
s = Flatten[a].ArrayReshape[b, {c^3, d, d, d}];
On my machine, the latter is faster. In general, rephrasing summations in terms of Dot
(.
) should lead to more efficient code as Dot
is highly optimized.
The code can be faster if we compile:
cf = Compile[{{a, _Real, 3}, {b, _Real, 6}}, Flatten[a].Flatten[b, 2]];
test = cf[a, b]; // AbsoluteTiming
(* {0.492055, Null} *)
and even faster if compile to C and extract the LibraryFunction[…]
:
cfc =
Compile[{{a, _Real, 3}, {b, _Real, 6}}, Flatten[a].Flatten[b, 2],
CompilationTarget -> C][[-1]];
testc = cfc[a, b]; // AbsoluteTiming
(* {0.234145, Null} *)
Tested on v9.0.1, with TDM-GCC-5.1.0-2 64-bit compiler, "SystemCompileOptions"->"-Ofast"
.