An algorithm I\'m working on requires computing, in a couple places, a type of matrix triple product.
The operation takes three square matrices with identical dimens
Let n
xn
be the matrix sizes. In Matlab, you can
A
and C
into a n^2
xn
matrix AC
, such that rows of AC
correspond to all combinations of rows of A
and C
.AC
by B
. That gives the desired result, only in a different shape.Code:
AC = reshape(bsxfun(@times, permute(A, [1 3 2]), permute(C, [3 1 2])), n^2, n); % // 1
X = permute(reshape((AC*B).', n, n, n), [2 1 3]); %'// 2, 3
Check with a verbatim loop-based approach:
%// Example data:
n = 3;
A = rand(n,n);
B = rand(n,n);
C = rand(n,n);
%// Proposed approach:
AC = reshape(bsxfun(@times, permute(A, [1 3 2]), permute(C, [3 1 2])), n^2, n);
X = permute(reshape((AC*B).', n, n, n), [2 1 3]); %'
%// Loop-based approach:
Xloop = NaN(n,n,n); %// initiallize
for ii = 1:n
for jj = 1:n
for kk = 1:n
Xloop(ii,jj,kk) = sum(A(ii,:).*B(:,jj).'.*C(kk,:)); %'
end
end
end
%// Compute maximum relative difference:
max(max(max(abs(X./Xloop-1))))
ans =
2.2204e-16
The maximum relative difference is of the order of eps
, so the result is correct to within numerical precision.