MATLAB: Does Matlab 2017b has a bug to do addition operation between a 2 x 2 matrix and a column vector

2017bbugimplicit expansionnot a bug

I have been teaching Matlab and I just found an interesting "bug" in Matlab 2017b. For a and b defined below, I was expecting that a + b gives an error since matrix dimensions don't match. But Matlab 2017b "works" just fine.
a = [1 0; 2 1]; b = [3; 2];
With Matlab 2013a, a + b gives "Error: Matrix dimensions must agree."
With Matlab 2017b, a + b gives [4 3; 4 3].
This must be a bug in Matlab 2017b, right?
Thanks a lot!

Best Answer

  • No, this is not a bug. This was a deliberate change made in R2016b.
    Implicit Expansion: Apply element-wise operations and functions to arrays with automatic expansion of dimensions of length 1
    Implicit expansion is a generalization of scalar expansion. With scalar expansion, a scalar expands to be the same size as another array to facilitate element-wise operations. With implicit expansion, the element-wise operators and functions listed here can implicitly expand their inputs to be the same size, as long as the arrays have compatible sizes. Two arrays have compatible sizes if, for every dimension, the dimension sizes of the inputs are either the same or one of them is 1. See Compatible Array Sizes for Basic Operations and Array vs. Matrix Operations for more information.
    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
    For example, you can calculate the mean of each column in a matrix A, and then subtract the vector of mean values from each column with A - mean(A).
    Previously, this functionality was available via the bsxfun function. It is now recommended that you replace most uses of bsxfun with direct calls to the functions and operators that support implicit expansion. Compared to using bsxfun, implicit expansion offers faster speed of execution, better memory usage, and improved readability of code. Compatibility Considerations
    If your code uses any of the element-wise operators or functions listed above and relies on the errors that MATLAB returns from mismatched sizes, particularly within a try/catch block, then your code might no longer catch those errors. This change is because some combinations of input sizes that previously caused errors are now valid.
    For example, in older releases of MATLAB, you could not add a row and a column vector, but those operands are now valid for addition with implicit expansion. In other words, an expression like [1 2] + [1; 2] previously returned a size mismatch error, but now it executes.
    This compatibility consideration does not apply to any uses of bsxfun.