MATLAB: How to multiply a vector with each column of a matrix most efficiently

efficientMATLABmatrixmultiplicationvector

Hey there,
I have a vector t (nx1) and a matrix A (nxm). I need to multiply t with each column of A element-wise.
Example: t=[ 1; 2 ]; A=[ 1 2; 3 4 ] => Res=[ 1*1 1*2; 2*3 2*4 ]
So far I have tried 4 versions:
% 1. Looping
for j = 1 : m
res( j ) = t .* A( :, j );
end
% 2. Repmat
tmat = repmat( t, 1, m )
res = tmat .* A;
% 3. diag
res = diag( t ) * A;
% 4. Indexing
A = A( : );
t = t( :, ones( 1, m ) );
t = t( : );
res = A .* t;
res = reshape( res, n, m );
I did some testing on these and found #1 to be (by far) the fastest one, followed by #2 and #4 (about 2 to 3 times slower) and then followed by #3 (8 to 9 times slower). This kind of surprised me, since #1 is the only version not taking advantage of matrix operations in some way.
Does anyone know a faster way to do this? Or could anybody give some reasons for the result I found?

Best Answer

The first question has been addressed, so I'll just throw out a couple of points about the second question.
  • The newer the version you're running, the more benefit you'll see from JIT enhancements, so loops aren't as slow and generally evil as they used to be.
  • Methods 2 & 4 both require a lot more memory and related memory operations. Assuming the variables are large, that's a lot of overhead on top of the calculations. (Also remember that MATLAB requires contiguous memory addresses for arrays.)
  • Method 3 not only incurs the same memory-monkeying penalty, but also needs more calculations.