Add each row in a matrix with corresponding element in a vector?
6 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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
0 commentaires
Réponse acceptée
Plus de réponses (1)
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.
0 commentaires
Voir également
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!