8.2. Basic arithmetic operations#

We will begin with using MATLAB to perform basic arithmetic operations since these form the fundamentals of computer programming (it is useful to think of your computer as a very powerful calculator). The arithmetic operators used to perform the basic operations are shown in the table below.

Table 8.1 Arithmetic operations in MATLAB#

Operation

Description

MATLAB syntax

\(x + y\)

addition

x + y

\(x - y\)

subtraction

x - y

\(x \times y\)

scalar multiplication

x * y

\(x \div y\)

scalar division

x / y

\(x^y\)

exponentiation (power)

x ^ y

\(x \operatorname{mod} y\)

modulo (remainder)

mod(x, y)

\(\lfloor x \rfloor\)

floor function (round number to the integer below)

floor(x)

\(\lceil x \rceil\)

ceiling function (round number to the integer above)

ceil(x)

Lets use MATLAB to perform the following calculations. In the command window enter the following commands, pressing the Enter key after each one.

3 + 4
4 - 7
5 * 3
2 / 9
2 ^ 5
mod(23, 4)
floor(11 / 3)
ceil(11 / 3)

Your command window should look like the following.

>> 3 + 4

ans =

     7

>> 4 - 7

ans =

    -3

>> 5 * 3

ans =

    15

>> 2 / 9

ans =

    0.2222

>> 2 ^ 5

ans =

    32

>> mod(23, 4)

ans =

     3

>> floor(11 / 3)

ans =

     3

>> ceil(11 / 3)

ans =

     4

Most of this should be fairly self explanatory.

Note

Note that \(2 \div 9 = 0.\dot{2}\) and MATLAB has outputted the result using 4 decimal places. This is the default format for floating point numbers. To output floating point numbers to 16 decimal places we can use the format long command.

8.2.1. Order of precedence of operations#

MATLAB follows the standard rules for order of operations, i.e., BIDMAS: Brackets > Indices (powers) > Division, Multiplication > Addition, Subtraction. Brackets should be used to override this where necessary.

For example, lets calculate the value of \(\dfrac{1}{2+3}\). Enter the following in to the console and press enter.

>> 1 / (2 + 3)

ans =

    0.2000

Which is the correct result. What if we forget to include the brackets in the calculation. Enter the following into the console and press enter.

>> 1 / 2 + 3

ans =

    3.5000

Which is obviously incorrect. What MATLAB has done here is calculate \(1 \div 2\) and then add 3 to the result. Care should be taken when dealing with arithmetic expressions that use multiple operators.


8.2.2. Exercise#

Exercise 8.1

Use the MATLAB command window to calculate:

  1. \(2 - (3 + 6)\)

  2. \(2(5 - 8(3 + 6))\)

  3. \(2(2 - 2(3 - 6 + 5(4 - 7)))\)

  4. \(\dfrac{2(5 - 4(3 + 8))}{3(4 - (3 - 5))}\)

  5. \(\dfrac{2(4^5)}{81 - 5^2}\)

  6. The remainder when 14151 is divided by 571