I was just curious why Matlab can compare an empty matrix to a singleton matrix. In particular
>> [] == [1]
ans =
[]
It just seems odd that it would do that and I'm just wondering why it would do that. This also works for other comparison operations (<=, <, >=, >, !=). It gives an error if the size of the row or column is greater than one.
Thanks!
Edit: I also believe they do this for other operators, such as addition, subtraction, etc.
[]
(empty matrix) is considered a valid matrix representation of size 0x0
by MATLAB. From the documentation for the eq
function, which is what gets called when you use operator ==
to compare matrices, the behavior is as follows:
A == B
compares each element of arrayA
for equality with the corresponding element of arrayB
, and returns an array with elements set to logical1
(true
) whereA
andB
are equal, or logical0
(false
) where they are not equal. Each input of the expression can be an array or a scalar value....
If one input is scalar and the other a nonscalar array, then the scalar input is treated as if it were an array having the same dimensions as the nonscalar input array.
In the comparison [] == [1]
, the left operand is non-scalar (isscalar([])
returns 0
) while the right operand is scalar. So scalar expansion rules apply, and the scalar operand is expanded to the dimensions of the non-scalar operand (in this case 0x0
), and the result is an empty matrix.
From the documentation: If one of the operands is a scalar and the other a matrix, the scalar expands to the size of the matrix.
This is a (slightly odd) general case of the scalar "expanding" to match the size of the matrix it is being compared to. With scalars, the size of the other array can be anything. That isn't true for nonscalar array comparisons.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With