MATLAB: Add each row in a matrix with corresponding element in a vector

matrixvector

Hi,
I have a matrix, say M = [ 1 1; 2 2; 3 3] and a vector V = [1;2;3], where V(1) adds to M(1,:) and V(2) adds to M(2,:), etc. The way I calculate it is
sum = M + ( V * ones(1,size(M,2)) )
same question for scaling a matrix with a vector.
Answer = M .* ( V * ones(1,size(M,2)) )
I can also use a for loop but I guess it's even slower. I wonder if there is an easier way to get this done?
Thanks

Best Answer

bsxfun(@plus,M,V)
bsxfun(@times,M,V)