# Matlab as a graphing scientific calculator (Part I)

## Topics in this lab

## Introduction

In this lab, we will explore the features of Matlab that allow you to do
many of the simple tasks that you might have previously done on a
scientific calculator.

For Parts II and III of this lab, use the following links.

Back to the top

## Guide to lab exercises

Here is the color coding for the exercises you will find on this page. Help on a topic is shown in green as

>> help sin sin Sine of argument in radians. sin(X) is the sine of the elements of X. ...............

Numerical input is shown in blue and the output is shown in white as

>> 1+1

ans = 2

Matlab keywords such as help, sin, sqrt, and many other reserved words will also be shown in white.

And if the output of a command is too long to print here, we will use

...............

Back to the top

## Getting help in Matlab

The most useful topics for Lab 1 are
below. Try these out at the command prompt by typing
help followed by a topic.

>> help arith Arithmetic operators. + Plus. X + Y adds matrices X and Y. X and Y must have the same dimensions unless one is a scalar (a 1-by-1 matrix). A scalar can be added to anything. .............

for help on elementary arithmetic operations and associated symbols,

>> help elfun Elementary math functions. Trigonometric. sin - Sine. sind - Sine of argument in degrees. sinh - Hyperbolic sine. asin - Inverse sine. .............

For help on changing the default formatting behavior,

>> help format format Set output format. format with no inputs sets the output format to the default appropriate for the class of the variable. For float variables, the default is format SHORT. .............

Here is how you can get general help.

>> help help HELP topics: .................... matlab/demos - Examples and demonstrations. matlab/graph2d - Two dimensional graphs. matlab/graph3d - Three dimensional graphs. matlab/graphics - Handle Graphics. matlab/plottools - Graphical plot editing tools matlab/scribe - Annotation and Plot Editing. matlab/specgraph - Specialized graphs. matlab/uitools - Graphical user interface components and tools toolbox/local - General preferences and configuration information. matlab/general - General purpose commands. matlab/ops - Operators and special characters. matlab/lang - Programming language constructs. matlab/elmat - Elementary matrices and matrix manipulation. matlab/randfun - Random matrices and random streams. matlab/elfun - Elementary math functions. matlab/specfun - Specialized math functions. matlab/matfun - Matrix functions - numerical linear algebra. matlab/datafun - Data analysis and Fourier transforms. matlab/polyfun - Interpolation and polynomials. matlab/funfun - Function functions and ODE solvers. matlab/sparfun - Sparse matrices. matlab/strfun - Character strings. matlab/iofun - File input and output. ...............

You can also access help by using the doc command.

>> doc arith

The output will be the help document in a new window.

Back to the top

## Basic data types in Matlab

For scientific computing, we deal almost exclusively with floating point
numbers, represented in Matlab as type double. In Matlab, the double is the default, and assumed for all numeric
data, unless otherwise specified.

Before continuing, we will set the formatting. More on this below.

`>> format short`

We can enter numbers at the Matlab prompt as single numbers

>> -47

ans = -47

>> 12756

ans = 12756

or as a comma separated list of values

>> 5, -34567, 4.36, 546.56987654, -7e-12, 4.5e200

ans = 5 ans = -34567 ans = 4.3600 ans = 546.5699 ans = -7.0000e-12 ans = 4.5000e+200

All values above are of type double. The last two values are written
using scientific notation. The first two values appear to be integer
values, but Matlab does not distinguish between integer and double
values, unless we specifically tell it to. So even the first two values
are stored as doubles. To those of you who are more familiar with
strongly typed languages, Matlab's way of representing all numeric data
in the same way may seem rather crude. But it means that we don't have
to worry type conversions. For example, the values 1/3 and 1.0/3.0 are exactly
the same. In compiled languages such as C, C++ or Fortran, the value of
1/3 would be truncated to the nearest integer,
which is 0 in this case.

The other data type that we will
encounter frequently is the string type. For example,

>> 'hello', 'goodbye', '%$&#!@$%*&()', '5 Easy Pieces'

ans = hello ans = goodbye ans = %$&#!@$%*&() ans = 5 Easy Pieces

are all examples of string, or character, dataypes. Strings are used in printing output, for example. Note the use of the single quotes ' ' rather than double quotes " ".

Back to the top

## Introduction to arithmetic operators

Matlab has all of the familar arithmetic operators: addition, subtraction, multiplication, division and exponentiation. Type each of the following expressions at the Matlab prompt and hit enter.

Multiplication

>> 2*33

ans = 66

Division

>> 45.1/9

ans = 5.0111

Addition

>> 21 + 100

ans = 121

and subtraction,

>> 10 - 22

ans = -12

Exponentiation

>> 2^4

ans = 16

Matlab follows rules about the order of operations, and so complex arithmetic expressions can be strung together using multiple operators. This expression combines addition and substraction.

>> 5 + 4 + 3 - 2 + 5 - 100

ans = -85

Here is an example that combines multiplication and division.

>> 25/5*4/2/5/2

ans = 1

Note that when no parenthesis are used, the exponentiation operator takes precedence over other operations. The following expression is equal to $5 \times 25$, and not $25^2$, which you might expect if you apply the operators sequentially.

>> 5*5^2

ans = 125

Note that you have to be careful when using fractional exponents. Without parenthesis (discussed below), the following expression is equivalent to $16/2 = 8$, not $16^{1/2} = 4$.

>> 16^1/2

ans = 8

The use of the negative sign takes precendence over exponentiation. For example,

>> 16*2^-2

ans = 4

is equivalent to $16 \times 2^{-2} = 4$.

Here is one final example that uses all five operators. Do you see how
the result is obtained?

>> 4*5/2^2+9^1/3-12

ans = -4

Back to the top

## Using parenthesis

By using parentheses, we can form complex arithmetic expressions. Note that all parentheses must be matched or you will get an error. Also, note that the expected order of operations is followed.

>> (3 + 4*6)/(2 - 34.1)

ans = -0.8411

>> 2^(-4)

ans = 0.0625

>> 1/(1 + 4/(5 + 1/5)

```
Error: Expression or statement is incorrect--possibly unbalanced (, {, or [.
```

We forgot a matching parenthesis when entering the continued fraction above. Using the up-arrow on the keyboard, we can easily recover the command, add the missing parenthesis at the end of the expression, and re-enter the command to get the correct answer.

>> 1/(1 + 4/(5 + 1/5))

ans = 0.5652

We can actually compute exactly what this continued fraction should be. Substracting the exact result from our original expression, we should expect to get zero :

>> 1/(1 + 4/(5 + 1/5)) - 13/23

ans = 1.1102e-16

Due to limited precision in the computer (we'll talk about this
more later), we don't get exactly 0, but a number very close to 0.

When using stacked exponents, the convention is to work in top down
order. So for example, the expression $2.1^{4.3^{2.1}}$ should be evaluated using
parenthesis as

>> 2.1^(4.3^2.1)

ans = 7.8240e+06

and not

>> (2.1^4.3)^2.1

ans = 812.1574

Back to the top

## Formatting output

One of the big differences between scientific computing and other branches of computer science is that scientific computing deals with floating point numbers to a much greater extent. One consequence of this is that the number of significant digits that appear in a result that we print out if very important. You may have noticed that for non-integer results that you obtained above, you have only seen four digits of precision printed after the decimal place. We might like to see the additional digits that Matlab is storing. To change Matlab's default behavior, use the format statement.

```
>> format long
1/3
```

ans = 0.333333333333333

>> 1/3000

ans = 3.333333333333333e-04

We can return to the default shortened format by using the short format option.

```
>> format short
1/3
```

ans = 0.3333

You can specify exponential notational with a trailing "e" for either the long or short versions of the format statement.

>> format long e 1/12

ans = 8.333333333333333e-02

>> format short e 1/12

ans = 8.3333e-02

**Note of things to come :** If you are familiar with the C/C++
print function 'printf' you might find the equivalent Matlab
function fprintf a more flexible way to
format output.

`>> fprintf('%16.8f\n',3/334)`

0.00898204

`>> fprintf('%16.8e\n',3/334)`

8.98203593e-03

We will be discussing this function in more detail in subsequent labs

Back to the top

## Elementary functions and predefined constants

Matlab has a large suite of elementary functions, including
the exponential function, the logarithm, and all trigonometric
functions.

To get help on these functions, you can use the `elfun` help
options.

>> help elfun Elementary math functions. Trigonometric. sin - Sine. sind - Sine of argument in degrees. sinh - Hyperbolic sine. asin - Inverse sine. asind - Inverse sine, result in degrees. asinh - Inverse hyperbolic sine. cos - Cosine. cosd - Cosine of argument in degrees. cosh - Hyperbolic cosine. acos - Inverse cosine. ...............

The trigonometric functions include the six standard functions
cos, sin,
tan, sec,
csc, and cot.

In addition, you can find all
of the inverse trigonometric functions acos,
asin, atan.
asec, acsc,
and acot.

Hyperbolic trigonometric functions cosh,
sinh, tanh,
acosh, asinh,
atanh and so on are also available.

Before starting with these elementary functions, however, it is
helpful to look at an important named constant available in
Matlab. This is the number pi.

```
>> format long
pi
```

ans = 3.141592653589793

This is obviously the value of `pi`, to 16 digits.

You can expect Matlab to behave in the same way as your
calculator when using these elementary functions. Below are some examples

>> cos(pi/2)

ans = 6.123233995736766e-17

>> sin(pi/2)

ans = 1

>> cos(3.1)^2 + sin(3.1)^2

ans = 1

>> tan(pi/2)

ans = 1.633123935319537e+16

Why is that last number so big?

It can be useful to use Matlab to verify trigonometric identities that
are easy to forget.

>> cos(3 + 5) - (cos(3)*cos(5) - sin(3)*sin(5))

ans = 0

whereas

>> cos(3 + 5) - (cos(3)*cos(5) + sin(3)*sin(5))

ans = 0.270646802738529

does not give the expected result of 0. The first expression appears to verify the (correct) cosine addition formula. Try this out with a few other values to convince yourself.

Exponential and logarithmic functions also behave as expected :

>> exp(pi)

ans = 23.140692632779267

>> log(exp(pi))

ans = 3.141592653589793

>> exp(log(pi))

ans = 3.141592653589793

>> log10(10^(-3))

ans = -3

>> log(4/7)-(log(4) - log(7))

ans = -1.110223024625157e-16

Note that the log is the logarithm base
e whereas log10
is the logarithm base **10**.

You may be wondering if **e** is another named constant in Matlab. It
is not, but it is easy to obtain by

>> exp(1)

ans = 2.718281828459046

We have already seen how we can raise one number to a power. We can of course use this to evaluate the square root of a number, or the cube root of a number. For example,

>> 5^(1/2)

ans = 2.236067977499790

>> 5^(0.5)

ans = 2.236067977499790

>> 11^(1/3)

ans = 2.223980090569315

>> 16^(1/3)

ans = 2.519842099789746

The square root is used so often that it has its own special function.

>> sqrt(5)

ans = 2.236067977499790

More generally, you can take the $n^{th}$ root of a value. For example the cube root of 5.1 as can be computed as

>> nthroot(5.1,3)

ans = 1.721300620726316

Or the fifth root of -56.3 as

>> nthroot(-56.3,5)

ans = -2.239245339355211

The nthroot function only returns at most one real-valued root of a number. If you request the even root of a negative number, nthroot will return an error. For example,

nthroot(-1,2)

```
Error using nthroot (line 32)
If X is negative, N must be an odd integer.
```

Back to the top

## Lab exercises

- $1 + 2(3 + 4^5)$
- $17 + 3/2016 + \frac{1}{4 - 2^5}$
- $5 + \frac{1}{3 + \frac{1}{4 + \frac{1}{12}}}$
- $(4.34 + 5.61)^{8.1}$
- $(3.1 \times 10^{12})(4.5 \times 10^{-2})$
- $\sqrt[3]{-1} \qquad \mbox{(use a '^')}$
- $\sqrt[3]{-1} \qquad \mbox{(use 'nthroot')}$
- $(10^2)^{1/2}$
- $10^{2^{1/2}}$
- $2.1^{{0.3}^{4.6}}$
- $5 + \frac{1}{2\sin(2)}$
- $(2+\sin(2.3))^{5\cos(5.6)}$
- $\ln(1/e)$
- $\left[\log_{10}(\sin(4.3) - \tan(1.1) + 5)\right]^{3.1^e}$
- $\cosh(\pi) - \frac{e^{\pi} + e^{-\pi}}{2}$
- $1+\tan^2(5.4) - \sec^2(5.4)$
- $\sqrt{\frac{16\tan^{-1}(1)^2}{\cos^2(\pi/2) - \sin^2(\pi/2)}}$
- $\cos^{-1}(-0.23)$
- $\cos(x) = 0.6, \qquad x = \mbox{??}$
- $\cos(46^\circ)$
- $\cos(\theta) = 123^\circ, \qquad \theta = \mbox{???}$
- $\log_5(11)$
- $(2 + 3i)(2 - 3i), \qquad \mbox{where $i= \sqrt{-1}$}$
- $\sin(2 + 3i) - \frac{e^{i(2 + 3i)} - e^{-i(2 + 3i)}}{2i}$
- $\log(-2)$
- $\mbox{Angle between the x-axis and the ray from (0,0) to (-2,3)}$

Compare your results with the solutions.

Back to the top

## Get the code

Do you want to try the above code fragments on your own? Download the Matlab script that produces this page here. (lab_1.m)

Published with MATLAB® 8.5