Add each row in a matrix with corresponding element in a vector?

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

 Respuesta aceptada

Más respuestas (1)

Jan
Jan el 19 de Mzo. de 2012
bsxfun is nicer and faster, but for completeness:
S = M + V(:, ones(1, size(M,2));
A = M .* V(:, ones(1, size(M,2));
PS. Do not use sum as name of a variable, because this shadows tzhe builtin function with the same name.

Categorías

Etiquetas

Preguntada:

Yue
el 18 de Mzo. de 2012

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by