Add each row in a matrix with corresponding element in a vector?
Mostra commenti meno recenti
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
Risposta accettata
Più risposte (1)
Jan
il 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.
Categorie
Scopri di più su Annotations in Centro assistenza e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!