Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can Matlab compare an empty matrix to a singleton matrix?

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.

like image 506
user1348913 Avatar asked Oct 18 '12 18:10

user1348913


2 Answers

[] (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 array A for equality with the corresponding element of array B, and returns an array with elements set to logical 1 (true) where A and B are equal, or logical 0 (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.

like image 152
Praetorian Avatar answered Sep 29 '22 13:09

Praetorian


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.

like image 44
tmpearce Avatar answered Sep 29 '22 13:09

tmpearce