Add each row in a matrix with corresponding element in a vector?
Show older comments
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
Accepted Answer
More Answers (1)
Jan
on 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.
Categories
Find more on Annotations in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!