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:
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
|Description||1st Array Size||2nd Array Size||Result Size|
|Vector and scalar|
|Row and column vectors|
|Vector and 2D matrix|
|N-D and K-D arrays|
|Description||1st Array Size||2nd Array Size||Possible Workaround|
|Vectors where a dimension is a multiple of the same dimension in the other array.|
|Arrays with dimensions that are multiples of each other.|
|N-D arrays that have the right amount of singleton dimensions but they're in the wrong order (#1).|
|N-D arrays that have the right amount of singleton dimensions but they're in the wrong order (#2).|
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
Compared to using
bsxfun, implicit expansion offers faster speed of execution, better memory usage, and improved readability of code.
bsxfunvs. implicit array expansion.