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