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

6 vues (au cours des 30 derniers jours)
Yue
Yue le 18 Mar 2012
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

Réponse acceptée

James Tursa
James Tursa le 18 Mar 2012
bsxfun(@plus,M,V)
bsxfun(@times,M,V)

Plus de réponses (1)

Jan
Jan le 19 Mar 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.

Catégories

En savoir plus sur Logical dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by