Back to tutorial index

Matlab as a graphing scientific calculator (Part I)

Topics in this lab


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 =


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.
    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 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 =


>> 12756
ans =


or as a comma separated list of values

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


ans =


ans =


ans =


ans =


ans =


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 =


ans =


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.


>> 2*33
ans =



>> 45.1/9
ans =



>> 21 + 100
ans =


and subtraction,

>> 10 - 22
ans =



>> 2^4
ans =


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 =


Here is an example that combines multiplication and division.

>> 25/5*4/2/5/2
ans =


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 =


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 =


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

>> 16*2^-2
ans =


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 =


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 =


>> 2^(-4)
ans =


>> 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 =


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 =


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 =


and not

>> (2.1^4.3)^2.1
ans =


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
ans =


>> 1/3000
ans =


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

>> format short
ans =


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

>> format long e
ans =


>> format short e
ans =


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)
>> fprintf('%16.8e\n',3/334)

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.
    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
ans =


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 =


>> sin(pi/2)
ans =


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


>> tan(pi/2)
ans =


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 =



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


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 =


>> log(exp(pi))
ans =


>> exp(log(pi))
ans =


>> log10(10^(-3))
ans =


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


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 =


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 =


>> 5^(0.5)
ans =


>> 11^(1/3)
ans =


>> 16^(1/3)
ans =


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

>> sqrt(5)
ans =


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 =


Or the fifth root of -56.3 as

>> nthroot(-56.3,5)
ans =


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,

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

Back to the top

Lab exercises

Evaluate the following expressions and compare to the true solutions (see link below).

  1. $1 + 2(3 + 4^5)$
  2. $17 + 3/2016 + \frac{1}{4 - 2^5}$
  3. $5 + \frac{1}{3 + \frac{1}{4 + \frac{1}{12}}}$
  4. $(4.34 + 5.61)^{8.1}$
  5. $(3.1 \times 10^{12})(4.5 \times 10^{-2})$
  6. $\sqrt[3]{-1} \qquad \mbox{(use a '^')}$
  7. $\sqrt[3]{-1} \qquad \mbox{(use 'nthroot')}$
  8. $(10^2)^{1/2}$
  9. $10^{2^{1/2}}$
  10. $2.1^{{0.3}^{4.6}}$
  11. $5 + \frac{1}{2\sin(2)}$
  12. $(2+\sin(2.3))^{5\cos(5.6)}$
  13. $\ln(1/e)$
  14. $\left[\log_{10}(\sin(4.3) - \tan(1.1) + 5)\right]^{3.1^e}$
  15. $\cosh(\pi) - \frac{e^{\pi} + e^{-\pi}}{2}$
  16. $1+\tan^2(5.4) - \sec^2(5.4)$
  17. $\sqrt{\frac{16\tan^{-1}(1)^2}{\cos^2(\pi/2) - \sin^2(\pi/2)}}$
  18. $\cos^{-1}(-0.23)$
  19. $\cos(x) = 0.6, \qquad x = \mbox{??}$
  20. $\cos(46^\circ)$
  21. $\cos(\theta) = 123^\circ, \qquad \theta = \mbox{???}$
  22. $\log_5(11)$
  23. $(2 + 3i)(2 - 3i), \qquad \mbox{where $i= \sqrt{-1}$}$
  24. $\sin(2 + 3i) - \frac{e^{i(2 + 3i)} - e^{-i(2 + 3i)}}{2i}$
  25. $\log(-2)$
  26. $\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)

Powered by MathJax

Published with MATLAB® 8.5