How to use spacing around operator?

9 Ansichten (letzte 30 Tage)
Klaus Webers
Klaus Webers am 3 Dez. 2019
Kommentiert: Walter Roberson am 3 Dez. 2019
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=1
b=2
a+b % as expected
a + b % as expected
(a +b) % as expected
a +b % unexpected !

Antworten (3)

Walter Roberson
Walter Roberson am 3 Dez. 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
Stephen23 am 3 Dez. 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 <):
  1. If there is no space a unary operator has a higher priority than the binary.
  2. 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.

Klaus Webers
Klaus Webers am 3 Dez. 2019
that solved my problem. Thanks a lot.
(as this "Zombi-problem" obviously comes up frequently, MathWorks should probably think about a more rigorous parsing at such instances. In particular, as the error message "Unrecognized function or variable 'a' " in may example case was misleading too.)
  1 Kommentar
Walter Roberson
Walter Roberson am 3 Dez. 2019
It is using rigorous parsing: in every case where you have whitespace (or comma or beginning of an expression) followed by + or - followed by an expression, the + is unary plus, and the minus is unary minus.
The situation is exactly the same as [1 -2] meaning vertcat(1, uminus(2)) rather than vertcat(minus(1,2))
There are some contexts such as listing spin states where unary plus is common to see,
spin = [-1 -1 +1 +2 +1 -2 -1]
and that should not be treated as
spin = [-1, -1+1+2+1, -2, -1]
or
spin = [-1-1+1+2+1-2-1]

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Programming Utilities finden Sie in Help Center und File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by