MATLAB [Matlab] Order of precedence in computations

  • Thread starter Thread starter gfd43tg
  • Start date Start date
  • Tags Tags
    Matlab
AI Thread Summary
The discussion focuses on the order of precedence for computations in MATLAB, emphasizing the importance of understanding this hierarchy for correct programming. The order includes parentheses, NOT, arithmetic operations, relational operations, AND, OR, short-circuit AND, and short-circuit OR. A correction is highlighted regarding arithmetic operations, specifically that multiplication takes precedence over addition, which is crucial for accurate calculations. The use of parentheses is encouraged to clarify intended operations. Additionally, a mnemonic, "PNARAOSS," is suggested as a memory aid for recalling the order. A reference link to MATLAB's official documentation on operator precedence is provided for further clarification.
gfd43tg
Gold Member
Messages
947
Reaction score
48
Hello, here is a list of the order of precedence for computations when programming, at least in MATLAB

1. Parentheses (starting with innermost pair)
2. NOT (~) (left to right)
3. Arithmetic operations (left to right)
4. Relational operations (left to right)
5. AND (&)
6. OR (|)
7. Short-circuit AND (&&)
8. Short-circuit OR (||)

I was wondering if there is any rhyme or reason for this order, or is it just something that I need to have committed to memory?
 
Physics news on Phys.org
Double check those rules, correct them, and then memorize them. They are fairly standard in programming and in mathematics. Be sure to check the rules you posted. Line 3 is wrong. It would make 2 + 3 * 5 = (2 + 3) *5 = 25. That is wrong. Multiplication precedes addition so 2 + 3 * 5 = 2 + 15 = 17.

Also, use parentheses liberally to force the calculation that you want.
 
Great. I forgot an old trick for memorizing things, use mnemonics! PNARAOSS!
 

Similar threads

Replies
4
Views
1K
Replies
1
Views
4K
Replies
1
Views
5K
Replies
1
Views
3K
Replies
4
Views
2K
Replies
3
Views
20K
Replies
11
Views
3K
Replies
2
Views
2K
Back
Top