From: James Tursa on
"Nathan Thern" <thern(a)raytheon.com> wrote in message <hlk70i$kho$1(a)fred.mathworks.com>...
> Hello,
> I have an application which originally multiplied 5 4x4 matrices together like so:
>
> R = M * N * O * P * Q;
>
> My application has changed somewhat, so now the O matrix is 4x4xZ with Z > 1.
> I changed my code to:
> R = zeros(4,4,Z);
> for x = 1:Z
> R(:,:,x) = M * N * O(:,:,x) * P * Q;
> end
>
> But I wanted to figure out how to do it in one statement again and get rid of the for-loop. So I started working with an example where Z=3.
>
> If my intermediate results for M * N * O(:,:,x) are A, B and C, and my end results for M * N * O(:,:,x) * P * Q are D, E and F, then I can do
> ABC = M * N * reshape(O,4,[]);
> to get ABC = [ A B C ]
> However, now to multiply into P and Q I want my intermediate result shaped like
> ABC = [ A; B; C ]
> In order to do this I have to do some permuting as well as reshaping:
> ABC = reshape(permute(reshape(M * N * reshape(O,4,[]),4,4,[]),[1 3 2]),[],4)
> This gives me
> ABC = [ A; B; C ]
> So my final statement is
> DEF = reshape(permute(reshape(M * N * reshape(O,4,[]),4,4,[]),[1 3 2]),[],4) * P * Q;
> This gives me a result in the form of
> DEF = [ D; E; F ]
>
> It seems to me that there must be a less obfuscated way to do this in one statement. I would appreciate any comments.
>
> regards,
> Nate Thern

R = mtimesx(mtimesx(M*N,O),P*Q);

This uses my mtimesx Fast Matrix Multiply utility which can be found here in the FEX:

http://www.mathworks.com/matlabcentral/fileexchange/25977-mtimesx-fast-matrix-multiply-with-multi-dimensional-support

mtimesx uses BLAS calls in the background (so the basic matrix multiply is just as fast as MATLAB) and has automatic nD support for calculations like you are doing (so it avoids looping in your MATLAB code).

James Tursa