I got a strange piece of code to debug which to my opinion should throw an exception but instead it produced totally odd results. Reduced it to these two lines:
Since both are 0
. Try A = {1, 2}
then you will get ans = 0
The line of code A{1:2}==A{2:1}
is not checking the equality of two comma-separated lists because 2:1
is an empty array. I think the intended indexing was 2:-1:1
; this will create a comma-separated list but also throw an error since ==
cannot handle the list.
However, it is odd that A{1:2}==A{2:1}
produces a valid output of any kind in my mind. The code is literally saying A{1:2} == A{[]}
, and the question is "what is A{[]}
?" According to my MATLAB R2014b, nothing, which makes some sense, but even a simple double array with an empty index returns an empty double. I guess the actual content, which is what is retreived by {
and }
, is nothing so, yeah.
But then how is MATLAB producing the answer of true
?
Consider the following code from the command window:
>> A = {0,0}; A{1:2} == A{[]}
ans =
1
>> A = {0,1}; A{1:2} == A{[]}
ans =
0
From that, I surmise that MATLAB places the comma-separated list as the first two arguments to eq
and appends A{[]}
nothing to it and interpret it simply as
eq(0,0,A{[]})
eq(0,1,A{[]})
which is, apparently, valid syntax (eq(a,b,)
is not). It is very interesting for a binary operation on elements of a cell array. This also works:
>> A = {[2,3],[3,2]};
>> A{1:2} .* A{[]}
ans =
6 6
>> A{1:2} ./ A{[]}
ans =
0.6667 1.5000
And just for fun, because I'm finding this quite interesting:
>> A = {rand(2),rand(2,1)};
>> A{1:2} \ A{[]}
ans =
0.8984
-0.7841
But I guess it makes sense. The parser finds a token, followed by an infix operator, followed by another token. It resolves the infix operator to its function, and then places the left and right tokens into the argument list in turn.
I guess I just find it a odd about the existence of "nothing"; although that would explain how [1,2,3,]
is valid syntax.
That said, I'm sure this is a quirk of the language and not a bug nor a feature.
Of course, the only way to know what is actually going on is to have an intimate knowledge of how MATLAB is interpreting the cell array expansion and application of the operator. Of course, I do not have this experience nor the source required (I'd imagine).