21

Is there an in-built function in octave to multiply each column of a m X n element-wise with a column vector of size m that is more efficient than using a loop?

Adam Lear
  • 38,111
  • 12
  • 81
  • 101
6nagi9
  • 534
  • 2
  • 7
  • 23

2 Answers2

39

You can replicate the vector as many times as you need to turn it into a m x n matrix as well and then use the built-in element-wise multiplication operator .*:

>> A = [1 2; 3 4; 5 6];
>> B = [1; 2; 3];

>> A .* repmat(B, 1, columns(A))
ans = 

    1    2
    6    8
   15   18
Adam Lear
  • 38,111
  • 12
  • 81
  • 101
3

I haven't tried Anna Lear's answer but as nobar commented in that answer, Octave now does broadcasting. So you just have to do A.*B. You will get a warning that'll say an automatic product broadcasting is being applied

>> A.*B
warning: product: automatic broadcasting operation applied
ans =

 1    2
 6    8
15   18
user3344591
  • 567
  • 5
  • 21