Operator Precedence

The best advice which I've seen on precedence is to remember the following: Within one pair of parentheses, expressions are evaluated from left to right, with the following order of precedence:

  1. exponentiation (^)
  2. transpose (')
  3. multiplication and division (* .* / ./ \ .\)
  4. addition and subtraction (+ -)

The transpose operator binds onto the preceding object.

For example:

>> A = [1 2; 3 4];
>> B = [2 3; 5 7];
>> C = [1 2; 4 8];
>> A + B*C^2'

ans =

    73   290
   174   688

>> A + ( B*( ( C^2 )' ) )

ans =

    73   290
   174   688

Place parentheses around all other operators to indicate the precedence you expect them to take. It also makes sense to place parentheses around the C^2 in A + B*(C^2)' to indicate that that is what you really meant, whereas B*A*B' is quite self explanitory.

Consider:

>> 3:6+2:17<5|5:2*3:22-5*2>19*4&~sin(4:5)>0.2

ans =

     1     0

When you write this, you might know what's going on, but given even one week, you will quickly forget. On the other hand, the following, while still complicated, can be parsed with much greater ease:

>> ((3:(6+2):17) < 5) | (((5:(2*3):(22-5*2)) > (19*4)) & (~sin(4:5) > 0.2));

Not only is this good for you when you come back to look at your own code, but if someone else looks at your code, then they won't have to spend hours trying to determine what it is you meant. Even worse, if there was a bug in your code, first they have to determine what is is you did, then try to determine what it is you meant, and then fix it.

To make your code even more readable, please see the style file.