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?
Asked
Active
Viewed 2.3k times
2 Answers
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
-
3I believe that Octave will now do this automatically (they call it "broadcasting"). By default, you will get a warning. – Brent Bradburn May 13 '13 at 04:59
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