Multiply each column of n-by-m matrix by respective constants in m-by-1 vector

13 vues (au cours des 30 derniers jours)
Hi
I have an n-by-m matrix and an m-by-1 vector. I want to multiply each of the m columns in the matrix by a constant specified in my vector.
E.g. if I have a matrix A=[1,2;3,4;5,6] and a vector B=[0.5,2] I want to multiply all the elements in the first column of my matrix by 0.5 and alle the elements en the second column by 2. That is, I would like to get the result C=[0.5,4;1.5,8;2.5,12].
It can easily be done by a loop, but I would like to know if the is a faster way to do this. A built in functionality? Dot-multiply doesn't seem to do the trick :(
Thanks in advance!
- Jesper

Réponse acceptée

the cyclist
the cyclist le 21 Jan 2012
C = bsxfun(@times,A,B);

Plus de réponses (2)

vlad ap
vlad ap le 22 Juil 2021
This also works:
C = B.*A
  2 commentaires
Les Beckham
Les Beckham le 23 Juil 2021
This is the right way to do this. Much simpler.
Steven Lord
Steven Lord le 23 Juil 2021
This works now due to implicit expansion. It would not have worked when the question was first asked in 2012.

Connectez-vous pour commenter.


Jesper
Jesper le 21 Jan 2012
Hi Cyclist
This was exactly what I needed ;)
Thanks!
- Jesper
  1 commentaire
the cyclist
the cyclist le 21 Jan 2012
Happy to help. For future reference, you might want to add a remark like this as a "comment" to an answer (like I did here), rather than as a separate "answer". On questions that have more activity than this one, it helps to keep things organized logically.

Connectez-vous pour commenter.

Community Treasure Hunt

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

Start Hunting!

Translated by