I was reading the documentation for matlab on element-wise multiplication and I came across this example:
Create a row vector a and a column vector b, then multiply them. The 1-by-3 row vector and 6-by-1 column vector combine to produce a 6-by-3 matrix with all combinations of elements multiplied.
The documentation sure showed the output, but how did they get to that output matrix of size6,3
? Which was obtained from multiplying a column vector b
of size 6,1
, and a row vector a
of size 1,3
using the methods explained in the document.
This is called broadcasting. When one dimension is 1 while the other is bigger, the unit dimension is expanded, as if with repmat
:
6 1 : column
1 3 : row
------
6 3 : result
Given
a = 1:3
b = [1:6]'
a .* b
is roughly equivalent to
a2 = repmat(a, 6, 1)
b2 = repmat(b, 1, 3)
a2 .* b2
But of course broadcasting is much more memory efficient.