How to use spacing around operator?
13 views (last 30 days)
Spacing around the '+' operator gives unexpected results, in paritcular: a +b (space in front of - but not after the +). Where's the syntactical difference?
% simple example:
a+b % as expected
a + b % as expected
(a +b) % as expected
a +b % unexpected !
Walter Roberson on 3 Dec 2019
Just like -5 is "unary minus", +5 is "unary plus". [a -b] is [a, -1*b] and [a +b] is [a, +1*b] -- except that uminus and uplus have actual associated functions, not just syntactic sugar . https://www.mathworks.com/help/matlab/ref/uplus.html
C = uplus(A) is an alternate way to execute +A, but is rarely used. It enables operator overloading for classes.
Stephen23 on 3 Dec 2019
This is explained in the MATLAB documentation:
And has also been covered several times on this forum, e.g.:
Really the differences between your examples come down to whether an operator can be both unary and binary (e.g. + and -) or is binary only (e.g. * and <):
- If there is no space a unary operator has a higher priority than the binary.
- If the operator is only binary then the space is always optional.
NOTE: All of the examples are code that should never be used in real life. Always use commas for separating elements of an array, if only because it makes the intention clear.