Why can I add a empty array to a scalar variable, but I cannot add an empty array to a vector?

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?

 채택된 답변

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개)

카테고리

도움말 센터File Exchange에서 Logical에 대해 자세히 알아보기

제품

릴리스

R2021a

태그

아직 태그를 입력하지 않았습니다.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by