Possible Duplicate:
MATLAB: How to vector-multiply two arrays of matrices?
Is there a way to contract higher-dimensional tensors in Matlab?
For example, suppose I have two 3-dimensional arrays, with these sizes:
size(A) == [M,N,P]
size(B) == [N,Q,P]
I want to contract A
and B
on the second and first indices, respectively. In other words, I want to consider A
to be an array of matrices of size [M,N]
and B
to be equal length array of [N,Q]
matrices; I want to multiply these arrays element-by-element (matrix-by-matrix) to get something of size [M,Q,P]
.
I can do this via a for-loop:
assert(size(A,2) == size(B,1));
assert(size(A,3) == size(B,3));
M = size(A,1);
P = size(A,3);
Q = size(B,2);
C = zeros(M, Q, P);
for ii = 1:size(A,3)
C(:,:,ii) = A(:,:,ii) * B(:,:,ii);
end
Is there a way to do this that avoids the for-loop? (And perhaps works with arrays of an arbitrary number of dimensions?)
Here is a solution (similar to what was done here) that computes the result in a single matrix-multiplication operation, although it involves heavy manipulation of the matrices to put them into desired shape. I then compare it to the simple for-loop computation (which I admit is a lot more readable)
Note that the above is performing more multiplications than needed, but sometimes "Anyone who adds, detracts (from execution time)". Sadly this is not the case, as the FOR-loop is much faster here :)
My point was to show that vectorization is not easy, and that loop-based solutions are not always bad...