Monthly Archives: September 2014

[Matlab] Operator Precedence

[In this post I will talk about one subtle difference between the operator precedence in C and Matlab, you can start from the third paragraph if you are familiar with the notion of operator precedence.]

Operator Precedence is really important. I have learnt it the hard way earlier this week. I decided to write about it, hopefully after reading this, you will never fall into the same trap like I did.

For those who are not familiar with the terminology, operator precedence (also called the order of operation) refers a set of rules that defines the order of calculations/procedures should follow in a given mathematical operation. It’s basically what we all learned in first grade. Multiplication has higher priority than addition. 1+2×3 = 7 not 9, because the multiplication operation goes first.

In mathematics, people follow the same rule for operator precedence. However, when it comes to programming, the situation can be a little different. Different programming languages may define operator precedence differently. The specific precedence rule that threw me off involves the comparison operators. In C-style languages, comparison operators are divided into two different categories: (1) the equal comparisons, including equal (==) and not equal (!=)  and (2) the unequal comparisons, including smaller than (<), greater than (>), smaller than or equal to (<=), and greater than or equal to (>=). In C-style languages, the unequal comparisons (i.e. >, <, <=, >=) precedes the equal comparisons (i.e. ==, !=).





and will evaluate to be true.

However, in Matlab, the equal comparisons and the unequal comparisons have the same level of priority. The same expression:


will execute from left to right, as:


and evaluate to be false (note, there are also type conversions going on here).

This can be pretty difficult to catch, especially when you are like me, having this hard wired C-style operator precedence in my head and trying to do some complicated matrix comparison in one line of Matlab code.

So, I have learned my lesson: (1) know the operator precedence. (2) parentheses are my friends. (3) break one line of complicated code into several lines of simpler codes when necessary.

I hope you learned something useful, and see you until next time.