Why can I add a empty array to a scalar variable, but I cannot add an empty array to a vector?
7 views (last 30 days)
Show older comments
MathWorks Support Team
on 4 Oct 2021
Answered: MathWorks Support Team
on 4 Oct 2021
In MATLAB it is possible to add an empty array to a scalar variable, namely,
>> 5 + []
and this results in an empty array. However, adding an empty array to a vector results in a dimension mismatch, namely,
>> [2 3] + []
namely,
Error using +
Arrays have incompatible sizes for this operation.
Why can I add a empty array to a scalar variable, but I cannot add an empty array to a vector?
Accepted Answer
MathWorks Support Team
on 4 Oct 2021
This behavior is stated in the documentation and follows the rules of implicit expansion, i.e., dimensions need to match or one of the dimensions must be 1 and the result will have the non-1 result as dimension. The following facts are valid for the aforementioned examples:
>> 5 + [] % 1x1 + 0x0 --> works and result is 0x0, since mismatches have a 1 to compensate.
>> [2 3] + [] % 1x2 + 0x0 --> does not work, since for the 2nd dim, 2 meets 0.
The corresponding documentation page where the implicit expansion is discussed is provided below,
The rules of implicit expansion are the same for empty arrays or arrays that have a dimension size of zero. The size of the dimension that is not equal to 1 determines the size of the output. This means that dimensions with a size of zero must be paired with a dimension of size 1 or 0 in the other array, and that the output has a dimension size of 0.
0 Comments
More Answers (0)
See Also
Categories
Find more on Matrices and Arrays in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!