MATLAB: How to vectorize a product of a tensor and a vector.

vectorization

How could I vectorize the following loop?
A=randn(10,10,40);
b=randn(10,1);
a=zeros(40,1);
for i=1:40
a(i)=b'*A(:,:,i)*b;
end

Best Answer

Hi Moslem
Here is one way, and it does test out faster than the for loop. How much faster depends on the sizes of what I called m and n, which in your example are 10 and 40. But 2 - 80 times faster, using the method of total tic and toc elapsed time on a lot of repetitions of the same code, and around 15 times faster in the 10 and 40 case. (I know some people on this site are down on tic and toc, but total time for a lot of repetitions seems to me to be a valid real world test). There is more of an advantage the larger n is, which is the length of the for loop.
The code uses reshape, which can be pretty time consuming. [ I thought. See Guillaume's comment ]. There are any number of situations where reshapes and transposes take significantly more time than just using a for loop, but this seems to be a case where matrix manipulation wins out. (There is a transpose at the end, but it's only on a vector).
I tried in on complex to make sure it checked out vs the original.
m = 10;
n = 40;
% A=rand(m,m,n);
% b=rand(m,1);
A = 2*(rand(m,m,n) + i*rand(m,m,n)) - (1+i);
b = 2*(rand(m,1) + i*rand(m,1)) - (1+i);
B = reshape(A,m,m*n);
bB = reshape(b'*B,m,n);
anew = b.'*bB;
anew = anew(:);