Saturday, October 18, 2008

Operators and Operator Precedence


Basic Linear Algebra

Most rules of linear algebra apply in MATLAB. Let's have two matrices x and y. Then for:

1. Addition (+) and Subtraction (-): Both x and y must have the same dimension

2. Multiplication (*): Both x and y must conform

3. Exponentiation (^; raising to a power): This was the topic of Assignment 1, Q1 and Q2. You are required to find this out yourself.

4. Matrix Left Division (\; or mldivide) and Matrix Right Division (/; or mrdivide): As MATLAB help on this says, x \ y computes inv(x) * y and x / y computes x * inv(y), except that internally they are computed a little differently (in particular, by Gaussian elimination). If both x and y are scalars, normal rules of multiplication and division apply, only that x \ y is equivalent to y / x.

5. Other than the 'typical' matrix mutiplication, exponentiation, division discussed as above, MATLAB also has element-by-element multiplication and division. This is done through the ' . ' (dot) operator. It, however, requires that matrices on which the operator is being used have the same dimension (rather obvious, since it refers to element-by-element operations). In particular:

z = x .* y   => z(i, j) = x(i, j) * y(i, j)
z = x .\ y  => z(i, j) = x(i, j) \ y(i, j) = y(i, j) / x(i, j)
z = x ./ y   => z(i, j) = x(i, j) / y(i, j) = x(i, j) / y(i, j)
z = x .^ y   => z(i, j) = x(i, j) ^ y(i, j) = x(i, j) ^ y(i, j)

6. And finally, the transpose operator ('): This we've already covered earlier.

Operator Precedence

Like standard arithmetic, computer arithmetic also follows certain rules when evaluating mathematical expresions. The order is as follows (taken from here):

1. Parentheses ()
2. Transpose (.'), power (.^), 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 (|)

[NB: In the case of a tie, operations are executed left-to-right. For example, x^y^z is interpreted as (x^y)^z. Unary operators are + or - operations that apply to a single element. For example, consider the expression (-4). This is an instance of a unary - since there is only 1 operation. (-4)^2 produces 16. However, -4^2 produces -16 it is interpreted as -(4^2) because - is no longer unary] [ack: Kevin Sheppard]

You can find more on this here. 

The last two in the list above are examples of what are called logical operators. However, before we get to those, let's get the discussion of some basic (but very useful) functions out of the way.

No comments: