3D matrix multiplication
284 views (last 30 days)
I have two 3D matrices that I need to multiply in a specific way. I need to do for k=1:Z M(:,:,k)=A(:,:,k)*B(:,:,k) end
but I do not want to use for loop because it makes my code run slower and I need to this multiplication for a unsteady flow profile calculation (close to million time steps). Is there a more efficient way to do it?
More Answers (4)
Daniel Frisch on 3 Feb 2020
Matrix multiplication can also be expressed using native Matlab code (times and sum):
% A : (a x c x Z)
% B : (c x b x Z)
Ap = permute(A,[2,1,4,3]); % (c x a x 1 x Z)
Bp = permute(B,[1,4,2,3]); % (c x 1 x b x Z)
M = Ap .* Bp; % (c x a x b x Z)
M = sum(M,1); % (1 x a x b x Z)
M = permute(M,[2,3,4,1]); % (a x b x Z)
Walter Roberson on 24 Jun 2011
There is no built-in MATLAB support for 3D multiplications. The program James refers to is probably a good choice.
By the way, especially in the releases of the last few years, "for" loops are sometimes faster than vectorization, especially for large matricies.