mtimesm, an efficient nD matrix multiplication routine.

Version 1.0.6 (3.11 KB) by wfH
A wrapper of `MTIMESX` and `PAGEMTIMES`. Created for people who have old matlab or have difficulties in compiling mex-file.
74 Downloads
Updated Thu, 30 Jun 2022 08:28:48 +0000

View License

MTIMESX (`PAGEMTIMES`) is a very efficient matrix multiply routine for n-Dimensional (nD, n > 2) arrays.
However, you have to update your MATLAB (`PAGEMTIMES` was introduced in R2020b), or build a mex-file.
So, I created this function (m-file) for people who have only old matlab or have difficulties in compiling mex-file.
This function follows the same behaviour as MTIMESX (`PAGEMTIMES`).
Run the following codes for demonstration.
ctest = 2000;
nfs1 = 45;
nfs2 = 55;
nks1 = 5;
nks2 = 7;
A = rand(nks1, nks1, nfs1, nfs2);
B = rand(nks2, nks1, nfs1, nfs2);
tic;
for ii = 1:ctest
C1 = zeros(nks1, nks2, nfs1, nfs2);
for ff = 1:nfs1
for gg = 1:nfs2
C1(:,:, ff, gg) = conj(A(:,:, ff, gg)).'*B(:,:, ff, gg).';
end
end
end
t1 = toc
tic, for jj = 1:ctest, C2 = mtimesx(A, 'c', B, 't');end, t2 =toc
tic; for kk = 1:ctest, C3 = mtimesm(A, 'c', B, 't', true);end, t3 = toc
tic; for oo = 1:ctest, C4 = pagemtimes(A, 'c', B, 't');end, t4 = toc
max(abs(C1(:)-C2(:)))
max(abs(C1(:)-C3(:)))
max(abs(C1(:)-C4(:)))
% on my notebook (i7-8550u), t1 ~17 sec; t2 ~1.3 sec; t3 ~3.8 sec; t4 ~0.39 sec.
% `PAGEMTIMES` is the fast in this case.

Cite As

wfH (2024). mtimesm, an efficient nD matrix multiplication routine. (https://www.mathworks.com/matlabcentral/fileexchange/82099-mtimesm-an-efficient-nd-matrix-multiplication-routine), MATLAB Central File Exchange. Retrieved .

MATLAB Release Compatibility
Created with R2020a
Compatible with any release
Platform Compatibility
Windows macOS Linux

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!
Version Published Release Notes
1.0.6

feat: supports "string".
feat: add parameter that specifies to use `pagemtimes` (`mtimesx`) or not.
doc: update demo

1.0.5

add wrapper of `pagemtimes`.

1.0.1

add example and result of comparison .

1.0.0