MATLAB Language Implicit array expansion (broadcasting) [R2016b]


Example

MATLAB R2016b featured a generalization of its scalar expansion1,2 mechanism, to also support certain element-wise operations between arrays of different sizes, as long as their dimension are compatible. The operators that support implicit expansion are1:

  • Element-wise arithmetic operators: +, -, .*, .^, ./, .\.
  • Relational operators: <, <=, >, >=, ==, ~=.
  • Logical operators: &, |, xor.
  • Bit-wise functions: bitand, bitor, bitxor.
  • Elementary math functions: max, min, mod, rem, hypot, atan2, atan2d.

The aforementioned binary operations are allowed between arrays, as long as they have "compatible sizes". Sizes are considered "compatible" when each dimension in one array is either exactly equal to the same dimension in the other array, or is equal to 1. Note that trailing singleton (that is, of size 1) dimensions are omitted by MATLAB, even though there's theoretically an infinite amount of them. In other words - dimensions that appear in one array and do not appear in the other, are implicitly fit for automatic expansion.

For example, in MATLAB versions before R2016b this would happen:

>> magic(3) + (1:3)
Error using  + 
Matrix dimensions must agree.

Whereas starting from R2016b the previous operation will succeed:

>> magic(3) + (1:3)
ans =

     9     3     9
     4     7    10
     5    11     5

Examples of compatible sizes:

Description1st Array Size2nd Array SizeResult Size
Vector and scalar[3x1][1x1][3x1]
Row and column vectors[1x3][2x1][2x3]
Vector and 2D matrix[1x3][5x3][5x3]
N-D and K-D arrays[1x3x3][5x3x1x4x2][5x3x3x4x2]

Examples of incompatible sizes:

Description1st Array Size2nd Array SizePossible Workaround
Vectors where a dimension is a multiple of the same dimension in the other array.[1x2][1x8]transpose
Arrays with dimensions that are multiples of each other.[2x2][8x8]repmat, reshape
N-D arrays that have the right amount of singleton dimensions but they're in the wrong order (#1).[2x3x4][2x4x3]permute
N-D arrays that have the right amount of singleton dimensions but they're in the wrong order (#2).[2x3x4x5][5x2]permute

IMPORTANT:
Code relying on this convention is NOT backward-compatible with any older versions of MATLAB. Therefore, the explicit invocation of bsxfun1,2 (which achieves the same effect) should be used if code needs to run on older MATLAB versions. If such a concern does not exist, MATLAB R2016 release notes encourage users to switch from bsxfun:

Compared to using bsxfun, implicit expansion offers faster speed of execution, better memory usage, and improved readability of code.


Related reading: