Arithmetic operations
The most common arithmetic operations in MATLAB are
Operation | Symbol |
Addition | + |
Subtraction | - |
Multiplication | * |
Division | / |
Powers | ^ |
This is just like on a calculator, in spreadsheets (Excel) and most programming languages.
Order of Operations
In MATLAB, and many other programming languages, operations are performed in the following order:
- expressions in brackets: ( ) ;
- powers: ^ ;
- multiplication and division: * , / ;
- addition and subtraction: + , - .
In ordinary written mathematics we sometimes leave out brackets and rely on the fact that an intelligent human will understand where they ought to go. In contrast, computers obey exactly the rules for evaluating expressions. If you are unsure, adding some extra brackets (parentheses) will not hurt.
Examples
To see how MATLAB will apply these rules, try typing the following commands in a MATLAB command window. The same arithmetic operators are used in each example, but the result may be different.
You do not need to type the MATLAB prompt
In the first case the multiplication has higher precedence than the addition so 2 * 3 = 6 is calculated first, then 1 is added to give 7.
In the second case the brackets force the 1 and 2 to be added first giving 3, which is then multiplied by 3 to give 9.
In the first case the division has higher precedence so 4 / 2 is evaluated first to give 2, then 1 is added to give 3.
The result is the same as the first case. Why?
The brackets force the addition to be evaluated first to give 3, then 4 is divided by 3 to give 1.3333
In the first case 8 is squared first to give 64, which is then divided by 3 to give 21.3333
In the second case, 8 is raised to the power 2/3 giving 4.
In the second case the brackets force 2 * 3 = 6 to be evaluated first, then 12 / 6 = 2. This version is usually clearer.
In the first case 43 = 64 is evaluated first, which is then squared to give 4096.
In the second case 32=9 is evaluated first and then 49=262144.
This is the same as the first case, but clearer.
Self-test Exercise
Write a MATLAB command to enter a fraction with 17.1 + 20.3 in the numerator and 36.5 + 41.8 in the denominator.
Note that the answer is NOT "17.1 + 20.3/36.5 + 41.8". Why not?
Answer: (17.1 + 20.3) / (36.5 + 41.8)
You must use brackets, otherwise the division is done before either addition.
Use the mouse to select the text between the word "Answer" and here to see the answer.
Summary
MATLAB evaluates arithmetic expressions precisely by the rules for order of precedence.
Use brackets as needed to get the correct expression or make the expression clear!