[Matlab] Order of precedence in computations

  • Context: MATLAB 
  • Thread starter Thread starter gfd43tg
  • Start date Start date
  • Tags Tags
    Matlab
Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
3 replies · 3K views
gfd43tg
Gold Member
Messages
949
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!