Does anyone know why this works in MATLAB?
>> 1 ++ 2
ans =
3
Coming from coding in C, python, Java etc, I find it most counterintuitive that this should work at all. Presumably there's something important about the parser that I don't understand?
There's a difference between
plus
anduplus
. I suspect MATLAB takes the first+
asplus
, and all the others asuplus
. Sinceuplus
is by default just "return what's behind", you add1
and2
, and use a lot of "return what's behind" in between.The reason
uplus
exists is to allow operator overloading in classes. The same works in other languages, e.g. in C#, to allow for operator overloading in confined classes.The other reason mentioned in that C# thread is that is changes unsigned shorts to integers, which is not the case for MATLAB:
It does, however, convert a boolean to a double, thanks to Cris Lunego for pointing that out:
The following however remains a mystery to me, inspired by Sanjay Manohar's comment:
The same works with multiple plusses,
[1 +++..+++ 2]
, so with all plusses consecutively in the middle generates[1 2]
, all other combinations (as far as I tested) result in3
. I asked a separate question about this: Why do the plus and unary plus behave strange in array syntax?