Why do unary operators like (+) and (-) used in conjunction with numbers not have precedence over the (^) operators while parsing at the MATLAB® command prompt?

3 views (last 30 days)
Unary operators like (+) and (-) should have a higher precedence over the (^) operators while being used in conjuntion with numbers.
When I execute the following command at the MATLAB command window:
-2^2
I obtain the following output:
-4
Why is the negative unary operator associated with a number not given precedence over the (^) operator?
I would like to see the following output:
4

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 27 Jun 2009
The documentation states:
Precedence levels determine the order in which MATLAB evaluates an expression. Within each precedence level, operators have equal precedence and are evaluated from left to right.
MATLAB uses the standard order of operations. The precedence rules for MATLAB are listed below, ordered from highest to lowest precedence level.
1) Parentheses ()
2) Transpose (.'), power (.^), complex conjugate transpose ('), matrix power (^)
3) Unary plus (+), unary minus (-), logical negation (~)
4) Multiplication (.*), right division (./), left division (.\), matrix multiplication (*), matrix right division (/), matrix left division (\)
5) Addition (+), subtraction (-)
6) Colon operator (:)
7) Less than (<), less than or equal to (<=), greater than (>), greater than or equal to (>=), equal to (==), not equal to (~=)
8) Element-wise AND (&)
9) Element-wise OR (|)
10) Short-circuit AND (&&)
11) Short-circuit OR ()
While performing parsing at the MATLAB command prompt, operators are given preference over the number. It should also be noted that for single unary operators like (+) or (-) to have precedence over a (^), they should be enclosed in parenthesis ().
For example:
(-2)^2
would give precedence to the (-) operator yielding the following output:
4
  1 Comment
Walter Roberson
Walter Roberson on 14 Mar 2023
The current documentation https://www.mathworks.com/help/matlab/matlab_prog/operator-precedence.html introduces another level
  • (2) Transpose (.'), power (.^), complex conjugate transpose ('), matrix power (^)
  • (3) Power with unary minus (.^-), unary plus (.^+), or logical negation (.^~) as well as matrix power with unary minus (^-), unary plus (^+), or logical negation (^~). Note: Although most operators work from left to right, the operators (^-), (.^-), (^+), (.^+), (^~), and (.^~) work from second from the right to left. It is recommended that you use parentheses to explicitly specify the intended precedence of statements containing these operator combinations.
  • (4) Unary plus (+), unary minus (-), logical negation (~)

Sign in to comment.

More Answers (0)

Tags

No tags entered yet.

Products


Release

R2008a

Community Treasure Hunt

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

Start Hunting!